<?php
// ==============================================================================
// 1. CONEXÃO ROBUSTA (CORREÇÃO DO ERRO)
// ==============================================================================
$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. Verifique se ele está na raiz do site.</p>"); 
}

try {
    // 1. Buscar configurações da loja
    $stmt_config = $pdo->prepare("SELECT * FROM config_loja WHERE id = 1");
    $stmt_config->execute();
    $loja_info = $stmt_config->fetch();

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

    // 2. Buscar Produtos do Banco de Dados
    // Pegamos apenas os que estão 'ativo = 1'
    $stmt_prod = $pdo->prepare("SELECT * FROM produtos WHERE ativo = 1 ORDER BY id DESC");
    $stmt_prod->execute();
    $produtos = $stmt_prod->fetchAll();

} catch (PDOException $e) {
    echo "Erro ao carregar dados: " . $e->getMessage();
    exit;
}

// Função para corrigir caminho da imagem (adicionar ../ se for upload local)
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">
    <link rel="icon" href="https://www.tiktok.com/favicon.ico" type="image/x-icon" />

    <style>
        /* === RESET E BASICO === */
        * { 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 (Search + Ícones) === */
        .header {
            display: flex; align-items: center; gap: 12px;
            padding: 12px 16px; position: sticky; top: 0; background: #fff; z-index: 100;
        }
        .back-btn { font-size: 24px; cursor: pointer; }
        .search-box {
            flex: 1; background: #f1f1f2; border-radius: 4px; padding: 8px 12px;
            display: flex; align-items: center; gap: 8px; color: #757575; font-size: 14px;
        }
        .header-icons { display: flex; gap: 16px; font-size: 22px; }

        /* === PERFIL DA LOJA === */
        .store-profile {
            display: flex; align-items: center; gap: 12px; padding: 10px 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 (Scroll Horizontal) === */
        .coupons-scroll {
            display: flex; gap: 10px; overflow-x: auto; padding: 0 16px 16px;
            scrollbar-width: none; /* Firefox */
        }
        .coupons-scroll::-webkit-scrollbar { display: none; } /* Chrome */
        
        .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;
        }
        .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;
        }
        .cp-pink .cp-btn { background: transparent; color: #ff0050; border: 1px solid #ff00501a; }
        .cp-pink { background: #fff5f7; border-color: #ff00501a; }

        /* === ABAS (Recomendado, Mais vendidos...) === */
        .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 (Vertical) === */
        .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: #ff0050; 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;
        }

        /* === ÍCONES SVG === */
        .icon-svg { width: 20px; height: 20px; fill: currentColor; }
        
        /* === MODO CELULAR NO DESKTOP (Centralizado) === */
        @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 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>
        <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>
            <span>Pesquisar</span>
        </div>
        <div class="header-icons">
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                 <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>
            <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>

    <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>

    <section class="coupons-scroll">
        <div class="coupon-card">
            <div class="cp-left">
                <span class="cp-title">Cupom de envio</span>
                <span class="cp-desc">em pedidos acima de R$ 109</span>
            </div>
            <button class="cp-btn">Resgatar</button>
        </div>
        <div class="coupon-card cp-pink">
            <div class="cp-left">
                <span class="cp-title">Desconto de R$ 10</span>
                <span class="cp-desc">nos pedidos acima de R$ 60</span>
            </div>
            <button class="cp-btn">Resgatar</button>
        </div>
    </section>

    <nav class="tabs">
        <div class="tab-item active">Recomendado</div>
        <div class="tab-item">Mais vendidos</div>
        <div class="tab-item">Lançamentos</div>
        <div class="tab-item">Preço</div>
    </nav>

    <main class="product-list">
        
        <?php if (count($produtos) > 0): ?>
            <?php foreach ($produtos as $prod): 
                // Calculo de desconto visual
                $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);
                }
            ?>
            <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="../checkout/?product_id=<?php echo $prod['id']; ?>">
                            <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;">
                Nenhum produto cadastrado na loja.
            </div>
        <?php endif; ?>

        <div style="text-align: center; color: #999; font-size: 13px; margin-top: 20px;">
            Não há mais produtos
        </div>

    </main>

</body>
</html>