<?php
// ==============================================================================
// 1. CONEXÃO E CONFIGURAÇÃO
// ==============================================================================
$paths = ['../config.php', '../../config.php', 'config.php'];
$config_loaded = false;
foreach ($paths as $path) { 
    if (file_exists($path)) { 
        require_once $path; 
        $config_loaded = true; 
        break; 
    }
}

if (!$config_loaded) { 
    die("<h1>Erro Crítico</h1><p>O arquivo config.php não foi encontrado.</p>"); 
}

// ==============================================================================
// 2. LÓGICA DE AFILIADOS (RASTREAMENTO)
// ==============================================================================
$codigo_afiliado = '';
if (isset($_GET['ref']) && !empty($_GET['ref'])) {
    $codigo_afiliado = preg_replace('/[^a-zA-Z0-9]/', '', $_GET['ref']);
    setcookie('afiliado_ref', $codigo_afiliado, time() + (86400 * 30), "/");
} elseif (isset($_COOKIE['afiliado_ref'])) {
    $codigo_afiliado = $_COOKIE['afiliado_ref'];
}

try {
    // --- A. DADOS DA LOJA ---
    $stmt_config = $pdo->prepare("SELECT * FROM config_loja WHERE id = 1");
    $stmt_config->execute();
    $loja_info = $stmt_config->fetch(PDO::FETCH_ASSOC);

    if (!$loja_info) {
        $loja_info = [
            'nome_loja' => 'Loja TikTok',
            'logo_url' => 'https://cdn-icons-png.flaticon.com/512/3135/3135715.png',
            'cor_primaria' => '#ff0050'
        ];
    }

    // --- B. BUSCAR CUPONS ATIVOS ---
    // Agora busca do banco de dados, permitindo controle pelo Admin
    $stmt_cupons = $pdo->query("SELECT * FROM cupoms WHERE ativo = 1 ORDER BY id DESC");
    $cupons = $stmt_cupons->fetchAll(PDO::FETCH_ASSOC);

    // --- C. FILTROS E BUSCA DE PRODUTOS ---
    $busca = isset($_GET['q']) ? trim($_GET['q']) : '';
    $filtro = isset($_GET['tab']) ? $_GET['tab'] : 'recomendado';

    $sql_prod = "SELECT * FROM produtos WHERE ativo = 1";
    $params_prod = [];

    // Lógica de Busca
    if (!empty($busca)) {
        $sql_prod .= " AND (nome LIKE ? OR descricao LIKE ?)";
        $params_prod[] = "%$busca%";
        $params_prod[] = "%$busca%";
    }

    // Lógica de Ordenação (Abas)
    switch ($filtro) {
        case 'mais_vendidos':
            $sql_prod .= " ORDER BY vendas_qtd DESC";
            break;
        case 'lancamentos':
            $sql_prod .= " ORDER BY id DESC"; // Assumindo ID maior = mais novo
            break;
        case 'preco':
            $sql_prod .= " ORDER BY preco_atual ASC";
            break;
        case 'recomendado':
        default:
            $sql_prod .= " ORDER BY id DESC"; // Padrão
            break;
    }

    $stmt_prod = $pdo->prepare($sql_prod);
    $stmt_prod->execute($params_prod);
    $produtos = $stmt_prod->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) {
    die("Erro de conexão: " . $e->getMessage());
}

// Helpers
function fixImg($path) {
    if (empty($path)) return 'https://placehold.co/200x200?text=Sem+Foto';
    if (strpos($path, 'http') === 0) return $path;
    return '../' . $path; 
}
?>

