<?php
require_once('conexao.php');
require_once('funcoes.php');

if (isset($_GET['add'])) {
    $id = intval($_GET['add']);
    $qtd = isset($_GET['qtd']) && intval($_GET['qtd']) > 0 ? intval($_GET['qtd']) : 1;
    $sql = "SELECT * FROM produtos WHERE id = $id";
    $result = $conn->query($sql);
    if ($result && $result->num_rows > 0) {
        $produto = $result->fetch_assoc();
        adicionarAoCarrinho($produto, $qtd);
        header("Location: index.php?msg=adicionado");
        exit;
    }
}

$carrinho = listarCarrinho() ?? [];

// Paginação
$produtosPorPagina = 50;
$paginaAtual = isset($_GET['pagina']) ? max(1, intval($_GET['pagina'])) : 1;
$offset = ($paginaAtual - 1) * $produtosPorPagina;

// Contar total de produtos
$sqlCount = "SELECT COUNT(*) as total FROM produtos";
$resultCount = $conn->query($sqlCount);
$totalProdutos = $resultCount->fetch_assoc()['total'];
$totalPaginas = ceil($totalProdutos / $produtosPorPagina);

// Buscar produtos da página atual
$sql = "SELECT id, codigo, nome, preco, foto FROM produtos LIMIT $produtosPorPagina OFFSET $offset";
$result = $conn->query($sql);

$produtos = [];
if ($result && $result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $produtos[] = $row;
    }
}

// Buscar todos os produtos para a busca (apenas os dados necessários)
$sqlBusca = "SELECT id, codigo, nome, preco, foto FROM produtos";
$resultBusca = $conn->query($sqlBusca);
$todosProdutos = [];
if ($resultBusca && $resultBusca->num_rows > 0) {
    while ($row = $resultBusca->fetch_assoc()) {
        $todosProdutos[] = $row;
    }
}

// URLs dos banners rotativos
$banners = [
    [
        'titulo' => '🛒 Compre com Preços de Atacado',
        'subtitulo' => 'Produtos de qualidade e economia para você!',
        'cta' => 'Ver Produtos',
        'imagem' => 'https://images.unsplash.com/photo-1542838133-d9229f34a475?w=1200&h=400&fit=crop&crop=center'
    ],
    [
        'titulo' => '🍎 Hortifruti Fresquinho',
        'subtitulo' => 'Frutas e vegetais direto do campo para sua mesa.',
        'cta' => 'Explorar Hortifruti',
        'imagem' => 'https://images.unsplash.com/photo-1518843875429-bf73a2416b71?w=1200&h=400&fit=crop&crop=center'
    ],
    [
        'titulo' => '🥩 Carnes e Frios de Qualidade',
        'subtitulo' => 'Seleção especial para suas refeições!',
        'cta' => 'Ver Carnes',
        'imagem' => 'https://images.unsplash.com/photo-1562259949-e8e7689d7828?w=1200&h=400&fit=crop&crop=center'
    ],
    [
        'titulo' => '⚡ Bebidas Geladas',
        'subtitulo' => 'Aproveite nossas ofertas em bebidas!',
        'cta' => 'Ver Bebidas',
        'imagem' => 'https://images.unsplash.com/photo-1582266014459-c290a6184a51?w=1200&h=400&fit=crop&crop=center'
    ]
];
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
<link rel="manifest" href="/manifest.json">
<meta name="theme-color" content="#A20000">

