<?php
/**
 * Página de Produtos - MontaLoja Modern Theme
 * Exibe todos os produtos da loja com filtros e ordenação
 */

// Verificar se foi chamado corretamente
if (!defined('BARBERFLOW')) {
    die('Acesso negado');
}

// Variáveis esperadas: $store, $pdo, $currentStoreId, $storeName, $logo, $whatsapp, etc.

// Carregar contexto da loja
$store = $_SESSION['current_store'] ?? null;
$currentStoreId = defined('STORE_ID') ? STORE_ID : ($store['id'] ?? 0);
$storeName = defined('STORE_NAME') ? STORE_NAME : ($store['name'] ?? '');
$logo = defined('STORE_LOGO') ? STORE_LOGO : ($store['logo_url'] ?? '');
$whatsapp = defined('STORE_WHATSAPP') ? STORE_WHATSAPP : ($store['whatsapp_number'] ?? '');
$logoType = $store['logo_type'] ?? 'text';
$logoImage = $store['logo_url'] ?? '';
$logoText = $store['logo_text'] ?? ($storeName ?: 'Loja');

// Carregar template_settings (customSettings) do banco
$customSettings = [];
if (!empty($store['template_settings'])) {
    $customSettings = json_decode($store['template_settings'], true) ?? [];
} elseif (defined('STORE_ID')) {
    try {
        $settingsStmt = $pdo->prepare("SELECT template_settings FROM stores WHERE id = ?");
        $settingsStmt->execute([STORE_ID]);
        $settingsRow = $settingsStmt->fetch(PDO::FETCH_ASSOC);
        if (!empty($settingsRow['template_settings'])) {
            $customSettings = json_decode($settingsRow['template_settings'], true) ?? [];
            $store['template_settings'] = $settingsRow['template_settings'];
        }
    } catch (PDOException $e) {}
}

// Sobrescrever variveis do header com customSettings
if (!empty($customSettings['header'])) {
    $logoType = $customSettings['header']['logo_type'] ?? $logoType;
    $logoImage = $customSettings['header']['logo_image'] ?? $logoImage;
    $logoText = $customSettings['header']['logo_text'] ?? $logoText;
}

// Parâmetros de filtro e ordenação
$categoryFilter = $_GET['categoria'] ?? '';
$searchQuery = $_GET['busca'] ?? '';
$sortBy = $_GET['ordenar'] ?? 'recent';
$page = max(1, intval($_GET['pagina'] ?? 1));
$perPage = 12;
$offset = ($page - 1) * $perPage;

