<?php
// 1. IMPORTAÇÕES E CONFIGURAÇÕES
// Alterado para ../ para buscar na raiz conforme sua imagem de pastas
require_once '../config.php';
$db = $conn; // Ajuste para reconhecer a variável $conn do seu config.php
include '../header.php'; 

date_default_timezone_set('America/Sao_Paulo');

// 3. CAPTURA DOS RESULTADOS DO DIA (SCRAPING)
$url = "https://www.ojogodobicho.com/deu_no_poste.htm";
$options = ['http' => ['method' => "GET", 'header' => "User-Agent: Mozilla/5.0\r\n"]];
$context = stream_context_create($options);
$html = @file_get_contents($url, false, $context);
$resultados = [];

if ($html !== FALSE) {
    $dom = new DOMDocument();
    @$dom->loadHTML($html);
    $xpath = new DOMXPath($dom);
    $tables = $xpath->query("//table");
    foreach ($tables as $table) {
        $rows = $xpath->query(".//tr", $table);
        foreach ($rows as $row) {
            $cols = $xpath->query(".//td", $row);
            if ($cols->length >= 2) {
                $p = trim($cols->item(0)->nodeValue);
                if (preg_match('/^[1-7]/', $p)) {
                    $resultados[$p] = [
                        'PPT' => $cols->item(1) ? trim($cols->item(1)->nodeValue) : '',
                        'PTM' => $cols->item(2) ? trim($cols->item(2)->nodeValue) : '',
                        'PT'  => $cols->item(3) ? trim($cols->item(3)->nodeValue) : '',
                        'PTV' => $cols->item(4) ? trim($cols->item(4)->nodeValue) : '',
                        'PTN' => $cols->item(5) ? trim($cols->item(5)->nodeValue) : '',
                        'COR' => $cols->item(6) ? trim($cols->item(6)->nodeValue) : ''
                    ];
                }
            }
        }
        break; 
    }
}

// 4. LÓGICA DOS BILHETES (TOP 3)
$g_top1 = $db->query("SELECT valor FROM ranking_bicho WHERE tipo='grupo' AND posicao='primeiro' ORDER BY total DESC LIMIT 3");
$m_top1 = $db->query("SELECT valor FROM ranking_bicho WHERE tipo='milhar' AND posicao='primeiro' ORDER BY total DESC LIMIT 3");

$g_topG = $db->query("SELECT valor FROM ranking_bicho WHERE tipo='grupo' AND posicao='geral' ORDER BY total DESC LIMIT 3");
$m_topG = $db->query("SELECT valor FROM ranking_bicho WHERE tipo='milhar' AND posicao='geral' ORDER BY total DESC LIMIT 3");
?>

