<?php
// 1. CONFIGURAÇÕES INICIAIS
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
date_default_timezone_set('America/Sao_Paulo');

// Define que estamos no módulo da Copa para o Header
$is_copa26 = true; 

if (file_exists('../config.php')) {
    include_once('../config.php');
} else {
    include_once('config.php');
}

include_once('../header.php');

// 2. MAPEAMENTO RIGOROSO (Organizado por grupos para facilitar a exibição em linhas)
$grupos = [
    "ESPECIAIS" => ["00"],
    "FWC" => ["FWC 1", "FWC 2", "FWC 3", "FWC 4", "FWC 5", "FWC 6", "FWC 7", "FWC 8"],
    "MEX" => range(1, 20),
    "RSA" => range(1, 20),
    "KOR" => range(1, 20),
    "CZE" => range(1, 20),
    "CAN" => range(1, 20),
    "BIH" => range(1, 20),
    "QAT" => range(1, 20),
    "SUI" => range(1, 20),
    "BRA" => range(1, 20),
    "MAR" => range(1, 20),
    "HAI" => range(1, 20),
    "SCO" => range(1, 20),
    "USA" => range(1, 20),
    "PAR" => range(1, 20),
    "AUS" => range(1, 20),
    "TUR" => range(1, 20),
    "GER" => range(1, 20),
    "CUW" => range(1, 20),
    "CIV" => range(1, 20),
    "ECU" => range(1, 20),
    "NED" => range(1, 20),
    "JPN" => range(1, 20),
    "SWE" => range(1, 20),
    "TUN" => range(1, 20),
    "BEL" => range(1, 20), 
    "EGV" => range(1, 20),
    "IRN" => range(1, 20),
    "NZL" => range(1, 20),
    "ESP" => range(1, 20),
    "CPV" => range(1, 20),
    "KSA" => range(1, 20),
    "URU" => range(1, 20),
    "FRA" => range(1, 20),
    "SEN" => range(1, 20),
    "IRQ" => range(1, 20),
    "NOR" => range(1, 20),
    "ARG" => range(1, 20),
    "ALG" => range(1, 20),
    "AUT" => range(1, 20),
    "JOR" => range(1, 20),
    "POR" => range(1, 20),
    "COD" => range(1, 20),
    "UZB" => range(1, 20),
    "COL" => range(1, 20),
    "ENG" => range(1, 20),
    "CRO" => range(1, 20),
    "GHA" => range(1, 20),
    "PAN" => range(1, 20),
    "FCW" => range(9, 19),
    "CC" => range(1, 14)
];

// Monta o mapeamento linear para manter a compatibilidade com os IDs do banco
$mapeamento = [];
foreach ($grupos as $prefixo => $itens) {
    foreach ($itens as $item) {
        $mapeamento[] = (is_numeric($item)) ? $prefixo . " " . $item : $item;
    }
}
$total_figurinhas = count($mapeamento);

// 3. LÓGICA DE GERENCIAMENTO (Mantida idêntica)
if (isset($_GET['toggle'])) {
    $id = (int)$_GET['toggle'];
    $index = $id - 1;
    $codigo_exibicao = $mapeamento[$index];

    $check = $conn->query("SELECT quantidade, repetidas FROM figurinhas WHERE id = $id");
    
    if ($check && $f = $check->fetch_assoc()) {
        if ($f['quantidade'] == 0) {
            $conn->query("UPDATE figurinhas SET quantidade = 1 WHERE id = $id");
        } else {
            echo "<script>
                let op = prompt('FIGURINHA $codigo_exibicao:\\n1. ADICIONAR REPETIDA (+1)\\n2. DAR BAIXA (REMOVER 1 UNIDADE)');
                if(op == '1') { window.location.href='index.php?add_rep=$id'; }
                if(op == '2') { window.location.href='index.php?reduce=$id'; }
            </script>";
            exit();
        }
    } else {
        $conn->query("INSERT INTO figurinhas (id, codigo, quantidade) VALUES ($id, '$codigo_exibicao', 1)");
    }
    echo "<script>window.location.href='index.php#fig-$id';</script>";
    exit();
}

if (isset($_GET['add_rep'])) {
    $id = (int)$_GET['add_rep'];
    $conn->query("UPDATE figurinhas SET repetidas = repetidas + 1 WHERE id = $id");
    echo "<script>window.location.href='index.php#fig-$id';</script>"; 
    exit();
}

if (isset($_GET['reduce'])) {
    $id = (int)$_GET['reduce'];
    $check = $conn->query("SELECT quantidade, repetidas FROM figurinhas WHERE id = $id");
    if ($f = $check->fetch_assoc()) {
        if ($f['repetidas'] > 0) {
            $conn->query("UPDATE figurinhas SET repetidas = repetidas - 1 WHERE id = $id");
        } else {
            $conn->query("UPDATE figurinhas SET quantidade = 0 WHERE id = $id");
        }
    }
    echo "<script>window.location.href='index.php#fig-$id';</script>"; 
    exit();
}

