<?php
$idParceiro = isset($_GET['id']) ? (string)$_GET['id'] : '';

// Carregamento de dados reais
$base_path = __DIR__ . '/data/';
$parceiros_file = $base_path . 'parceiros.json';
$produtos_file  = $base_path . 'produtos.json';

$parceiros = file_exists($parceiros_file) ? json_decode(file_get_contents($parceiros_file), true) : [];
$produtos  = file_exists($produtos_file) ? json_decode(file_get_contents($produtos_file), true) : [];

$parceiro = null;
foreach($parceiros as $p){
    if((string)$p['id'] === $idParceiro){
        $parceiro = $p;
        break;
    }
}

// Fallback seguro
if(!$parceiro) {
    $parceiro = [
        'nome' => 'Loja Parceira',
        'logo' => '',
        'cor_primaria' => '#2563eb'
    ];
}

$produtosParceiro = array_filter($produtos, fn($p)=>
    (string)($p['id_parceiro'] ?? '') === $idParceiro && ($p['status'] ?? '') === 'ativo'
);

// Categorias para o filtro
$categorias = array_unique(array_filter(array_column($produtosParceiro, 'categoria')));
sort($categorias);
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?= htmlspecialchars($parceiro['nome']) ?></title>
    
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.css"/>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="https://unpkg.com/@phosphor-icons/web"></script>

    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '<?= $parceiro['cor_primaria'] ?? "#2563eb" ?>',
                    },
                    fontFamily: {
                        sans: ['Inter', 'sans-serif'],
                    }
                }
            }
        }
    </script>

    <style>
        :root {
            --p-color: <?= $parceiro['cor_primaria'] ?? "#2563eb" ?>;
        }
        body { background-color: #f8fafc; color: #1e293b; }
        
        header {
            background: rgba(255, 255, 255, 0.9);
            backdrop-filter: blur(10px);
            border-bottom: 1px solid #e2e8f0;
            position: sticky;
            top: 0;
            z-index: 100;
        }

        .card-produto {
            background: #fff;
            border-radius: 8px;
            border: 1px solid #e2e8f0;
            transition: all 0.3s ease;
            display: flex;
            flex-direction: column;
            height: 100%;
            overflow: hidden;
            cursor: pointer;
        }

        .card-produto:hover {
            transform: translateY(-4px);
            box-shadow: 0 12px 20px -5px rgba(0,0,0,0.1);
            border-color: var(--p-color);
        }

        .img-wrapper {
            width: 100%;
            height: 240px;
            background: #f1f5f9;
            display: flex;
            align-items: center;
            justify-content: center;
            position: relative;
            padding: 10px;
        }

        .img-wrapper img {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
        }

        .btn-cart {
            background-color: var(--p-color);
            color: #ffffff !important;
            padding: 12px;
            border-radius: 6px;
            font-weight: 600;
            width: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            transition: opacity 0.2s;
            border: none;
            cursor: pointer;
        }

        .btn-cart:hover { opacity: 0.9; }

        .heart-btn {
            position: absolute;
            top: 10px;
            right: 10px;
            z-index: 20;
            background: #fff;
            width: 34px;
            height: 34px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            cursor: pointer;
        }

        .heart-btn i { color: #cbd5e1; transition: color 0.2s; }
        .heart-btn.active i { color: #ef4444; }

        .filter-btn {
            padding: 8px 16px;
            border-radius: 20px;
            background: #fff;
            border: 1px solid #e2e8f0;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s;
            white-space: nowrap;
        }

        .filter-btn.active {
            background: var(--p-color);
            color: #fff;
            border-color: var(--p-color);
        }

        .search-box {
            position: relative;
            width: 100%;
            max-width: 400px;
        }

        .search-box input {
            width: 100%;
            padding: 10px 15px 10px 40px;
            border-radius: 8px;
            border: 1px solid #e2e8f0;
            outline: none;
        }

        .search-box i {
            position: absolute;
            left: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: #94a3b8;
        }

        .badge-cart {
            background: #ef4444;
            color: white;
            font-size: 10px;
            font-weight: 700;
            padding: 2px 6px;
            border-radius: 10px;
            position: absolute;
            top: -5px;
            right: -5px;
            border: 2px solid #fff;
        }

        .cart-float {
            position: fixed;
            bottom: 25px;
            right: 25px;
            background: var(--p-color);
            color: #fff !important;
            width: 60px;
            height: 60px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 10px 25px rgba(0,0,0,0.2);
            z-index: 99;
        }

        /* Modal Styles */
        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            display: none;
            align-items: center;
            justify-content: center;
            z-index: 200;
            padding: 20px;
            backdrop-filter: blur(4px);
        }

        .modal-content {
            background: #fff;
            width: 100%;
            max-width: 600px;
            border-radius: 12px;
            overflow: hidden;
            position: relative;
            animation: slideUp 0.3s ease;
        }

        @keyframes slideUp {
            from { transform: translateY(20px); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }

        .modal-close {
            position: absolute;
            top: 15px;
            right: 15px;
            font-size: 24px;
            cursor: pointer;
            z-index: 10;
            color: #64748b;
        }
        .no-scrollbar::-webkit-scrollbar { display: none; }
        .no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }
    </style>
</head>
<body>

<header>
    <div class="max-w-7xl mx-auto px-4 h-16 flex justify-between items-center">
        <div class="flex items-center gap-3">
            <?php if(!empty($parceiro['logo'])): ?>
                <img src="<?= htmlspecialchars($parceiro['logo']) ?>" class="h-8 w-auto">
            <?php endif; ?>
            <span class="font-bold text-lg text-slate-800"><?= htmlspecialchars($parceiro['nome']) ?></span>
        </div>

        <div class="flex items-center gap-4 md:gap-6">
            <a href="favoritos.php?id=<?= $idParceiro ?>" class="text-slate-500 hover:text-primary transition-colors" title="Favoritos">
                <i class="ph ph-heart text-2xl"></i>
            </a>
            <a href="conta.php?id=<?= $idParceiro ?>" class="text-slate-500 hover:text-primary transition-colors flex items-center gap-2" title="Minha Conta">
                <i class="ph ph-user text-2xl"></i>
                <span id="clienteNome" class="hidden lg:inline text-xs font-bold text-slate-700"></span>
            </a>
            <a href="downloads.php?id=<?= $idParceiro ?>" class="text-slate-500 hover:text-primary transition-colors" title="Meus Downloads">
                <i class="ph ph-download-simple text-2xl"></i>
            </a>
            <a href="carrinho.php?id=<?= $idParceiro ?>" class="relative text-slate-500 hover:text-primary transition-colors" title="Carrinho">
                <i class="ph ph-shopping-cart text-2xl"></i>
                <span id="cartCount" class="badge-cart hidden">0</span>
            </a>
        </div>
    </div>
</header>

<main class="max-w-7xl mx-auto px-4 py-8">
    
    <div class="flex flex-col md:flex-row justify-between items-center gap-4 mb-10">
        <div class="search-box">
            <i class="ph ph-magnifying-glass"></i>
            <input type="text" id="searchInput" placeholder="Buscar produtos..." onkeyup="filtrar()">
        </div>
        
        <div class="flex gap-2 overflow-x-auto pb-2 w-full md:w-auto no-scrollbar">
            <button class="filter-btn active" onclick="filtrarCat('todas', this)">Todas</button>
            <?php foreach($categorias as $cat): ?>
                <button class="filter-btn" onclick="filtrarCat('<?= $cat ?>', this)"><?= htmlspecialchars($cat) ?></button>
            <?php endforeach; ?>
        </div>
    </div>

    <div id="produtosGrid" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
        <?php foreach($produtosParceiro as $produto): ?>
        <div class="card-produto product-item" 
             data-nome="<?= strtolower($produto['nome']) ?>" 
             data-cat="<?= $produto['categoria'] ?? '' ?>"
             onclick='abrirDetalhes(<?= json_encode($produto) ?>)'>
            
            <div class="img-wrapper">
                <div class="heart-btn" onclick='event.stopPropagation(); toggleFav("<?= $produto['id'] ?>", this)'>
                    <i class="fa-solid fa-heart"></i>
                </div>
                
                <div class="swiper w-full h-full">
                    <div class="swiper-wrapper">
                        <?php foreach($produto['imagens'] as $img): ?>
                        <div class="swiper-slide flex items-center justify-center">
                            <img src="<?= htmlspecialchars($img) ?>" loading="lazy">
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>

            <div class="p-4 flex-grow flex flex-col">
                <h3 class="font-bold text-slate-800 mb-1 line-clamp-1"><?= htmlspecialchars($produto['nome']) ?></h3>
                <p class="text-slate-500 text-xs line-clamp-2 mb-4 h-8"><?= htmlspecialchars($produto['descricao']) ?></p>
                
                <div class="mt-auto">
                    <div class="text-xl font-extrabold text-slate-900 mb-4">
                        R$ <?= number_format($produto['valor'],2,',','.') ?>
                    </div>
                    <button class="btn-cart" onclick='event.stopPropagation(); addCarrinho(<?= json_encode($produto) ?>)'>
                        <i class="ph ph-shopping-cart-simple"></i> Adicionar
                    </button>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>

    <div id="noResults" class="hidden text-center py-20">
        <p class="text-slate-400">Nenhum produto encontrado.</p>
    </div>
</main>

<div id="modalDetalhes" class="modal-overlay" onclick="fecharDetalhes()">
    <div class="modal-content" onclick="event.stopPropagation()">
        <i class="ph ph-x modal-close" onclick="fecharDetalhes()"></i>
        <div id="modalBody"></div>
    </div>
</div>

<a href="carrinho.php?id=<?= $idParceiro ?>" class="cart-float">
    <i class="ph ph-shopping-cart text-2xl"></i>
    <span id="cartFloat" class="badge-cart hidden">0</span>
</a>

<script src="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.js"></script>
<script>
    function initSwipers() {
        new Swiper('.swiper', { loop: true });
    }
    initSwipers();

    let carrinho = JSON.parse(localStorage.getItem('carrinho_<?= $idParceiro ?>')) || [];
    let favoritos = JSON.parse(localStorage.getItem('favoritos_<?= $idParceiro ?>')) || [];
    let catAtiva = 'todas';

    const Toast = Swal.mixin({
        toast: true, position: 'top-end', showConfirmButton: false, timer: 2000
    });

    function addCarrinho(prod) {
        carrinho.push(prod);
        localStorage.setItem('carrinho_<?= $idParceiro ?>', JSON.stringify(carrinho));
        atualizarUI();
        Toast.fire({ icon: 'success', title: 'Adicionado ao carrinho!' });
    }

    function toggleFav(id, el) {
        const idx = favoritos.indexOf(id);
        if(idx === -1) {
            favoritos.push(id);
            el.classList.add('active');
            Toast.fire({ icon: 'success', title: 'Salvo nos favoritos!' });
        } else {
            favoritos.splice(idx, 1);
            el.classList.remove('active');
            Toast.fire({ icon: 'info', title: 'Removido dos favoritos' });
        }
        localStorage.setItem('favoritos_<?= $idParceiro ?>', JSON.stringify(favoritos));
    }

    function filtrarCat(cat, el) {
        catAtiva = cat;
        document.querySelectorAll('.filter-btn').forEach(b => b.classList.remove('active'));
        el.classList.add('active');
        filtrar();
    }

    function filtrar() {
        const busca = document.getElementById('searchInput').value.toLowerCase();
        const items = document.querySelectorAll('.product-item');
        let count = 0;
        items.forEach(item => {
            const matchBusca = item.getAttribute('data-nome').includes(busca);
            const matchCat = (catAtiva === 'todas' || item.getAttribute('data-cat') === catAtiva);
            item.style.display = (matchBusca && matchCat) ? 'flex' : 'none';
            if(matchBusca && matchCat) count++;
        });
        document.getElementById('noResults').classList.toggle('hidden', count > 0);
    }

    function atualizarUI() {
        const c = carrinho.length;
        ['cartCount', 'cartFloat'].forEach(id => {
            const el = document.getElementById(id);
            if(el) { el.textContent = c; el.classList.toggle('hidden', c === 0); }
        });

        const cliente = JSON.parse(localStorage.getItem('cliente_logado_<?= $idParceiro ?>'));
        if (cliente) {
            document.getElementById('clienteNome').textContent = cliente.nome.split(' ')[0];
            document.getElementById('clienteNome').classList.remove('hidden');
        }
        
        // Marcar favoritos carregados
        document.querySelectorAll('.product-item').forEach(item => {
            const id = JSON.parse(item.getAttribute('onclick').match(/abrirDetalhes\((.*)\)/)[1]).id;
            if(favoritos.includes(id)) {
                item.querySelector('.heart-btn').classList.add('active');
            }
        });
    }

    function abrirDetalhes(prod) {
        const modal = document.getElementById('modalDetalhes');
        const body = document.getElementById('modalBody');
        const valorFormatado = new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(prod.valor);
        
        body.innerHTML = `
            <div class="flex flex-col md:flex-row">
                <div class="w-full md:w-1/2 bg-slate-50 p-6 flex items-center justify-center border-b md:border-b-0 md:border-r border-slate-100">
                    <img src="${prod.imagens[0]}" class="max-w-full max-h-[300px] object-contain">
                </div>
                <div class="w-full md:w-1/2 p-6 flex flex-col">
                    <span class="text-[10px] font-bold text-primary uppercase tracking-widest mb-1">${prod.categoria || ''}</span>
                    <h2 class="text-2xl font-bold text-slate-800 mb-2">${prod.nome}</h2>
                    <div class="text-2xl font-black text-slate-900 mb-4">${valorFormatado}</div>
                    <div class="flex-grow overflow-y-auto max-h-40 mb-6 pr-2">
                        <p class="text-slate-600 text-sm leading-relaxed">${prod.descricao}</p>
                    </div>
                    <button class="btn-cart" onclick='addCarrinho(${JSON.stringify(prod)})'>
                        <i class="ph ph-shopping-cart-simple"></i> Adicionar ao Carrinho
                    </button>
                </div>
            </div>
        `;
        modal.style.display = 'flex';
        document.body.style.overflow = 'hidden';
    }

    function fecharDetalhes() {
        document.getElementById('modalDetalhes').style.display = 'none';
        document.body.style.overflow = 'auto';
    }

    atualizarUI();
</script>

</body>
</html>