<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Loja de <?php echo $loja_info['nome_loja']; ?></title>
    
    <link href="https://fonts.googleapis.com/css2?family=Rubik:wght@400;500;600;700&display=swap" rel="stylesheet">
    <!-- Toastify para alertas bonitos -->
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css">
    
    <style>
        /* === RESET E VARIAVEIS === */
        :root { --primary: <?php echo $loja_info['cor_primaria']; ?>; }
        * { box-sizing: border-box; margin: 0; padding: 0; font-family: 'Rubik', sans-serif; -webkit-tap-highlight-color: transparent; }
        body { background-color: #fff; color: #161823; padding-bottom: 80px; }
        a { text-decoration: none; color: inherit; }
        
        /* === CABEÇALHO === */
        .header {
            display: flex; align-items: center; gap: 12px;
            padding: 12px 16px; position: sticky; top: 0; background: #fff; z-index: 100;
            box-shadow: 0 1px 0 rgba(0,0,0,0.05);
        }
        .back-btn { font-size: 24px; cursor: pointer; display: flex; align-items: center; }
        
        /* Formulário de Busca Funcional */
        .search-form { flex: 1; }
        .search-box {
            background: #f1f1f2; border-radius: 4px; padding: 8px 12px;
            display: flex; align-items: center; gap: 8px; color: #757575; font-size: 14px;
        }
        .search-box input {
            border: none; background: transparent; width: 100%; outline: none; font-size: 14px; color: #161823;
        }
        
        .header-icons { display: flex; gap: 16px; font-size: 22px; align-items: center; }

        /* === PERFIL DA LOJA === */
        .store-profile { display: flex; align-items: center; gap: 12px; padding: 16px; }
        .store-icon {
            width: 48px; height: 48px; background: #f1f1f2; border-radius: 50%;
            display: flex; align-items: center; justify-content: center; border: 1px solid #e0e0e0; overflow: hidden;
        }
        .store-icon img { width: 100%; height: 100%; object-fit: cover; }
        .store-name { font-weight: 600; font-size: 16px; }

        /* === CUPONS === */
        .coupons-scroll {
            display: flex; gap: 10px; overflow-x: auto; padding: 0 16px 16px;
            scrollbar-width: none;
        }
        .coupons-scroll::-webkit-scrollbar { display: none; }
        
        .coupon-card {
            min-width: 240px; background: #f8f8f8; border-radius: 8px; padding: 10px 12px;
            display: flex; justify-content: space-between; align-items: center; border: 1px solid #eee;
            transition: transform 0.2s;
        }
        .coupon-card:active { transform: scale(0.98); }
        .cp-left { display: flex; flex-direction: column; gap: 2px; }
        .cp-title { font-weight: 700; font-size: 13px; color: #161823; }
        .cp-desc { font-size: 11px; color: #757575; }
        .cp-btn {
            background: #00baa5; color: #fff; font-weight: 600; font-size: 12px;
            padding: 6px 12px; border-radius: 4px; border: none; cursor: pointer;
        }
        
        /* Variação Rosa do Cupom */
        .cp-pink { background: #fff5f7; border-color: #ff00501a; }
        .cp-pink .cp-btn { background: transparent; color: #ff0050; border: 1px solid #ff00501a; }

        /* === ABAS (FILTROS) === */
        .tabs {
            display: flex; gap: 24px; padding: 0 16px; border-bottom: 1px solid #f1f1f2;
            overflow-x: auto; margin-bottom: 16px;
        }
        .tab-item {
            font-size: 15px; font-weight: 600; color: #757575; padding: 10px 0;
            position: relative; white-space: nowrap; cursor: pointer;
        }
        .tab-item.active { color: #161823; }
        .tab-item.active::after {
            content: ''; position: absolute; bottom: 0; left: 0; right: 0;
            height: 2px; background: #161823;
        }

        /* === LISTA DE PRODUTOS === */
        .product-list { display: flex; flex-direction: column; gap: 16px; padding: 0 16px; }
        
        .prod-card { display: flex; gap: 12px; align-items: flex-start; }
        .prod-img {
            width: 100px; height: 100px; border-radius: 8px; object-fit: cover;
            background: #f8f8f8; flex-shrink: 0;
        }
        .prod-info {
            flex: 1; display: flex; flex-direction: column; justify-content: space-between; min-height: 100px;
        }
        .prod-title {
            font-size: 14px; font-weight: 400; color: #161823;
            display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden;
            line-height: 1.3;
        }
        .prod-tags { margin-top: 4px; display: flex; flex-wrap: wrap; gap: 4px; }
        .tag-discount {
            background: #fff2f5; color: #ff0050; font-size: 10px; font-weight: 600;
            padding: 2px 4px; border-radius: 2px; display: flex; align-items: center; gap: 2px;
        }
        .prod-sold { font-size: 11px; color: #757575; margin-top: 4px; }
        
        .prod-bottom {
            display: flex; justify-content: space-between; align-items: flex-end; margin-top: auto;
        }
        .prod-price { font-size: 16px; font-weight: 700; color: #161823; }
        
        .btn-buy {
            background: var(--primary); color: #fff; border: none; border-radius: 4px;
            padding: 6px 12px; font-size: 13px; font-weight: 600;
            display: flex; align-items: center; gap: 6px; cursor: pointer;
            transition: opacity 0.2s;
        }
        .btn-buy:active { opacity: 0.8; }

        /* Desktop Container */
        @media (min-width: 481px) {
            html { background-color: #e5e5e5; }
            body {
                max-width: 480px; margin: 0 auto; background-color: #ffffff;
                min-height: 100vh; box-shadow: 0 0 30px rgba(0,0,0,0.15); border: 1px solid #ddd;
            }
            .header { max-width: 480px; margin: 0 auto; left: 0; right: 0; }
        }
    </style>
</head>
<body>

    <!-- Header com Busca Funcional -->
    <header class="header">
        <div class="back-btn" onclick="history.back()">
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M15 18l-6-6 6-6"/>
            </svg>
        </div>
        
        <form action="" method="GET" class="search-form">
            <!-- Mantém o filtro de aba se existir -->
            <?php if(isset($_GET['tab'])): ?>
                <input type="hidden" name="tab" value="<?php echo htmlspecialchars($_GET['tab']); ?>">
            <?php endif; ?>
            <!-- Mantém o afiliado se existir na URL -->
            <?php if(isset($_GET['ref'])): ?>
                <input type="hidden" name="ref" value="<?php echo htmlspecialchars($_GET['ref']); ?>">
            <?php endif; ?>

            <div class="search-box">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line>
                </svg>
                <input type="text" name="q" placeholder="Pesquisar produto..." value="<?php echo htmlspecialchars($busca); ?>">
            </div>
        </form>

        <div class="header-icons">
            <!-- Ícone Menu/Opções (Visual) -->
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="opacity: 0.6;">
                 <circle cx="18" cy="5" r="3"></circle><circle cx="6" cy="12" r="3"></circle><circle cx="18" cy="19" r="3"></circle><line x1="8.59" y1="13.51" x2="15.42" y2="17.49"></line><line x1="15.41" y1="6.51" x2="8.59" y2="10.49"></line>
            </svg>
            <!-- Link para Área do Aluno / Perfil -->
            <a href="../area_aluno.php">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path><circle cx="12" cy="7" r="4"></circle>
                </svg>
            </a>
        </div>
    </header>

    <!-- Perfil da Loja -->
    <section class="store-profile">
        <div class="store-icon">
            <img src="<?php echo fixImg($loja_info['logo_url']); ?>" alt="Loja">
        </div>
        <div class="store-name"><?php echo $loja_info['nome_loja']; ?></div>
    </section>

    <!-- Cupons Dinâmicos (Vindos do Banco de Dados) -->
    <?php if (count($cupons) > 0): ?>
    <section class="coupons-scroll">
        <?php foreach($cupons as $cupom): 
            // Define estilo baseado no campo 'cor_fundo' do banco
            $classeExtra = ($cupom['cor_fundo'] == 'pink') ? 'cp-pink' : '';
        ?>
        <div class="coupon-card <?php echo $classeExtra; ?>">
            <div class="cp-left">
                <span class="cp-title"><?php echo $cupom['titulo']; ?></span>
                <span class="cp-desc"><?php echo $cupom['descricao']; ?></span>
            </div>
            <!-- Botão com JS para copiar -->
            <button class="cp-btn" onclick="copiarCupom('<?php echo $cupom['codigo']; ?>')">Resgatar</button>
        </div>
        <?php endforeach; ?>
    </section>
    <?php endif; ?>

    <!-- Abas de Filtro Funcionais -->
    <nav class="tabs">
        <a href="?tab=recomendado<?php echo $busca ? '&q='.$busca : ''; ?>" class="tab-item <?php echo $filtro == 'recomendado' ? 'active' : ''; ?>">Recomendado</a>
        <a href="?tab=mais_vendidos<?php echo $busca ? '&q='.$busca : ''; ?>" class="tab-item <?php echo $filtro == 'mais_vendidos' ? 'active' : ''; ?>">Mais vendidos</a>
        <a href="?tab=lancamentos<?php echo $busca ? '&q='.$busca : ''; ?>" class="tab-item <?php echo $filtro == 'lancamentos' ? 'active' : ''; ?>">Lançamentos</a>
        <a href="?tab=preco<?php echo $busca ? '&q='.$busca : ''; ?>" class="tab-item <?php echo $filtro == 'preco' ? 'active' : ''; ?>">Preço</a>
    </nav>

    <!-- Lista de Produtos -->
    <main class="product-list">
        
        <?php if (count($produtos) > 0): ?>
            <?php foreach ($produtos as $prod): 
                // Calculo de desconto
                $tem_desconto = ($prod['preco_original'] > $prod['preco_atual']);
                $pct = 0;
                if($tem_desconto && $prod['preco_original'] > 0) {
                    $pct = round((($prod['preco_original'] - $prod['preco_atual']) / $prod['preco_original']) * 100);
                }
                
                // Link de Compra com Afiliado
                $link_compra = "../checkout/?product_id=" . $prod['id'];
                if (!empty($codigo_afiliado)) {
                    $link_compra .= "&ref=" . $codigo_afiliado;
                }
            ?>
            <div class="prod-card">
                <img src="<?php echo fixImg($prod['imagem_principal']); ?>" class="prod-img" alt="<?php echo $prod['nome']; ?>">
                
                <div class="prod-info">
                    <h3 class="prod-title"><?php echo $prod['nome']; ?></h3>
                    
                    <?php if($tem_desconto): ?>
                    <div class="prod-tags">
                        <div class="tag-discount">
                            <svg width="10" height="10" viewBox="0 0 24 24" fill="currentColor"><path d="M20.59 13.41l-7.17 7.17a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z"></path><line x1="7" y1="7" x2="7.01" y2="7"></line></svg>
                            <?php echo $pct; ?>% OFF
                        </div>
                    </div>
                    <?php endif; ?>

                    <div class="prod-sold"><?php echo $prod['vendas_qtd']; ?> vendido(s)</div>

                    <div class="prod-bottom">
                        <span class="prod-price">R$ <?php echo number_format($prod['preco_atual'], 2, ',', '.'); ?></span>
                        
                        <a href="<?php echo $link_compra; ?>">
                            <button class="btn-buy">
                                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                    <circle cx="9" cy="21" r="1"></circle><circle cx="20" cy="21" r="1"></circle><path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path>
                                </svg>
                                Comprar
                            </button>
                        </a>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        <?php else: ?>
            <div style="text-align: center; color: #999; font-size: 13px; padding: 40px;">
                <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="#ddd" stroke-width="2" style="margin-bottom: 10px;">
                    <circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line>
                </svg>
                <br>
                Nenhum produto encontrado.
            </div>
        <?php endif; ?>

        <div style="text-align: center; color: #999; font-size: 13px; margin-top: 20px;">
            Fim da lista
        </div>

    </main>

    <!-- Lib de Notificação (Toastify) -->
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/toastify-js"></script>

    <script>
        // Função para Copiar Cupom
        function copiarCupom(codigo) {
            // Cria elemento temporário
            const el = document.createElement('textarea');
            el.value = codigo;
            document.body.appendChild(el);
            el.select();
            document.execCommand('copy');
            document.body.removeChild(el);

            // Notificação Bonita
            Toastify({
                text: "Cupom " + codigo + " copiado!",
                duration: 3000,
                gravity: "top", // `top` or `bottom`
                position: "center", // `left`, `center` or `right`
                backgroundColor: "linear-gradient(to right, #00b09b, #96c93d)",
                stopOnFocus: true, 
            }).showToast();
        }
    </script>

</body>
</html>