// 4. BUSCA DE DADOS
$dados_banco = [];
$total_obtidas = 0;
$total_repetidas = 0;

$res = $conn->query("SELECT * FROM figurinhas");
if($res) {
    while($row = $res->fetch_assoc()) {
        $dados_banco[$row['id']] = $row;
        if($row['quantidade'] > 0) $total_obtidas++;
        $total_repetidas += (int)($row['repetidas'] ?? 0);
    }
}
?>

<style>
    .module-wrapper { display: flex; width: 100%; min-height: calc(100vh - 100px); text-transform: uppercase; flex-wrap: wrap; background: #fff; }
    .sidebar-indicators { width: 250px; background-color: #f0f0f0; border-right: 1px solid #ccc; padding: 15px; position: sticky; top: 0; height: fit-content; z-index: 100; }
    .indicator-card { background: #fff; border: 1px solid #ccc; border-radius: 4px; padding: 12px; margin-bottom: 15px; text-align: center; }
    .datagrid-container { flex: 1; min-width: 320px; padding: 15px; background: #fff; }
    .filter-btn { display: block; width: 100%; padding: 10px; margin-bottom: 5px; border: 1px solid #ccc; background: #fff; cursor: pointer; font-size: 10px; font-weight: bold; text-align: left; border-radius: 4px; }
    .filter-btn:hover { background: #eee; }
    .filter-btn.active { background: #00569e; color: #fff; border-color: #00569e; }
    
    /* AJUSTE PARA LINHA ÚNICA */
    .grupo-row { margin-bottom: 20px; }
    .grupo-titulo { font-size: 11px; font-weight: bold; color: #555; margin-bottom: 8px; border-bottom: 1px solid #eee; padding-bottom: 4px; }
    .grid-figurinhas { display: grid; grid-template-columns: repeat(auto-fill, minmax(65px, 1fr)); gap: 6px; }
    
    .figurinha { aspect-ratio: 3/4; background: #e9ecef; position: relative; cursor: pointer; display: flex; align-items: center; justify-content: center; border: 1px solid #ced4da; transition: transform 0.1s; text-align: center; }
    .figurinha:hover { border-color: #00569e; transform: scale(1.1); z-index: 5; }
    .num { font-weight: bold; color: #6c757d; font-size: 9px; padding: 2px; line-height: 1.1; }
    .have { background: #FFFF00 !important; border-color: #ffd700; }
    .have .num { color: #000; }
    .rep-badge { position: absolute; top: -6px; right: -6px; background: #d32f2f; color: white; font-size: 9px; padding: 2px 6px; border-radius: 12px; font-weight: bold; border: 1.5px solid white; box-shadow: 0 2px 4px rgba(0,0,0,0.2); }
    
    /* Filtros via CSS */
    .f-faltam .figurinha.have { display: none; }
    .f-tenho .figurinha:not(.have) { display: none; }
    .f-repetidas .figurinha:not(.is-rep) { display: none; }

    .btn-whatsapp { display: block; width: 100%; padding: 12px; margin-top: 10px; border: none; background: #25D366; color: #fff; cursor: pointer; font-size: 10px; font-weight: bold; text-align: center; border-radius: 4px; text-decoration: none; }
    .btn-whatsapp:hover { background: #128C7E; }

    @media (max-width: 768px) { .sidebar-indicators { width: 100%; position: relative; border-right: none; } .module-wrapper { flex-direction: column; } }
    html { scroll-behavior: smooth; }
</style>

<div class="module-wrapper">
    <div class="sidebar-indicators">
        <div class="indicator-card">
            <h4 style="font-size: 10px; color: #666; margin-bottom: 10px;">📊 STATUS DO ÁLBUM</h4>
            <div style="font-size: 20px; font-weight: bold; color: #00569e;"><?php echo $total_obtidas; ?> / <?php echo $total_figurinhas; ?></div>
            <div style="font-size: 12px; color: #2e7d32; font-weight: bold; margin-top: 5px;"><?php echo ($total_figurinhas > 0) ? round(($total_obtidas/$total_figurinhas)*100, 1) : 0; ?>% COMPLETO</div>
            <div style="font-size: 11px; color: #d32f2f; margin-top: 5px;">REPETIDAS: <?php echo $total_repetidas; ?></div>
        </div>

        <div style="margin-bottom: 20px;">
            <p style="font-size: 9px; font-weight: bold; color: #666; margin-bottom: 8px;">OPÇÕES DE VISUALIZAÇÃO:</p>
            <button class="filter-btn active" onclick="filtrar('todas', this)">📌 TODAS AS FIGURINHAS</button>
            <button class="filter-btn" onclick="filtrar('tenho', this)">✅ JÁ POSSUO (<?php echo $total_obtidas; ?>)</button>
            <button class="filter-btn" onclick="filtrar('faltam', this)">❌ AINDA FALTAM (<?php echo ($total_figurinhas - $total_obtidas); ?>)</button>
            <button class="filter-btn" onclick="filtrar('repetidas', this)">🔄 REPETIDAS (<?php echo $total_repetidas; ?>)</button>
            <button class="btn-whatsapp" onclick="compartilharWhatsApp()">📲 COMPARTILHAR COLEÇÃO</button>
        </div>

        <a href="../index.php" style="display:block; text-decoration:none; color:#00569e; font-size:10px; font-weight:bold; border: 2px solid #00569e; padding: 12px; text-align: center; border-radius: 4px;">➡️ VOLTAR AO PAINEL</a>
    </div>

    <div class="datagrid-container" id="grid-container">
        <div style="font-weight: bold; font-size: 14px; margin-bottom: 20px; color: #00569e; border-left: 4px solid #00569e; padding-left: 10px;">
            ⚽ ÁLBUM COPA 2026 - TJ PRESENTES
        </div>

        <?php 
        $contador_global = 1;
        foreach ($grupos as $prefixo => $itens): 
        ?>
            <div class="grupo-row">
                <div class="grupo-titulo"><?php echo $prefixo; ?></div>
                <div class="grid-figurinhas">
                    <?php 
                    foreach ($itens as $item):
                        $label = (is_numeric($item)) ? $prefixo . " " . $item : $item;
                        $id_sticker = $contador_global;
                        $f = isset($dados_banco[$id_sticker]) ? $dados_banco[$id_sticker] : ['quantidade' => 0, 'repetidas' => 0];
                        $classe_rep = ($f['repetidas'] > 0) ? 'is-rep' : '';
                    ?>
                        <div id="fig-<?php echo $id_sticker; ?>" 
                             class="figurinha <?php echo ($f['quantidade'] > 0) ? 'have' : ''; ?> <?php echo $classe_rep; ?>" 
                             data-id="<?php echo $id_sticker; ?>"
                             data-label="<?php echo $label; ?>"
                             data-have="<?php echo ($f['quantidade'] > 0) ? '1' : '0'; ?>"
                             data-rep="<?php echo $f['repetidas']; ?>"
                             onclick="location.href='index.php?toggle=<?php echo $id_sticker; ?>'">
                            <span class="num"><?php echo $label; ?></span>
                            <?php if($f['repetidas'] > 0): ?><span class="rep-badge"><?php echo $f['repetidas']; ?></span><?php endif; ?>
                        </div>
                    <?php 
                        $contador_global++;
                    endforeach; 
                    ?>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
</div>

<script>
function filtrar(tipo, btn) {
    document.querySelectorAll('.filter-btn').forEach(b => b.classList.remove('active'));
    btn.classList.add('active');
    const container = document.getElementById('grid-container');
    container.classList.remove('f-tenho', 'f-faltam', 'f-repetidas');
    if(tipo !== 'todas') { container.classList.add('f-' + tipo); }
    window.scrollTo({top: 0, behavior: 'smooth'});
}

function compartilharWhatsApp() {
    let tenho = [];
    let faltam = [];
    let repetidas = [];

    document.querySelectorAll('.figurinha').forEach(fig => {
        let label = fig.getAttribute('data-label');
        let isHave = fig.getAttribute('data-have') === '1';
        let reps = parseInt(fig.getAttribute('data-rep'));

        if (isHave) {
            tenho.push(label);
        } else {
            faltam.push(label);
        }
        if (reps > 0) {
            repetidas.push(label + "(" + reps + "x)");
        }
    });

    let msg = "*⚽ MEU ÁLBUM COPA 2026 - TJ PRESENTES* \n\n";
    msg += "📊 *RESUMO:* \n";
    msg += "✅ Tenho: " + tenho.length + " \n";
    msg += "❌ Faltam: " + faltam.length + " \n";
    msg += "🔄 Repetidas: " + repetidas.length + " \n\n";

    if(repetidas.length > 0) {
        msg += "*🔄 MINHAS REPETIDAS:* \n" + repetidas.join(", ") + " \n\n";
    }

    if(faltam.length > 0) {
        msg += "*❌ AINDA FALTAM:* \n" + faltam.join(", ") + " \n";
    }

    let url = "https://api.whatsapp.com/send?text=" + encodeURIComponent(msg);
    window.open(url, '_blank');
}
</script>