<!-- Para iPhone/iPad -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="default">
<link rel="apple-touch-icon" href="/icons/icon-192.png">

    <meta charset="UTF-8">
    <title>Catálogo - Mercadinho Pajeú</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        body { 
            background: #f4f6f8; 
            margin: 0;
            padding-top: 160px; /* Espaço para navbar fixa + barra de pesquisa */
        }
        .navbar {
            background: linear-gradient(135deg, #A20000 0%, #8B0000 100%) !important;
            position: fixed;
            top: 0; 
            left: 0;
            height: 62px;			
            width: 100%; 
            z-index: 1040;
            box-shadow: 0 4px 20px rgba(162, 0, 0, 0.3);
            padding: 8px 0;
        }
        .navbar-brand {
            font-size: 1.6rem;
            font-weight: bold;
            letter-spacing: 1px;
            color: #fff !important;
            display: flex;
            align-items: center;
            gap: 12px;
        }
        .navbar-logo {
            height: 42px;
            width: 60px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.2);
        }
        .search-bar-fixed {
            position: fixed;
            top: 100px;
            left: 0;
            width: 100%;
            z-index: 1039;
            background: linear-gradient(135deg, #A20000 100%, #8B0000 100%) !important;
            backdrop-filter: blur(10px);
            padding: 15px 0;
            box-shadow: 0 2px 15px rgba(0,0,0,0.1);
            border-bottom: 1px solid rgba(0,0,0,0.1);
        }
        .search-container {
            max-width: 600px;
            margin: 0 auto;
            position: relative;
            display: flex;
            align-items: center;
            gap: 15px;
            padding: 0 20px;
        }
        .search-input {
            flex: 1;
            padding: 12px 20px;
            border: 2px solid #e9ecef;
            border-radius: 25px;
            font-size: 1rem;
            background: white;
            color: #333;
            outline: none;
            transition: all 0.3s ease;
        }
        .search-input:focus {
            border-color: #A20000;
            box-shadow: 0 0 0 3px rgba(162, 0, 0, 0.1);
        }
        .search-input::placeholder {
            color: #999;
        }
        .mic-button {
            background: linear-gradient(135deg, #A20000 0%, #8B0000 100%);
            border: none;
            border-radius: 50%;
            color: white;
            width: 50px;
            height: 50px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 1.2rem;
            box-shadow: 0 2px 10px rgba(162, 0, 0, 0.3);
        }
        .mic-button:hover {
            background: linear-gradient(135deg, #A20000 0%, #8B0000 100%);
            transform: scale(1.05);
            box-shadow: 0 4px 15px rgba(162, 0, 0, 0.4);
        }
        .mic-button.recording {
            background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
            animation: pulse 1s infinite;
        }
        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.1); }
            100% { transform: scale(1); }
        }
        .search-results {
            position: absolute;
            top: 100%;
            left: 20px;
            right: 80px;
            background: white;
            border-radius: 0 0 15px 15px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.1);
            max-height: 400px;
            overflow-y: auto;
            z-index: 1000;
            display: none;
            border: 1px solid #e9ecef;
            border-top: none;
        }
        .search-result-item {
            padding: 12px 20px;
            border-bottom: 1px solid #f0f0f0;
            cursor: pointer;
            transition: background 0.2s ease;
        }
        .search-result-item:hover {
            background: #f8f9fa;
        }
        .search-result-item:last-child {
            border-bottom: none;
        }
        .search-result-name {
            font-weight: 600;
            color: #333;
            margin-bottom: 4px;
        }
        .search-result-code {
            font-size: 0.9rem;
            color: #666;
        }
        .search-result-price {
            font-weight: bold;
            color: #ffc107;
            font-size: 1.1rem;
        }
        .menu-toggle {
            background: rgba(255,255,255,0.1);
            border: 2px solid rgba(255,255,255,0.3);
            border-radius: 8px;
            color: white;
            padding: 8px 12px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .menu-toggle:hover {
            background: rgba(255,255,255,0.2);
            border-color: rgba(255,255,255,0.5);
            transform: scale(1.05);
        }
        .menu-dots {
            display: flex;
            flex-direction: column;
            gap: 3px;
        }
        .menu-dot {
            width: 4px;
            height: 4px;
            background: white;
            border-radius: 50%;
        }
        .dropdown-menu {
            background: white;
            border: none;
            border-radius: 12px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.15);
            padding: 12px 0;
            margin-top: 8px;
            min-width: 280px;
        }
        .dropdown-header {
            color: #333;
            font-weight: bold;
            font-size: 0.9rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            padding: 8px 20px;
            border-bottom: 1px solid #e9ecef;
            margin-bottom: 8px;
        }
        .dropdown-item {
            padding: 10px 20px;
            color: #333;
            transition: all 0.2s ease;
            border-left: 3px solid transparent;
        }
        .dropdown-item:hover {
            background: #f8f9fa;
            color: #A20000;
            border-left-color: #A20000;
        }
        .dropdown-item i {
            margin-right: 10px;
            width: 16px;
            color: #A20000;
        }
        .banner-carousel {
            margin-bottom: 30px;
            position: relative;
            overflow: hidden;
            border-radius: 0 0 20px 20px;
        }
        .banner-slide {
            background-size: cover;
            background-position: center;
            color: white;
            padding: 60px 0;
            position: relative;
            min-height: 300px;
            display: flex;
            align-items: center;
        }
        .banner-slide::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: linear-gradient(135deg, rgba(162, 0, 0, 0.8) 0%, rgba(139, 0, 0, 0.6) 50%, rgba(139, 0, 0, 0.8) 100%);
            z-index: 1;
        }
        .banner-slide::after {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grid" width="10" height="10" patternUnits="userSpaceOnUse"><path d="M 10 0 L 0 0 0 10" fill="none" stroke="rgba(255,255,255,0.1)" stroke-width="0.5"/></pattern></defs><rect width="100" height="100" fill="url(%23grid)"/></svg>');
            opacity: 0.3;
            z-index: 2;
        }
        .banner-content {
            position: relative;
            z-index: 3;
            text-align: center;
        }
        .banner-title {
            font-size: 2.5rem;
            font-weight: bold;
            margin-bottom: 15px;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
        }
        .banner-subtitle {
            font-size: 1.2rem;
            opacity: 0.9;
            margin-bottom: 25px;
        }
        .banner-cta {
            background: #ffc107;
            color: #212529;
            padding: 12px 30px;
            border-radius: 25px;
            text-decoration: none;
            font-weight: bold;
            display: inline-block;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(255, 193, 7, 0.4);
        }
        .banner-cta:hover {
            background: #ffcd39;
            color: #212529;
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(255, 193, 7, 0.6);
        }
        .carousel-control-prev,
        .carousel-control-next {
            width: 5%;
            opacity: 0.8;
        }
        .carousel-control-prev:hover,
        .carousel-control-next:hover {
            opacity: 1;
        }
        .carousel-indicators {
            bottom: 20px;
        }
        .carousel-indicators [data-bs-target] {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            margin: 0 4px;
            background-color: rgba(255, 255, 255, 0.5);
            border: 2px solid rgba(255, 255, 255, 0.8);
        }
        .carousel-indicators .active {
            background-color: #ffc107;
            border-color: #ffc107;
        }
        .catalog-title {
            font-weight: 700; 
            color: #333;
            margin-bottom: 2rem; 
            text-align: center; 
            letter-spacing: .5px;
            font-size: 2rem;
            position: relative;
        }
        .catalog-title::after {
            content: '';
            position: absolute;
            bottom: -10px;
            left: 50%;
            transform: translateX(-50%);
            width: 80px;
            height: 3px;
            background: linear-gradient(90deg, #A20000, #ffc107);
            border-radius: 2px;
        }
        .catalog-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 15px;
        }
        .card {
            border: none; 
            border-radius: 16px;
            box-shadow: 0 4px 20px rgba(0,0,0,.08);
            transition: all .3s ease;
            overflow: hidden;
            background: white;
        }
        .card:hover {
            transform: translateY(-8px);
            box-shadow: 0 12px 40px rgba(162, 0, 0, 0.15);
        }
        .card-img-top {
            height: 200px; 
            object-fit: contain;
            background: #fff; 
            padding: 15px; 
            cursor: pointer;
            transition: all .3s ease;
            border-bottom: 1px solid #f0f0f0;
        }
        .card-img-top:hover { 
            transform: scale(1.05);
        }
        .card-body {
            padding: 20px;
        }
        .product-name { 
            font-size: 1.1rem; 
            font-weight: 600; 
            color: #212529; 
            margin-bottom: 8px;
            line-height: 1.3;
        }
        .product-code { 
            color: #888; 
            font-size: .9rem; 
            margin-bottom: 12px;
        }
        .product-price { 
            margin-bottom: 20px;
        }
        .price-old {
            color: #888; 
            text-decoration: line-through; 
            font-size: 0.9rem;
            display: block;
        }
        .price-current {
            color: #ffc107; 
            font-weight: bold; 
            font-size: 1.3rem;
            display: block;
        }
        .btn-primary { 
            background: linear-gradient(135deg, #A20000 0%, #A20000 100%);
            border: none;
            border-radius: 10px;
            padding: 12px 20px;
            font-weight: 600;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }
        .btn-primary::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
            transition: left 0.5s;
        }
        .btn-primary:hover::before {
            left: 100%;
        }
        .btn-primary:hover { 
            background: linear-gradient(135deg, #A20000 0%, #8B0000 100%);
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(162, 0, 0, 0.3);
        }
        .products-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 20px;
            margin-bottom: 40px;
        }
        .pagination-container {
            display: flex;
            justify-content: center;
            align-items: center;
            margin: 40px 0;
            gap: 15px;
        }
        .pagination-info {
            color: #666;
            font-size: 0.9rem;
            margin: 0 20px;
        }
        .pagination {
            margin: 0;
        }
        .page-link {
            color: #333;
            border: 1px solid #dee2e6;
            padding: 8px 12px;
            margin: 0 2px;
            border-radius: 8px;
            transition: all 0.2s ease;
        }
        .page-link:hover {
            background: #A20000;
            color: white;
            border-color: #A20000;
        }
        .page-item.active .page-link {
            background: #A20000;
            border-color: #A20000;
        }
        .page-item.disabled .page-link {
            color: #6c757d;
            background: #fff;
            border-color: #dee2e6;
        }
        .floating-cart-btn {
            position: fixed;
            left: 20px;
            bottom: 30px;
            z-index: 1200;
            background: linear-gradient(135deg, #A20000 0%, #8B0000 100%);
            color: #fff;
            border-radius: 50px;
            box-shadow: 0 6px 25px rgba(162, 0, 0, 0.4);
            padding: 12px 24px 12px 16px;
            font-size: 1.1rem;
            display: flex;
            align-items: center;
            border: none;
            transition: all .3s ease;
            font-weight: 600;
            text-decoration: none;
        }
        .floating-cart-btn:hover {
            background: linear-gradient(135deg, #A20000 0%, #8B0000 100%);
            color: #fff;
            text-decoration: none;
            transform: translateY(-3px);
            box-shadow: 0 8px 30px rgba(162, 0, 0, 0.5);
        }
        .floating-cart-btn .bi {
            font-size: 1.5rem;
            margin-right: 10px;
        }
        .floating-cart-count {
            background: #ffc107;
            color: #212529;
            font-weight: bold;
            margin-left: 10px;
            border-radius: 50%;
            font-size: 0.9rem;
            padding: 4px 8px;
            min-width: 24px;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            animation: pulse 2s infinite;
        }
        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.1); }
            100% { transform: scale(1); }
        }
        @media (max-width: 768px) {
            .navbar {
                padding: 6px 0;
                height: 56px; /* Altura fixa para o navbar em mobile */
            }
            .navbar-brand {
                font-size: 1.3rem;
            }
            .search-bar-fixed {
                top: 56px; /* Posicionado exatamente abaixo do navbar mobile */
                padding: 12px 0;
                height: 76px; /* Altura fixa para a barra de pesquisa */
            }
            body {
                padding-top: 132px; /* 56px (navbar) + 76px (search-bar) = 132px */
            }
            .products-grid {
                grid-template-columns: repeat(2, 1fr);
                gap: 15px;
            }
            .banner-title {
                font-size: 2rem;
            }
            .banner-slide {
                padding: 40px 0;
                min-height: 250px;
            }
            .pagination-container {
                flex-direction: column;
                gap: 10px;
            }
            .pagination-info {
                margin: 0;
            }
            .search-input {
                padding: 10px 15px;
                font-size: 0.9rem;
            }
            .mic-button {
                width: 45px;
                height: 45px;
                font-size: 1.1rem;
            }
            .search-container {
                padding: 0 15px;
            }
        }
        @media (max-width: 480px) {
            .navbar {
                padding: 4px 0;
                height: 52px; /* Altura ainda menor para telas muito pequenas */
            }
            .navbar-brand {
                font-size: 1.2rem;
            }
            .search-bar-fixed {
                top: 52px; /* Posicionado exatamente abaixo do navbar pequeno */
                padding: 10px 0;
                height: 70px; /* Altura menor para a barra de pesquisa */
            }
            body {
                padding-top: 122px; /* 52px (navbar) + 70px (search-bar) = 122px */
            }
            .banner-title {
                font-size: 1.8rem;
            }
            .catalog-container {
                padding: 0 10px;
            }
            .card-body {
                padding: 15px;
            }
            .product-name {
                font-size: 1rem;
            }
            .price-current {
                font-size: 1.2rem;
            }
            .search-container {
                padding: 0 12px;
            }
            .search-input {
                padding: 8px 12px;
                font-size: 0.85rem;
            }
            .mic-button {
                width: 40px;
                height: 40px;
                font-size: 1rem;
            }
        }
        .modal-content {
            border-radius: 16px;
            border: none;
            box-shadow: 0 20px 60px rgba(0,0,0,0.2);
        }
        .modal-header {
            background: linear-gradient(135deg, #A20000 0%, #8B0000 100%);
            color: white;
            border-radius: 16px 16px 0 0;
            border-bottom: none;
        }
        .modal-product-img {
            max-width: 100%; 
            max-height: 300px;
            object-fit: contain; 
            display: block;
            margin: 0 auto 15px auto;
            border-radius: 8px;
        }
        footer {
            background: linear-gradient(135deg, #8B0000 0%, #A20000 100%);
            color: #ffc107;
            padding: 30px 0;
            text-align: center;
            margin-top: 60px;
            position: relative;
        }
        footer::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 3px;
            background: linear-gradient(90deg, #A20000, #ffc107, #A20000);
        }
    </style>
</head>
<body>
    <!-- Navbar -->
    <nav class="navbar navbar-expand-lg navbar-dark">
        <div class="container-fluid">
            <a class="navbar-brand" href="#">
                <center><img src="logo2.jpg" class="navbar-logo" alt="Logo"></center>
                <center>Mercadinho Pajeú</center>
            </a>
            <!-- Menu -->
            <div class="dropdown">
                <button class="menu-toggle dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                    <i class="bi bi-three-dots-vertical"></i>
                </button>
                <ul class="dropdown-menu dropdown-menu-end">
                    <li><h6 class="dropdown-header">Contatos/Sociais</h6></li>
                    <li><a class="dropdown-item" href="mailto:mercadopajeu@gmail.com"><i class="bi bi-envelope"></i>Email</a></li>
                    <li><a class="dropdown-item" href="https://www.instagram.com/mercadinhopajeu/"><i class="bi bi-instagram"></i>Instagram</a></li>
                    <li><a class="dropdown-item" href="https://maps.app.goo.gl/ncVcetgw3QiukAaCA"><i class="bi bi-geo-alt"></i>Localização</a></li>
                    <li><a class="dropdown-item" href="https://wa.me/5583988814996"><i class="bi bi-whatsapp"></i>Whatsapp</a></li>
                    <button id="btnInstall" style="display:none; margin:10px 0 0 10px;">Instalar app</button>
                    <li><hr class="dropdown-divider"></li>
                    <li><h6 class="dropdown-header">Categorias</h6></li>
                    <li><a class="dropdown-item" href="#"><i class="bi bi-apple"></i>Hortifruti</a></li>
                    <li><a class="dropdown-item" href="#"><i class="bi bi-droplet"></i>Laticínios</a></li>
                    <li><a class="dropdown-item" href="#"><i class="bi bi-cup-straw"></i>Bebidas</a></li>
                    <li><a class="dropdown-item" href="#"><i class="bi bi-box-seam"></i>Limpeza</a></li>
                    <li><a class="dropdown-item" href="#"><i class="bi bi-grid-3x3"></i>Mercearia</a></li>
                </ul>
            </div>
        </div>
    </nav>

    <!-- Barra de pesquisa fixa -->
    <div class="search-bar-fixed">
        <div class="search-container">
            <input type="text" class="search-input" id="searchInput" placeholder="Buscar produto...">
            <button class="mic-button" id="micButton" onclick="startVoiceSearch()">
                <i class="bi bi-mic"></i>
            </button>
            <div class="search-results" id="searchResults"></div>
        </div>
    </div>

    <!-- Banner rotativo -->
    <div id="bannerCarousel" class="carousel slide banner-carousel" data-bs-ride="carousel" data-bs-interval="5000">
        <div class="carousel-indicators">
            <?php foreach($banners as $index => $banner): ?>
                <button type="button" data-bs-target="#bannerCarousel" data-bs-slide-to="<?php echo $index; ?>" 
                        <?php echo $index === 0 ? 'class="active" aria-current="true"' : ''; ?> 
                        aria-label="Slide <?php echo $index + 1; ?>"></button>
            <?php endforeach; ?>
        </div>
        <div class="carousel-inner">
            <?php foreach($banners as $index => $banner): ?>
                <div class="carousel-item <?php echo $index === 0 ? 'active' : ''; ?>" 
                    style="background-image: url('<?php echo $banner['imagem']; ?>');">
                    <div class="banner-slide">
                        <div class="container">
                            <div class="banner-content">
                                <h1 class="banner-title"><?php echo $banner['titulo']; ?></h1>
                                <p class="banner-subtitle"><?php echo $banner['subtitulo']; ?></p>
                                <a href="#produtos" class="banner-cta"><?php echo $banner['cta']; ?></a>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
        <button class="carousel-control-prev" type="button" data-bs-target="#bannerCarousel" data-bs-slide="prev">
            <span class="carousel-control-prev-icon" aria-hidden="true"></span>
            <span class="visually-hidden">Anterior</span>
        </button>
        <button class="carousel-control-next" type="button" data-bs-target="#bannerCarousel" data-bs-slide="next">
            <span class="carousel-control-next-icon" aria-hidden="true"></span>
            <span class="visually-hidden">Próximo</span>
        </button>
    </div>

    <!-- Carrinho flutuante -->
    <a href="carrinho.php" class="floating-cart-btn">
        <i class="bi bi-cart3"></i>
        Carrinho
        <span class="floating-cart-count">
            <?php echo count($carrinho); ?>
        </span>
    </a>

    <!-- Conteúdo principal -->
    <div class="container catalog-container">
        <h1 class="catalog-title" id="produtos">Catálogo de Produtos</h1>
        <?php if (isset($_GET['msg']) && $_GET['msg']=='adicionado'): ?>
            <div class="alert alert-success text-center">✅ Produto adicionado ao carrinho!</div>
        <?php endif; ?>
        <div class="pagination-container">
            <div class="pagination-info">
                Mostrando <?php echo ($offset + 1); ?> - <?php echo min($offset + $produtosPorPagina, $totalProdutos); ?> 
                de <?php echo $totalProdutos; ?> produtos
            </div>
        </div>
        <div class="products-grid">
            <?php
            if ($produtos):
                foreach($produtos as $row): ?>
                    <div class="card h-100">
                        <?php if ($row['foto']): ?>
                            <img src="admin/fotos/<?php echo htmlspecialchars($row['foto']); ?>"
                                class="card-img-top"
                                alt="<?php echo htmlspecialchars($row['nome']); ?>"
                                data-bs-toggle="modal"
                                data-bs-target="#produtoModal"
                                data-id="<?php echo $row['id']; ?>"
                                data-nome="<?php echo htmlspecialchars($row['nome']); ?>"
                                data-codigo="<?php echo htmlspecialchars($row['codigo']); ?>"
                                data-preco="<?php echo number_format($row['preco'], 2, ',', '.'); ?>"
                                data-foto="admin/fotos/<?php echo htmlspecialchars($row['foto']); ?>"
                            >
                        <?php else: ?>
                            <img src="https://via.placeholder.com/300x200?text=Sem+Imagem"
                                class="card-img-top"
                                alt="Sem imagem"
                                data-bs-toggle="modal"
                                data-bs-target="#produtoModal"
                                data-id="<?php echo $row['id']; ?>"
                                data-nome="<?php echo htmlspecialchars($row['nome']); ?>"
                                data-codigo="<?php echo htmlspecialchars($row['codigo']); ?>"
                                data-preco="<?php echo number_format($row['preco'], 2, ',', '.'); ?>"
                                data-foto="https://via.placeholder.com/300x200?text=Sem+Imagem"
                            >
                        <?php endif; ?>
                        <div class="card-body d-flex flex-column">
                            <div class="flex-grow-1">
                                <h5 class="product-name"><?php echo htmlspecialchars($row['nome']); ?></h5>
                                <p class="product-code">Cód: <?php echo htmlspecialchars($row['codigo']); ?></p>
                                <?php
                                    $precoAtual = $row['preco'];
                                    $precoDe = $precoAtual * 1.12;
                                ?>
                                <div class="product-price">
                                    <span class="price-old">
                                        De R$ <?php echo number_format($precoDe, 2, ',', '.'); ?>
                                    </span>
                                    <span class="price-current">
                                        Por R$ <?php echo number_format($precoAtual, 2, ',', '.'); ?>
                                    </span>
                                </div>
                            </div>
                            <a href="?add=<?php echo $row['id']; ?>" class="btn btn-primary w-100">
                                <i class="bi bi-cart-plus me-2"></i>Adicionar ao Carrinho
                            </a>
                        </div>
                    </div>
            <?php endforeach;
            else: ?>
                <div class="col-12">
                    <div class="alert alert-warning text-center">⚠️ Nenhum produto encontrado.</div>
                </div>
            <?php endif; ?>
        </div>
        <?php if ($totalPaginas > 1): ?>
            <div class="pagination-container">
                <nav aria-label="Navegação de páginas">
                    <ul class="pagination">
                        <?php if ($paginaAtual > 1): ?>
                            <li class="page-item">
                                <a class="page-link" href="?pagina=1" aria-label="Primeira">
                                    <i class="bi bi-chevron-double-left"></i>
                                </a>
                            </li>
                        <?php endif; ?>
                        <?php if ($paginaAtual > 1): ?>
                            <li class="page-item">
                                <a class="page-link" href="?pagina=<?php echo $paginaAtual - 1; ?>" aria-label="Anterior">
                                    <i class="bi bi-chevron-left"></i>
                                </a>
                            </li>
                        <?php endif; ?>
                        <?php
                        $inicio = max(1, $paginaAtual - 2);
                        $fim = min($totalPaginas, $paginaAtual + 2);
                        for ($i = $inicio; $i <= $fim; $i++): ?>
                            <li class="page-item <?php echo $i == $paginaAtual ? 'active' : ''; ?>">
                                <a class="page-link" href="?pagina=<?php echo $i; ?>"><?php echo $i; ?></a>
                            </li>
                        <?php endfor; ?>
                        <?php if ($paginaAtual < $totalPaginas): ?>
                            <li class="page-item">
                                <a class="page-link" href="?pagina=<?php echo $paginaAtual + 1; ?>" aria-label="Próxima">
                                    <i class="bi bi-chevron-right"></i>
                                </a>
                            </li>
                        <?php endif; ?>
                        <?php if ($paginaAtual < $totalPaginas): ?>
                            <li class="page-item">
                                <a class="page-link" href="?pagina=<?php echo $totalPaginas; ?>" aria-label="Última">
                                    <i class="bi bi-chevron-double-right"></i>
                                </a>
                            </li>
                        <?php endif; ?>
                    </ul>
                </nav>
            </div>
        <?php endif; ?>
    </div>
    <!-- Modal do produto -->
    <div class="modal fade" id="produtoModal" tabindex="-1" aria-labelledby="produtoModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <form id="produtoModalForm" method="get" class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="produtoModalLabel">Detalhes do Produto</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <img id="modalProductImg" src="" alt="" class="modal-product-img">
                        </div>
                        <div class="col-md-6">
                            <h4 id="modalProductName"></h4>
                            <p><strong>Código:</strong> <span id="modalProductCode"></span></p>
                            <h3 class="text-success" id="modalProductPrice"></h3>
                            <div class="mt-4 mb-3">
                                <label for="modalQtd" class="form-label">Quantidade:</label>
                                <input type="number" name="qtd" id="modalQtd" class="form-control" min="1" value="1" style="max-width:100px;display:inline-block;">
                            </div>
                            <input type="hidden" name="add" id="modalAddId">
                            <button type="submit" class="btn btn-primary btn-lg w-100">
                                <i class="bi bi-cart-plus me-2"></i>Adicionar ao Carrinho
                            </button>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
    <!-- Modal para resultado da busca -->
    <div class="modal fade" id="searchProductModal" tabindex="-1" aria-labelledby="searchProductModalLabel" aria-hidden="true">
      <div class="modal-dialog modal-lg">
        <form method="get" class="modal-content" id="searchProductForm">
          <div class="modal-header">
            <h5 class="modal-title" id="searchProductModalLabel">Produto</h5>
            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Fechar"></button>
          </div>
          <div class="modal-body">
            <div class="row">
              <div class="col-md-6">
                <img id="searchModalImg" src="" alt="" class="modal-product-img">
              </div>
              <div class="col-md-6">
                <h4 id="searchModalName"></h4>
                <p><strong>Código:</strong> <span id="searchModalCode"></span></p>
                <h3 class="text-success" id="searchModalPrice"></h3>
                <div class="mb-3 mt-4">
                  <label for="searchModalQtd" class="form-label">Quantidade:</label>
                  <input type="number" name="qtd" id="searchModalQtd" class="form-control" min="1" value="1" style="max-width:100px;display:inline-block;">
                </div>
                <input type="hidden" name="add" id="searchModalAddId">
                <button type="submit" class="btn btn-primary btn-lg w-100">
                  <i class="bi bi-cart-plus me-2"></i>Adicionar ao Carrinho
                </button>
              </div>
            </div>
          </div>
        </form>
      </div>
    </div>
    <footer>
        <div class="container">
            <p>&copy; 2025 Mercadinho Pajeú. Todos os direitos reservados.</p>
            <p>Sua compra fácil, rápida e com preço baixo.</p>
        </div>
    </footer>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        const produtos = <?php echo json_encode($todosProdutos); ?>;
        const searchInput = document.getElementById('searchInput');
        const searchResults = document.getElementById('searchResults');
        searchInput.addEventListener('input', function() {
            const query = this.value.toLowerCase().trim();
            if (query.length < 2) {
                searchResults.style.display = 'none';
                return;
            }
            const results = produtos.filter(produto => 
                produto.nome.toLowerCase().includes(query) ||
                produto.codigo.toLowerCase().includes(query)
            ).slice(0, 5);
            if (results.length > 0) {
                searchResults.innerHTML = results.map(produto => `
                    <div class="search-result-item" 
                        onclick="showSearchProductModal(${produto.id})"
                        style="display:flex;align-items:center;gap:15px;">
                        <img src="${produto.foto ? 'admin/fotos/' + produto.foto : 'https://via.placeholder.com/60x60?text=Sem+Imagem'}" 
                             alt="${produto.nome}" style="width:60px;height:60px;object-fit:contain;border-radius:8px;border:1px solid #eee;background:#fff;">
                        <div style="flex:1;">
                            <div class="search-result-name">${produto.nome}</div>
                            <div class="search-result-code">Código: ${produto.codigo}</div>
                            <div class="search-result-price">R$ ${parseFloat(produto.preco).toFixed(2).replace('.', ',')}</div>
                        </div>
                    </div>
                `).join('');
                searchResults.style.display = 'block';
            } else {
                searchResults.innerHTML = '<div class="search-result-item">Nenhum produto encontrado</div>';
                searchResults.style.display = 'block';
            }
        });
        document.addEventListener('click', function(e) {
            if (!e.target.closest('.search-container')) {
                searchResults.style.display = 'none';
            }
        });
        function showSearchProductModal(productId) {
            const produto = produtos.find(p => p.id == productId);
            if (!produto) return;
            document.getElementById('searchModalImg').src = produto.foto ? 'admin/fotos/' + produto.foto : 'https://via.placeholder.com/300x200?text=Sem+Imagem';
            document.getElementById('searchModalName').textContent = produto.nome;
            document.getElementById('searchModalCode').textContent = produto.codigo;
            document.getElementById('searchModalPrice').textContent = 'R$ ' + parseFloat(produto.preco).toFixed(2).replace('.', ',');
            document.getElementById('searchModalQtd').value = 1;
            document.getElementById('searchModalAddId').value = produto.id;
            var myModal = new bootstrap.Modal(document.getElementById('searchProductModal'));
            myModal.show();
            searchResults.style.display = 'none';
        }
        document.getElementById('searchProductForm').addEventListener('submit', function(e) {
            e.preventDefault();
            const id = document.getElementById('searchModalAddId').value;
            const qtd = document.getElementById('searchModalQtd').value;
            window.location.href = `?add=${id}&qtd=${qtd}`;
        });
        let recognition;
        const micButton = document.getElementById('micButton');
        function startVoiceSearch() {
            if (!('webkitSpeechRecognition' in window) && !('SpeechRecognition' in window)) {
                alert('Seu navegador não suporta reconhecimento de voz.');
                return;
            }
            recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
            recognition.lang = 'pt-BR';
            recognition.continuous = false;
            recognition.interimResults = false;
            recognition.onstart = function() {
                micButton.classList.add('recording');
                micButton.innerHTML = '<i class="bi bi-mic-fill"></i>';
            };
            recognition.onresult = function(event) {
                const transcript = event.results[0][0].transcript;
                searchInput.value = transcript;
                searchInput.dispatchEvent(new Event('input'));
            };
            recognition.onerror = function(event) {
                micButton.classList.remove('recording');
                micButton.innerHTML = '<i class="bi bi-mic"></i>';
                if (event.error === 'not-allowed') {
                    alert('Permissão para usar o microfone foi negada. Por favor, permita o acesso ao microfone.');
                } else {
                    alert('Erro no reconhecimento de voz: ' + event.error);
                }
            };
            recognition.onend = function() {
                micButton.classList.remove('recording');
                micButton.innerHTML = '<i class="bi bi-mic"></i>';
            };
            recognition.start();
        }
        const produtoModal = document.getElementById('produtoModal');
        produtoModal.addEventListener('show.bs.modal', function (event) {
            const button = event.relatedTarget;
            const id = button.getAttribute('data-id');
            const nome = button.getAttribute('data-nome');
            const codigo = button.getAttribute('data-codigo');
            const preco = button.getAttribute('data-preco');
            const foto = button.getAttribute('data-foto');
            document.getElementById('modalProductName').textContent = nome;
            document.getElementById('modalProductCode').textContent = codigo;
            document.getElementById('modalProductPrice').textContent = 'R$ ' + preco;
            document.getElementById('modalProductImg').src = foto;
            document.getElementById('modalProductImg').alt = nome;
            document.getElementById('modalQtd').value = 1;
            document.getElementById('modalAddId').value = id;
        });
        document.getElementById('produtoModalForm').addEventListener('submit', function(e) {
            e.preventDefault();
            const id = document.getElementById('modalAddId').value;
            const qtd = document.getElementById('modalQtd').value;
            window.location.href = `?add=${id}&qtd=${qtd}`;
        });
        let deferredPrompt;
        window.addEventListener('beforeinstallprompt', (e) => {
          e.preventDefault();
          deferredPrompt = e;
          document.getElementById('btnInstall').style.display = 'inline-block';
        });
        document.getElementById('btnInstall').addEventListener('click', async () => {
          if (deferredPrompt) {
            deferredPrompt.prompt();
            await deferredPrompt.userChoice;
            document.getElementById('btnInstall').style.display = 'none';
            deferredPrompt = null;
          }
        });
        if ('serviceWorker' in navigator) {
          window.addEventListener('load', () => {
            navigator.serviceWorker.register('/sw.js');
          });
        }
    </script>
</body>
</html>