// Buscar categorias para o filtro
try {
    $categoriesStmt = $pdo->prepare("
        SELECT DISTINCT c.id, c.name, c.name as slug, COUNT(p.id) as product_count
        FROM categories c
        LEFT JOIN products p ON p.category_id = c.id AND p.store_id = ? AND p.is_active = 1
        WHERE c.store_id = ? AND c.is_active = 1
        GROUP BY c.id, c.name
        
        ORDER BY c.sort_order ASC, c.name ASC
    ");
    $categoriesStmt->execute([$currentStoreId, $currentStoreId]);
    $categories = $categoriesStmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    // Fallback: buscar categorias da coluna category dos produtos
    try {
        $categoriesStmt = $pdo->prepare("
            SELECT DISTINCT category as name, category as slug, COUNT(*) as product_count
            FROM products 
            WHERE store_id = ? AND is_active = 1 AND category IS NOT NULL AND category != ''
            GROUP BY category
            ORDER BY category ASC
        ");
        $categoriesStmt->execute([$currentStoreId]);
        $categories = $categoriesStmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        $categories = [];
    }
}

// Montar query de produtos
$whereClause = "WHERE p.store_id = ? AND p.is_active = 1";
$params = [$currentStoreId];

if (!empty($categoryFilter)) {
    $whereClause .= " AND p.category_id IN (SELECT id FROM categories WHERE name = ?)";
    $params[] = $categoryFilter;
}

if (!empty($searchQuery)) {
    $whereClause .= " AND (p.name LIKE ? OR p.description LIKE ?)";
    $params[] = "%{$searchQuery}%";
    $params[] = "%{$searchQuery}%";
}

// Ordenação
switch ($sortBy) {
    case 'price_asc':
        $orderBy = "ORDER BY p.price ASC";
        break;
    case 'price_desc':
        $orderBy = "ORDER BY p.price DESC";
        break;
    case 'name_asc':
        $orderBy = "ORDER BY p.name ASC";
        break;
    case 'name_desc':
        $orderBy = "ORDER BY p.name DESC";
        break;
    case 'popular':
        $orderBy = "ORDER BY p.views DESC, p.id DESC";
        break;
    case 'recent':
    default:
        $orderBy = "ORDER BY p.id DESC";
        break;
}

// Contar total de produtos
try {
    $countStmt = $pdo->prepare("SELECT COUNT(*) FROM products p {$whereClause}");
    $countStmt->execute($params);
    $totalProducts = $countStmt->fetchColumn();
    $totalPages = ceil($totalProducts / $perPage);
} catch (PDOException $e) {
    $totalProducts = 0;
    $totalPages = 1;
}

// Total de TODOS os produtos (sem filtro de categoria)
try {
    $allCountStmt = $pdo->prepare("SELECT COUNT(*) FROM products p WHERE p.store_id = ? AND p.is_active = 1");
    $allCountStmt->execute([$currentStoreId]);
    $totalAllProducts = $allCountStmt->fetchColumn();
} catch (PDOException $e) {
    $totalAllProducts = $totalProducts;
}

// Buscar produtos
try {
    $productsStmt = $pdo->prepare("
        SELECT p.*, 
               COALESCE(rv.avg_rating, 0) as avg_rating,
               COALESCE(rv.total_reviews, 0) as total_reviews
        FROM products p
        LEFT JOIN (
            SELECT product_id, AVG(rating) as avg_rating, COUNT(*) as total_reviews 
            FROM product_reviews 
            WHERE is_approved = 1 
            GROUP BY product_id
        ) rv ON p.id = rv.product_id
        {$whereClause}
        {$orderBy}
        LIMIT {$perPage} OFFSET {$offset}
    ");
    $productsStmt->execute($params);
    $products = $productsStmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $products = [];
}
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Produtos - <?php echo htmlspecialchars($storeName); ?></title>
<meta name="description" content="Confira todos os produtos de <?php echo htmlspecialchars($storeName); ?>. <?php echo $totalProducts; ?> produtos disponíveis.">
<meta name="theme-color" content="#ffffff">
<?php if (!empty($faviconUrl)): ?>
<link rel="icon" type="image/png" href="<?php echo htmlspecialchars($faviconUrl); ?>?v=<?php echo time(); ?>">
<link rel="shortcut icon" type="image/png" href="<?php echo htmlspecialchars($faviconUrl); ?>?v=<?php echo time(); ?>">
<?php endif; ?>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/iconify-icon@1.0.7/dist/iconify-icon.min.js"></script>
<link rel="stylesheet" href="/pages/storefront/templates/retail/modern/includes/styles.css?v=1.0.9">
<?php include __DIR__ . "/includes/dynamic-styles.php"; ?>
<?php
// Detectar se é tema escuro baseado na cor de fundo
$bgHex = $bgColor ?? '#FAFBFC';
$bgR = hexdec(substr($bgHex, 1, 2));
$bgG = hexdec(substr($bgHex, 3, 2));
$bgB = hexdec(substr($bgHex, 5, 2));
$bgLuminance = ($bgR * 0.299 + $bgG * 0.587 + $bgB * 0.114);
$isDarkTheme = $bgLuminance < 128;

if ($isDarkTheme) {
    $borderColor = 'rgba(255,255,255,0.12)';
    $borderLight = 'rgba(255,255,255,0.08)';
    $mutedColor = '#808080';
    $shadowSm = '0 1px 2px rgba(0,0,0,0.3)';
    $shadowMd = '0 4px 12px rgba(0,0,0,0.4)';
    $shadowLg = '0 12px 40px rgba(0,0,0,0.5)';
    $surfaceHover = 'rgba(255,255,255,0.05)';
} else {
    $borderColor = '#E5E7EB';
    $borderLight = '#F3F4F6';
    $mutedColor = '#9CA3AF';
    $shadowSm = '0 1px 2px rgba(0,0,0,0.04)';
    $shadowMd = '0 4px 12px rgba(0,0,0,0.05)';
    $shadowLg = '0 12px 40px rgba(0,0,0,0.08)';
    $surfaceHover = '#F8F9FA';
}
?>
<style>

/* Page Container */
.products-page {
    min-height: 100vh;
}

.products-container {
    max-width: 1400px;
    margin: 0 auto;
    padding: 2rem 1.5rem;
}

/* Page Header */
.page-header {
    margin-bottom: 2rem;
}

.page-breadcrumb {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    font-size: 0.875rem;
    color: var(--text-secondary);
    margin-bottom: 1rem;
}

.page-breadcrumb a {
    color: var(--text-secondary);
    text-decoration: none;
    transition: color 0.2s;
}

.page-breadcrumb a:hover {
    color: var(--primary);
}

.page-title {
    font-size: 2rem;
    font-weight: 800;
    color: var(--text);
    margin-bottom: 0.5rem;
}

.page-subtitle {
    color: var(--text-secondary);
    font-size: 1rem;
}

/* Filters Bar */
.filters-bar {
    display: flex;
    flex-wrap: wrap;
    gap: 1rem;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 2rem;
    padding: 1rem 1.5rem;
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: 16px;
}

.filters-left {
    display: flex;
    flex-wrap: wrap;
    gap: 0.75rem;
    align-items: center;
}

.filter-btn {
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.625rem 1rem;
    background: var(--bg);
    border: 1px solid var(--border);
    border-radius: 50px;
    font-size: 0.875rem;
    font-weight: 500;
    color: var(--text);
    cursor: pointer;
    transition: all 0.2s;
}

.filter-btn:hover {
    border-color: var(--primary);
    color: var(--primary);
}

.filter-btn.active {
    background: var(--primary);
    border-color: var(--primary);
    color: white;
}

.filter-btn iconify-icon {
    font-size: 1.1rem;
}

.filters-right {
    display: flex;
    align-items: center;
    gap: 1rem;
}

.sort-select {
    padding: 0.625rem 2.5rem 0.625rem 1rem;
    background: var(--bg);
    border: 1px solid var(--border);
    border-radius: 10px;
    font-size: 0.875rem;
    font-weight: 500;
    color: var(--text);
    cursor: pointer;
    appearance: none;
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24'%3E%3Cpath fill='%236B7280' d='M7 10l5 5 5-5z'/%3E%3C/svg%3E");
    background-repeat: no-repeat;
    background-position: right 0.75rem center;
}

.view-toggle {
    display: flex;
    gap: 0.25rem;
    padding: 0.25rem;
    background: var(--bg);
    border-radius: 10px;
}

.view-btn {
    padding: 0.5rem;
    background: transparent;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    color: var(--text-secondary);
    transition: all 0.2s;
}

.view-btn:hover, .view-btn.active {
    background: var(--surface);
    color: var(--primary);
}

.view-btn iconify-icon {
    font-size: 1.25rem;
}

/* Search Bar */
.search-filter {
    position: relative;
    flex: 1;
    max-width: 300px;
}

.search-filter input {
    width: 100%;
    padding: 0.625rem 1rem 0.625rem 2.5rem;
    background: var(--bg);
    border: 1px solid var(--border);
    border-radius: 10px;
    font-size: 0.875rem;
    color: var(--text);
}

.search-filter input:focus {
    outline: none;
    border-color: var(--primary);
}

.search-filter iconify-icon {
    position: absolute;
    left: 0.875rem;
    top: 50%;
    transform: translateY(-50%);
    color: var(--text-secondary);
}

/* Categories Sidebar */
.products-layout {
    display: grid;
    grid-template-columns: 250px 1fr;
    gap: 2rem;
}

.categories-sidebar {
    position: sticky;
    top: 100px;
    height: fit-content;
}

.sidebar-card {
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: 16px;
    padding: 1.25rem;
}

.sidebar-title {
    font-size: 1rem;
    font-weight: 700;
    color: var(--text);
    margin-bottom: 1rem;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.sidebar-title iconify-icon {
    color: var(--primary);
}

.category-list {
    list-style: none;
    padding: 0;
    margin: 0;
}

.category-item {
    margin-bottom: 0.25rem;
}

.category-link {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0.75rem 1rem;
    color: var(--text);
    text-decoration: none;
    border-radius: 10px;
    font-size: 0.9rem;
    font-weight: 500;
    transition: all 0.2s;
}

.category-link:hover {
    background: var(--surface-hover);
    color: var(--primary);
}

.category-link.active {
    background: var(--primary-soft);
    color: var(--primary);
}

.category-count {
    font-size: 0.8rem;
    color: var(--text-secondary);
    background: var(--bg);
    padding: 0.25rem 0.5rem;
    border-radius: 20px;
}

/* Products Grid */
.products-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
    gap: 1.5rem;
}

.products-grid.list-view {
    grid-template-columns: 1fr;
}
.products-grid.list-view .product-card {
    display: flex;
    flex-direction: row;
    max-height: 180px;
}
.products-grid.list-view .product-image {
    width: 180px;
    min-width: 180px;
    aspect-ratio: 1;
    flex-shrink: 0;
}
.products-grid.list-view .product-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    padding: 1rem 1.5rem;
}
.products-grid.list-view .product-footer {
    margin-top: 0.5rem;
}
.products-grid.list-view .product-name {
    font-size: 1.1rem;
}
.products-grid.list-view .product-wishlist {
    top: 8px;
    right: 8px;
}
.products-grid.list-view .product-badge {
    top: 8px;
    left: 8px;
}

/* Product Card */
.product-card {
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: 16px;
    overflow: hidden;
    transition: all 0.3s;
    position: relative;
}

.product-card:hover {
    transform: translateY(-4px);
    box-shadow: var(--shadow-lg);
    border-color: var(--primary);
}

.product-image {
    position: relative;
    aspect-ratio: 1;
    overflow: hidden;
    background: var(--bg);
}

.product-image img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: transform 0.3s;
}

.product-card:hover .product-image img {
    transform: scale(1.05);
}

.product-badges {
    position: absolute;
    top: 0.75rem;
    left: 0.75rem;
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
}

.badge {
    padding: 0.35rem 0.75rem;
    border-radius: 20px;
    font-size: 0.7rem;
    font-weight: 700;
    text-transform: uppercase;
}

.badge-sale {
    background: #EF4444;
    color: white;
}

.badge-new {
    background: var(--accent);
    color: white;
}

.product-actions {
    position: absolute;
    top: 0.75rem;
    right: 0.75rem;
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
    opacity: 0;
    transform: translateX(10px);
    transition: all 0.3s;
}

.product-card:hover .product-actions {
    opacity: 1;
    transform: translateX(0);
}

.action-btn-sm {
    width: 36px;
    height: 36px;
    border-radius: 50%;
    background: var(--surface);
    border: 1px solid var(--border);
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.2s;
    color: var(--text);
}

.action-btn-sm:hover {
    background: var(--primary);
    border-color: var(--primary);
    color: white;
}

.action-btn-sm.favorited {
    background: #FEE2E2;
    border-color: #FEE2E2;
    color: #EF4444;
}

.product-info {
    padding: 1rem;
}

.product-category {
    font-size: 0.75rem;
    color: var(--primary);
    font-weight: 600;
    text-transform: uppercase;
    margin-bottom: 0.5rem;
}

/* Product Rating */
.product-rating { display: flex; align-items: center; gap: 2px; margin-bottom: 8px; }
.product-rating iconify-icon { font-size: 0.9rem; color: #fbbf24; }
.product-rating iconify-icon[icon="solar:star-outline"] { color: #d1d5db; }
.product-rating span { font-size: 0.8rem; color: #6b7280; margin-left: 4px; }

.product-name {
    font-size: 0.95rem;
    font-weight: 600;
    color: var(--text);
    margin-bottom: 0.75rem;
    line-height: 1.4;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}

.product-name a {
    color: inherit;
    text-decoration: none;
}

.product-name a:hover {
    color: var(--primary);
}

.product-price {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    margin-bottom: 1rem;
}

.price-current {
    font-size: 1.25rem;
    font-weight: 800;
    color: var(--primary);
}

.price-original {
    font-size: 0.875rem;
    color: var(--text-secondary);
    text-decoration: line-through;
}

.add-to-cart-btn {
    width: 100%;
    padding: 0.75rem;
    background: var(--primary);
    border: none;
    border-radius: 10px;
    color: white;
    font-weight: 600;
    font-size: 0.875rem;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 0.5rem;
    transition: all 0.2s;
}

.add-to-cart-btn:hover {
    background: var(--primary-hover);
    transform: scale(1.02);
}

/* Empty State */
.empty-state {
    text-align: center;
    padding: 4rem 2rem;
    grid-column: 1 / -1;
}

.empty-icon {
    font-size: 4rem;
    color: var(--text-secondary);
    margin-bottom: 1rem;
}

.empty-title {
    font-size: 1.25rem;
    font-weight: 700;
    color: var(--text);
    margin-bottom: 0.5rem;
}

.empty-text {
    color: var(--text-secondary);
    margin-bottom: 1.5rem;
}

/* Pagination */
.pagination {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 0.5rem;
    margin-top: 3rem;
    padding-top: 2rem;
    border-top: 1px solid var(--border);
}

.page-btn {
    min-width: 40px;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 0.75rem;
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: 10px;
    color: var(--text);
    font-weight: 500;
    text-decoration: none;
    transition: all 0.2s;
}

.page-btn:hover {
    border-color: var(--primary);
    color: var(--primary);
}

.page-btn.active {
    background: var(--primary);
    border-color: var(--primary);
    color: white;
}

.page-btn.disabled {
    opacity: 0.5;
    pointer-events: none;
}

/* Responsive */
@media (max-width: 1024px) {
    .products-layout {
        grid-template-columns: 1fr;
    }

    .categories-sidebar {
        display: none;
    }

    .mobile-categories {
        display: flex !important;
    }
}

@media (max-width: 768px) {
    .products-container {
        padding: 1rem;
    }

    .page-title {
        font-size: 1.5rem;
    }

    .filters-bar {
        flex-direction: column;
        align-items: stretch;
    }

    .filters-left {
        overflow-x: auto;
        padding-bottom: 0.5rem;
        flex-wrap: nowrap;
    }

    .filters-right {
        justify-content: space-between;
    }

    .search-filter {
        max-width: 100%;
        order: -1;
        width: 100%;
    }

    .products-grid {
        grid-template-columns: repeat(2, 1fr);
        gap: 1rem;
    }
}

@media (max-width: 480px) {
    .products-grid {
        grid-template-columns: 1fr;
    }
}

/* Mobile Categories (Hidden on Desktop) */
.mobile-categories {
    display: none;
    overflow-x: auto;
    gap: 0.5rem;
    padding-bottom: 0.5rem;
    margin-bottom: 1rem;
    -webkit-overflow-scrolling: touch;
}

.mobile-categories::-webkit-scrollbar {
    display: none;
}
/* Card Estilo Home */
.product-wishlist { position: absolute; top: 12px; right: 12px; width: 36px; height: 36px; border-radius: 50%; background: rgba(255,255,255,0.9); border: none; cursor: pointer; display: flex; align-items: center; justify-content: center; transition: all 0.2s; z-index: 2; }
.product-wishlist:hover { background: #fff; transform: scale(1.1); }
.product-footer { display: flex; align-items: center; justify-content: space-between; margin-top: auto; }
.price-old { text-decoration: line-through; color: var(--text-secondary); font-size: 0.85rem; margin-right: 0.5rem; }
.btn-add-cart { width: 40px; height: 40px; border-radius: 50%; background: var(--primary); color: #fff; border: none; cursor: pointer; display: flex; align-items: center; justify-content: center; transition: all 0.2s; }
.btn-add-cart:hover { transform: scale(1.1); }
.product-placeholder { width: 100%; height: 100%; background: var(--bg); display: flex; align-items: center; justify-content: center; }
.product-badge { position: absolute; top: 12px; left: 12px; background: #ef4444; color: #fff; padding: 4px 10px; border-radius: 4px; font-size: 0.75rem; font-weight: 600; z-index: 2; }
article.product-card { cursor: pointer; }
</style>
</head>
<body>

<?php
    // Configurações do cabeçalho
    // Configurações do cabeçalho - usar customSettings se disponível
    $headerSettings = $customSettings['header'] ?? [
        'logo_type' => 'text',
        'logo_text' => $storeName,
        'logo_image' => $logo,
        'show_search' => true,
        'show_cart' => true,
        'show_wishlist' => true,
        'sticky' => true
    ];

    $logoType = $headerSettings['logo_type'] ?? 'text';
    $logoImage = $headerSettings['logo_image'] ?? $logo;
    $logoText = $headerSettings['logo_text'] ?? $storeName;
    $storeSlug = $store['slug'] ?? '';

    // Detectar URL base
    $currentHost = $_SERVER['HTTP_HOST'] ?? '';
    $isLojaPathAccess = strpos($_SERVER['REQUEST_URI'] ?? '', '/loja/') !== false;

    if (!isset($baseUrl) || empty($baseUrl)) {
        if (function_exists('get_store_url') && !empty($store)) {
            $baseUrl = get_store_url($store);
        } elseif ($isLojaPathAccess) {
            $baseUrl = '/loja/' . ($store['slug'] ?? '');
        } else {
            $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https://' : 'http://';
            $baseUrl = $protocol . $currentHost;
        }
    }

    // Menu dinâmico - Itens fixos SEMPRE aparecem primeiro
    // Itens fixos que SEMPRE aparecem (Início e Produtos)
    $fixedMenuItems = [
        ['id' => 1, 'name' => 'Início', 'link' => $baseUrl, 'icon' => 'solar:home-2-bold'],
        ['id' => 2, 'name' => 'Produtos', 'link' => $baseUrl . '/produtos', 'icon' => 'solar:bag-3-bold'],
    ];
    
    // Itens customizáveis - filtrar Início e Produtos
    $savedMenuItems = $customSettings['menu'] ?? [];
    $customMenuItems = [];
    if (!empty($savedMenuItems)) {
        foreach ($savedMenuItems as $item) {
            $itemName = strtolower(trim($item['name'] ?? ''));
            if (!in_array($itemName, ['início', 'inicio', 'produtos', 'home', 'products'])) {
                $customMenuItems[] = $item;
            }
        }
    }
    if (empty($customMenuItems)) {
        $customMenuItems = [
            ['id' => 3, 'name' => 'Categorias', 'link' => $baseUrl . '#categorias', 'icon' => 'solar:widget-4-bold'],
            ['id' => 4, 'name' => 'Contato', 'link' => $baseUrl . '#contato', 'icon' => 'solar:phone-bold']
        ];
    }
    $menuItems = array_merge($fixedMenuItems, $customMenuItems);
    // Corrigir links relativos do menu
    foreach ($menuItems as &$item) {
        $link = $item['link'] ?? '';
        if (strpos($link, '#') === 0) {
            $item['link'] = $baseUrl . $link;
        }
    }
    unset($item);
?>

<?php include __DIR__ . '/../../../includes/cart.php'; ?>

<?php include __DIR__ . '/includes/header.php'; ?>

<main class="products-page">
    <!-- Page Header Banner -->
    <section class="page-header-banner">
        <div class="page-header-content">
            <nav class="page-breadcrumb">
                <a href="<?php echo htmlspecialchars($baseUrl); ?>">Início</a>
                <iconify-icon icon="solar:alt-arrow-right-linear"></iconify-icon>
                <span>Produtos</span>
                <?php if (!empty($categoryFilter)): ?>
                <iconify-icon icon="solar:alt-arrow-right-linear"></iconify-icon>
                <span><?php echo htmlspecialchars($categoryFilter); ?></span>
                <?php endif; ?>
            </nav>
            <h1 class="page-header-title">
                <?php if (!empty($categoryFilter)): ?>
                    <?php echo htmlspecialchars($categoryFilter); ?>
                <?php elseif (!empty($searchQuery)): ?>
                    Resultados para "<?php echo htmlspecialchars($searchQuery); ?>"
                <?php else: ?>
                    Todos os Produtos
                <?php endif; ?>
            </h1>
            <p class="page-header-subtitle"><?php echo $totalProducts; ?> produto<?php echo $totalProducts != 1 ? 's' : ''; ?> encontrado<?php echo $totalProducts != 1 ? 's' : ''; ?></p>
        </div>
    </section>

    <div class="products-container">
        <!-- Filters Bar -->
        <div class="filters-bar">
            <div class="filters-left">
                <div class="search-filter">
                    <iconify-icon icon="solar:magnifer-bold"></iconify-icon>
                    <form method="GET" action="">
                        <input type="text" name="busca" placeholder="Buscar produtos..." value="<?php echo htmlspecialchars($searchQuery); ?>">
                        <?php if (!empty($categoryFilter)): ?>
                        <input type="hidden" name="categoria" value="<?php echo htmlspecialchars($categoryFilter); ?>">
                        <?php endif; ?>
                    </form>
                </div>

                <!-- Mobile Categories -->
                <div class="mobile-categories">
                    <a href="?<?php echo !empty($searchQuery) ? 'busca=' . urlencode($searchQuery) : ''; ?>" 
                       class="filter-btn <?php echo empty($categoryFilter) ? 'active' : ''; ?>">
                        Todos
                    </a>
                    <?php foreach ($categories as $cat): ?>
                    <a href="?categoria=<?php echo urlencode($cat['name'] ?? $cat['slug'] ?? ''); ?><?php echo !empty($searchQuery) ? '&busca=' . urlencode($searchQuery) : ''; ?>" 
                       class="filter-btn <?php echo $categoryFilter === ($cat['name'] ?? $cat['slug'] ?? '') ? 'active' : ''; ?>">
                        <?php echo htmlspecialchars($cat['name'] ?? ''); ?>
                    </a>
                    <?php endforeach; ?>
                </div>
            </div>

            <div class="filters-right">
                <select class="sort-select" onchange="window.location.href=this.value">
                    <option value="?ordenar=recent<?php echo !empty($categoryFilter) ? '&categoria=' . urlencode($categoryFilter) : ''; ?><?php echo !empty($searchQuery) ? '&busca=' . urlencode($searchQuery) : ''; ?>" <?php echo $sortBy === 'recent' ? 'selected' : ''; ?>>Mais Recentes</option>
                    <option value="?ordenar=price_asc<?php echo !empty($categoryFilter) ? '&categoria=' . urlencode($categoryFilter) : ''; ?><?php echo !empty($searchQuery) ? '&busca=' . urlencode($searchQuery) : ''; ?>" <?php echo $sortBy === 'price_asc' ? 'selected' : ''; ?>>Menor Preço</option>
                    <option value="?ordenar=price_desc<?php echo !empty($categoryFilter) ? '&categoria=' . urlencode($categoryFilter) : ''; ?><?php echo !empty($searchQuery) ? '&busca=' . urlencode($searchQuery) : ''; ?>" <?php echo $sortBy === 'price_desc' ? 'selected' : ''; ?>>Maior Preço</option>
                    <option value="?ordenar=name_asc<?php echo !empty($categoryFilter) ? '&categoria=' . urlencode($categoryFilter) : ''; ?><?php echo !empty($searchQuery) ? '&busca=' . urlencode($searchQuery) : ''; ?>" <?php echo $sortBy === 'name_asc' ? 'selected' : ''; ?>>A-Z</option>
                    <option value="?ordenar=name_desc<?php echo !empty($categoryFilter) ? '&categoria=' . urlencode($categoryFilter) : ''; ?><?php echo !empty($searchQuery) ? '&busca=' . urlencode($searchQuery) : ''; ?>" <?php echo $sortBy === 'name_desc' ? 'selected' : ''; ?>>Z-A</option>
                </select>

                <div class="view-toggle">
                    <button class="view-btn active" onclick="setView('grid')" title="Grade">
                        <iconify-icon icon="solar:widget-bold"></iconify-icon>
                    </button>
                    <button class="view-btn" onclick="setView('list')" title="Lista">
                        <iconify-icon icon="solar:list-bold"></iconify-icon>
                    </button>
                </div>
            </div>
        </div>

        <!-- Products Layout -->
        <div class="products-layout">
            
            <!-- Categories Sidebar (Desktop) -->
            <aside class="categories-sidebar">
                <div class="sidebar-card">
                    <h3 class="sidebar-title">
                        <iconify-icon icon="solar:folder-bold"></iconify-icon>
                        Categorias
                    </h3>
                    <ul class="category-list">
                        <li class="category-item">
                            <a href="?<?php echo !empty($searchQuery) ? 'busca=' . urlencode($searchQuery) : ''; ?>" 
                               class="category-link <?php echo empty($categoryFilter) ? 'active' : ''; ?>">
                                Todos os Produtos
                                <span class="category-count"><?php echo $totalAllProducts; ?></span>
                            </a>
                        </li>
                        <?php foreach ($categories as $cat): ?>
                        <li class="category-item">
                            <a href="?categoria=<?php echo urlencode($cat['name'] ?? $cat['slug'] ?? ''); ?><?php echo !empty($searchQuery) ? '&busca=' . urlencode($searchQuery) : ''; ?>" 
                               class="category-link <?php echo $categoryFilter === ($cat['name'] ?? $cat['slug'] ?? '') ? 'active' : ''; ?>">
                                <?php echo htmlspecialchars($cat['name'] ?? ''); ?>
                                <span class="category-count"><?php echo $cat['product_count'] ?? 0; ?></span>
                            </a>
                        </li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            </aside>

            <!-- Products Grid -->
            <div class="products-main">
                <?php if (empty($products)): ?>
                <div class="empty-state">
                    <iconify-icon icon="solar:bag-cross-bold" class="empty-icon"></iconify-icon>
                    <h3 class="empty-title">Nenhum produto encontrado</h3>
                    <p class="empty-text">Tente ajustar os filtros ou fazer uma nova busca.</p>
                    <a href="<?php echo htmlspecialchars($baseUrl); ?>/produtos" class="add-to-cart-btn" style="width: auto; display: inline-flex;">
                        <iconify-icon icon="solar:refresh-bold"></iconify-icon>
                        Ver Todos os Produtos
                    </a>
                </div>
                <?php else: ?>
                <div class="products-grid" id="productsGrid">
                    <?php foreach ($products as $product): 
                        $productImage = !empty($product['image_url']) ? $product['image_url'] : '';
                        $productPrice = floatval($product['price'] ?? 0);
                        $productOriginalPrice = floatval($product['original_price'] ?? $product['compare_price'] ?? 0);
                        $hasDiscount = $productOriginalPrice > $productPrice;
                        $discountPercent = $hasDiscount ? round((1 - $productPrice / $productOriginalPrice) * 100) : 0;
                        $productSlug = $product['slug'] ?? $product['id'];
                    ?>
                    <article class="product-card" onclick="window.location.href='<?php echo htmlspecialchars($baseUrl); ?>/produto/<?php echo htmlspecialchars($productSlug); ?>'" style="cursor:pointer">
                        <div class="product-image">
                            <?php if (!empty($productImage)): ?>
                                <img src="<?php echo htmlspecialchars($productImage); ?>" alt="<?php echo htmlspecialchars($product['name']); ?>" loading="lazy">
                            <?php else: ?>
                                <div class="product-placeholder"></div>
                            <?php endif; ?>
                            <?php if ($hasDiscount): ?>
                            <span class="product-badge">-<?php echo $discountPercent; ?>%</span>
                            <?php endif; ?>
                            <button class="product-wishlist" onclick="event.stopPropagation(); toggleFavorite(<?php echo $product['id']; ?>, this)" title="Favoritar">
                                <iconify-icon icon="solar:heart-outline" style="font-size: 1.1rem;"></iconify-icon>
                            </button>
                        </div>
                        <div class="product-info">
                            <?php if (!empty($product['category_name'])): ?>
                            <div class="product-category"><?php echo htmlspecialchars($product['category_name']); ?></div>
                            <?php endif; ?>
                            <h3 class="product-name"><?php echo htmlspecialchars($product['name']); ?></h3>
                            <div class="product-rating">
                                <?php 
                                $avgR = floatval($product['avg_rating'] ?? 0);
                                for ($star = 1; $star <= 5; $star++): 
                                ?>
                                <iconify-icon icon="<?php echo $star <= round($avgR) ? 'solar:star-bold' : 'solar:star-outline'; ?>"></iconify-icon>
                                <?php endfor; ?>
                                <span>(<?php echo number_format($avgR, 1); ?>)</span>
                            </div>
                            <div class="product-footer">
                                <div class="product-price">
                                    <?php if ($hasDiscount): ?>
                                    <span class="price-old">R$ <?php echo number_format($productOriginalPrice, 2, ',', '.'); ?></span>
                                    <?php endif; ?>
                                    <span class="price-current">R$ <?php echo number_format($productPrice, 2, ',', '.'); ?></span>
                                </div>
                                <button class="btn-add-cart" onclick="event.stopPropagation(); addToCart(<?php echo $product['id']; ?>, '<?php echo htmlspecialchars(addslashes($product['name'])); ?>', <?php echo $productPrice; ?>, '<?php echo htmlspecialchars($productImage); ?>')" title="Adicionar ao carrinho">
                                    <iconify-icon icon="solar:cart-plus-bold" style="font-size: 1.2rem;"></iconify-icon>
                                </button>
                            </div>
                        </div>
                    </article>
                    <?php endforeach; ?>
                </div>

                <!-- Pagination -->
                <?php if ($totalPages > 1): ?>
                <nav class="pagination">
                    <?php if ($page > 1): ?>
                    <a href="?pagina=<?php echo $page - 1; ?><?php echo !empty($categoryFilter) ? '&categoria=' . urlencode($categoryFilter) : ''; ?><?php echo !empty($searchQuery) ? '&busca=' . urlencode($searchQuery) : ''; ?><?php echo !empty($sortBy) ? '&ordenar=' . urlencode($sortBy) : ''; ?>" class="page-btn">
                        <iconify-icon icon="solar:alt-arrow-left-bold"></iconify-icon>
                    </a>
                    <?php endif; ?>

                    <?php
                    $startPage = max(1, $page - 2);
                    $endPage = min($totalPages, $page + 2);
                    
                    if ($startPage > 1): ?>
                    <a href="?pagina=1<?php echo !empty($categoryFilter) ? '&categoria=' . urlencode($categoryFilter) : ''; ?><?php echo !empty($searchQuery) ? '&busca=' . urlencode($searchQuery) : ''; ?><?php echo !empty($sortBy) ? '&ordenar=' . urlencode($sortBy) : ''; ?>" class="page-btn">1</a>
                    <?php if ($startPage > 2): ?>
                    <span class="page-btn disabled">...</span>
                    <?php endif; ?>
                    <?php endif; ?>

                    <?php for ($i = $startPage; $i <= $endPage; $i++): ?>
                    <a href="?pagina=<?php echo $i; ?><?php echo !empty($categoryFilter) ? '&categoria=' . urlencode($categoryFilter) : ''; ?><?php echo !empty($searchQuery) ? '&busca=' . urlencode($searchQuery) : ''; ?><?php echo !empty($sortBy) ? '&ordenar=' . urlencode($sortBy) : ''; ?>" 
                       class="page-btn <?php echo $i === $page ? 'active' : ''; ?>">
                        <?php echo $i; ?>
                    </a>
                    <?php endfor; ?>

                    <?php if ($endPage < $totalPages): ?>
                    <?php if ($endPage < $totalPages - 1): ?>
                    <span class="page-btn disabled">...</span>
                    <?php endif; ?>
                    <a href="?pagina=<?php echo $totalPages; ?><?php echo !empty($categoryFilter) ? '&categoria=' . urlencode($categoryFilter) : ''; ?><?php echo !empty($searchQuery) ? '&busca=' . urlencode($searchQuery) : ''; ?><?php echo !empty($sortBy) ? '&ordenar=' . urlencode($sortBy) : ''; ?>" class="page-btn"><?php echo $totalPages; ?></a>
                    <?php endif; ?>

                    <?php if ($page < $totalPages): ?>
                    <a href="?pagina=<?php echo $page + 1; ?><?php echo !empty($categoryFilter) ? '&categoria=' . urlencode($categoryFilter) : ''; ?><?php echo !empty($searchQuery) ? '&busca=' . urlencode($searchQuery) : ''; ?><?php echo !empty($sortBy) ? '&ordenar=' . urlencode($sortBy) : ''; ?>" class="page-btn">
                        <iconify-icon icon="solar:alt-arrow-right-bold"></iconify-icon>
                    </a>
                    <?php endif; ?>
                </nav>
                <?php endif; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
</main>

<?php include __DIR__ . '/includes/footer.php'; ?>
<script>
// Alternar visualização grade/lista
function setView(view) {
    const grid = document.getElementById('productsGrid');
    const btns = document.querySelectorAll('.view-btn');
    
    btns.forEach(btn => btn.classList.remove('active'));
    event.target.closest('.view-btn').classList.add('active');
    
    if (view === 'list') {
        grid.classList.add('list-view');
    } else {
        grid.classList.remove('list-view');
    }
    
    localStorage.setItem('productsView', view);
}

// Restaurar visualização salva
document.addEventListener('DOMContentLoaded', function() {
    const savedView = localStorage.getItem('productsView');
    if (savedView === 'list') {
        setView('list');
    }
});

// Favoritos
const storeSlug = '<?php echo htmlspecialchars($storeSlug ?? $store["slug"] ?? ""); ?>';
const favoritesKey = `montaloja_favorites_${storeSlug}`;

function toggleFavorite(productId, button) {
    let favorites = JSON.parse(localStorage.getItem(favoritesKey) || '[]');
    const index = favorites.indexOf(productId);
    
    if (index > -1) {
        favorites.splice(index, 1);
        button.classList.remove('favorited');
        button.querySelector('iconify-icon').setAttribute('icon', 'solar:heart-outline');
    } else {
        favorites.push(productId);
        button.classList.add('favorited');
        button.querySelector('iconify-icon').setAttribute('icon', 'solar:heart-bold');
    }
    
    localStorage.setItem(favoritesKey, JSON.stringify(favorites));
    
    if (typeof updateWishlistBadge === 'function') {
        updateWishlistBadge();
    }
}

// Verificar favoritos ao carregar
document.addEventListener('DOMContentLoaded', function() {
    const favorites = JSON.parse(localStorage.getItem(favoritesKey) || '[]');
    document.querySelectorAll('.action-btn-sm[onclick^="toggleFavorite"]').forEach(btn => {
        const onclick = btn.getAttribute('onclick');
        const match = onclick.match(/toggleFavorite\((\d+)/);
        if (match) {
            const productId = parseInt(match[1]);
            if (favorites.includes(productId)) {
                btn.classList.add('favorited');
                btn.querySelector('iconify-icon').setAttribute('icon', 'solar:heart-bold');
            }
        }
    });
});
</script>

</body>
</html>