<style>
    /* Ajuste de Visibilidade Global */
    body { background-color: #f4f4f4; }
    
    /* Estilo do Bilhete */
    .bilhete {
        background: #fffef0;
        border: 1px solid #bbb;
        box-shadow: 3px 3px 10px rgba(0,0,0,0.15);
        padding: 15px;
        font-family: 'Courier New', Courier, monospace;
        color: #000; /* Texto bem preto para o bilhete */
        width: 100%;
        max-width: 320px;
        margin: 0 auto 20px auto;
        position: relative;
    }
    .bilhete::after {
        content: "";
        position: absolute;
        bottom: -10px; left: 0; right: 0;
        height: 10px;
        background: linear-gradient(-45deg, #fffef0 5px, transparent 0), linear-gradient(45deg, #fffef0 5px, transparent 0);
        background-size: 10px 10px;
    }
    .bilhete-header { text-align: center; border-bottom: 2px dashed #000; padding-bottom: 5px; margin-bottom: 10px; }
    .bilhete-linha { display: flex; justify-content: space-between; font-size: 14px; margin: 3px 0; border-bottom: 1px solid #eee; }
    .bilhete-footer { text-align: center; border-top: 2px dashed #000; margin-top: 10px; padding-top: 5px; font-size: 11px; font-weight: bold; }

    /* Layout do Painel */
    .dashboard-grid { display: flex; gap: 15px; align-items: flex-start; }
    .col-resultados { flex: 1.8; }
    .col-rankings { flex: 1.2; display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
    
    /* Tabelas Excel com Contraste Alto */
    .excel-table { width: 100%; border-collapse: collapse; background: #fff; }
    .excel-table td, .excel-table th { padding: 5px; font-size: 11px; border: 1px solid #999; text-align: center; }
    
    /* CORREÇÃO DOS TÍTULOS - Cores Fortes e Texto Branco */
    .th-header-main { background: #1b5e20 !important; color: #ffffff !important; font-weight: bold; text-transform: uppercase; }
    .th-sub-header { background: #424242 !important; color: #ffffff !important; font-weight: bold; }
    
    .bg-vermelho { background: #b71c1c !important; color: #ffffff !important; }
    .bg-azul { background: #0d47a1 !important; color: #ffffff !important; }
    .bg-preto { background: #212121 !important; color: #ffffff !important; }
    .bg-cinza-escuro { background: #455a64 !important; color: #ffffff !important; }
    .bg-vitoria { background: #dff0d8 !important; color: #3c763d !important; font-weight: bold; }
</style>

<div class="container" style="padding-top: 10px;">
    
    <div style="display: flex; gap: 20px; justify-content: center; flex-wrap: wrap; margin-bottom: 20px;">
        
        <div class="bilhete">
            <div class="bilhete-header">
                <strong style="font-size: 16px;">JOGO DO BICHO</strong><br>
                <span>JOGO DO DIA: SÓ 1º PRÊMIO</span><br>
                <small><?php echo date('d/m/Y H:i'); ?></small>
            </div>
            <div style="text-align:center; font-weight:bold; background:#000; color:#fff; margin-bottom:5px;">GRUPOS RECOMENDADOS</div>
            <?php while($g = $g_top1->fetch_assoc()): ?>
                <div class="bilhete-linha"><span>GRUPO:</span> <strong><?php echo str_pad($g['valor'], 2, "0", STR_PAD_LEFT); ?></strong></div>
            <?php endwhile; ?>
            
            <div style="text-align:center; font-weight:bold; background:#000; color:#fff; margin: 10px 0 5px 0;">MILHARES RECOMENDADAS</div>
            <?php while($m = $m_top1->fetch_assoc()): ?>
                <div class="bilhete-linha"><span>MILHAR:</span> <strong><?php echo $m['valor']; ?></strong></div>
            <?php endwhile; ?>
            <div class="bilhete-footer">*** BOA SORTE ***</div>
        </div>

        <div class="bilhete">
            <div class="bilhete-header">
                <strong style="font-size: 16px;">JOGO DO BICHO</strong><br>
                <span>JOGO DO DIA: 1º AO 5º</span><br>
                <small><?php echo date('d/m/Y H:i'); ?></small>
            </div>
            <div style="text-align:center; font-weight:bold; background:#000; color:#fff; margin-bottom:5px;">GRUPOS RECOMENDADOS</div>
            <?php while($g = $g_topG->fetch_assoc()): ?>
                <div class="bilhete-linha"><span>GRUPO:</span> <strong><?php echo str_pad($g['valor'], 2, "0", STR_PAD_LEFT); ?></strong></div>
            <?php endwhile; ?>
            
            <div style="text-align:center; font-weight:bold; background:#000; color:#fff; margin: 10px 0 5px 0;">MILHARES RECOMENDADAS</div>
            <?php while($m = $m_topG->fetch_assoc()): ?>
                <div class="bilhete-linha"><span>MILHAR:</span> <strong><?php echo $m['valor']; ?></strong></div>
            <?php endwhile; ?>
            <div class="bilhete-footer">*** BOA SORTE ***</div>
        </div>
    </div>

    <div class="dashboard-grid">
        <div class="col-resultados">
            <table class="excel-table">
                <thead>
                    <tr><th colspan="7" class="th-header-main">MAPA DE RESULTADOS DO DIA</th></tr>
                    <tr>
                        <th class="th-sub-header">PR</th>
                        <th class="th-sub-header">PPT</th>
                        <th class="th-sub-header">PTM</th>
                        <th class="th-sub-header">PT</th>
                        <th class="th-sub-header">PTV</th>
                        <th class="th-sub-header">PTN</th>
                        <th class="th-sub-header" style="background:#2e7d32 !important;">COR</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($resultados as $p => $v): ?>
                    <tr>
                        <td style="background:#eee; font-weight:bold; color:#000;"><?php echo $p; ?>º</td>
                        <td><?php echo str_replace('0000-0','',$v['PPT']); ?></td>
                        <td><?php echo str_replace('0000-0','',$v['PTM']); ?></td>
                        <td><?php echo str_replace('0000-0','',$v['PT']); ?></td>
                        <td><?php echo str_replace('0000-0','',$v['PTV']); ?></td>
                        <td><?php echo str_replace('0000-0','',$v['PTN']); ?></td>
                        <td class="bg-vitoria"><?php echo str_replace('0000-0','',$v['COR']); ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <div class="col-rankings">
            <table class="excel-table">
                <tr><th colspan="2" class="bg-vermelho">GRUPO (1º)</th></tr>
                <?php $r1 = $db->query("SELECT valor, total FROM ranking_bicho WHERE tipo='grupo' AND posicao='primeiro' ORDER BY total DESC LIMIT 5");
                while($r = $r1->fetch_assoc()) echo "<tr><td style='font-weight:bold;'>G-".str_pad($r['valor'],2,"0",STR_PAD_LEFT)."</td><td style='background:#f9f9f9;'>{$r['total']}x</td></tr>"; ?>
            </table>
            <table class="excel-table">
                <tr><th colspan="2" class="bg-azul">GRUPO (1-5)</th></tr>
                <?php $rg = $db->query("SELECT valor, total FROM ranking_bicho WHERE tipo='grupo' AND posicao='geral' ORDER BY total DESC LIMIT 5");
                while($r = $rg->fetch_assoc()) echo "<tr><td style='font-weight:bold;'>G-".str_pad($r['valor'],2,"0",STR_PAD_LEFT)."</td><td style='background:#f9f9f9;'>{$r['total']}x</td></tr>"; ?>
            </table>
            <table class="excel-table">
                <tr><th colspan="2" class="bg-preto">MILHAR (1º)</th></tr>
                <?php $m1 = $db->query("SELECT valor, total FROM ranking_bicho WHERE tipo='milhar' AND posicao='primeiro' ORDER BY total DESC LIMIT 5");
                while($r = $m1->fetch_assoc()) echo "<tr><td style='font-weight:bold; color:#d32f2f;'>{$r['valor']}</td><td style='background:#f9f9f9;'>{$r['total']}x</td></tr>"; ?>
            </table>
            <table class="excel-table">
                <tr><th colspan="2" class="bg-cinza-escuro">MILHAR (1-5)</th></tr>
                <?php $mg = $db->query("SELECT valor, total FROM ranking_bicho WHERE tipo='milhar' AND posicao='geral' ORDER BY total DESC LIMIT 5");
                while($r = $mg->fetch_assoc()) echo "<tr><td style='font-weight:bold; color:#0d47a1;'>{$r['valor']}</td><td style='background:#f9f9f9;'>{$r['total']}x</td></tr>"; ?>
            </table>
        </div>
    </div>
</div>

<?php echo "</div></body></html>"; ?>