<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
require_once 'config.php';

try {
    $db = new PDO('mysql:host=localhost;dbname=erniinrk_bekasi', 'erniinrk_bekasi', 'Kelentit123@');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}

$bulanIndo = [
    'January' => 'Januari', 'February' => 'Februari', 'March' => 'Maret',
    'April' => 'April', 'May' => 'Mei', 'June' => 'Juni',
    'July' => 'Juli', 'August' => 'Agustus', 'September' => 'September',
    'October' => 'Oktober', 'November' => 'November', 'December' => 'Desember'
];

// Format date for display
function formatDisplayDate($date, $bulanIndo) {
    if (!$date) return ['day' => '--', 'month' => '--', 'year' => '--'];
    
    $timestamp = strtotime($date);
    return [
        'day' => date('d', $timestamp),
        'month' => $bulanIndo[date('F', $timestamp)] ?? date('F', $timestamp),
        'year' => date('Y', $timestamp)
    ];
}

// Ambil semua market dari database
try {
    $stmt = $db->query("DESCRIBE markets");
    $columns = $stmt->fetchAll(PDO::FETCH_COLUMN);
    
    if (in_array('status', $columns) && in_array('display_order', $columns)) {
        $market_query = "SELECT * FROM markets WHERE status = 1 ORDER BY display_order ASC, market_name ASC";
    } elseif (in_array('status', $columns)) {
        $market_query = "SELECT * FROM markets WHERE status = 1 ORDER BY market_name ASC";
    } else {
        $market_query = "SELECT * FROM markets ORDER BY market_name ASC";
    }
    
    $stmt = $db->prepare($market_query);
    $stmt->execute();
    $all_markets = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch (Exception $e) {
    $stmt = $db->prepare("SELECT * FROM markets ORDER BY market_name ASC");
    $stmt->execute();
    $all_markets = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Normalisasi data market
foreach ($all_markets as &$market) {
    if (!isset($market['display_name']) || empty($market['display_name'])) {
        $market['display_name'] = strtoupper($market['market_name']);
    }
    if (!isset($market['color_theme']) || empty($market['color_theme'])) {
        $market['color_theme'] = 'color-1';
    }
    if (!isset($market['result_time'])) {
        $market['result_time'] = '15:30:00';
    }
}
unset($market);

// Ambil hasil terakhir untuk setiap market
$market_results = [];
foreach ($all_markets as $market) {
    try {
        $stmt = $db->prepare("SELECT * FROM lottery_results WHERE market = ? ORDER BY draw_date DESC, created_at DESC LIMIT 1");
        $stmt->execute([$market['market_name']]);
        $market_results[$market['market_name']] = $stmt->fetch(PDO::FETCH_ASSOC);
    } catch (Exception $e) {
        $market_results[$market['market_name']] = null;
    }
}

// Ambil history untuk setiap market
$market_histories = [];
foreach ($all_markets as $market) {
    try {
        $stmt = $db->prepare("SELECT * FROM lottery_results WHERE market = ? ORDER BY draw_date DESC LIMIT 10");
        $stmt->execute([$market['market_name']]);
        $history = $stmt->fetchAll(PDO::FETCH_ASSOC);
        $market_histories[$market['market_name']] = array_slice($history, 0, 4);
    } catch (Exception $e) {
        $market_histories[$market['market_name']] = [];
    }
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <base href="https://pastijepe.online/" />
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">		
    <meta content="width=device-width, initial-scale=1.0" name="viewport"/>
    <meta name="description" content="BEKASI POOLS - Lottery Results & Live Draws"/>
    <title>BEKASI POOLS • Live Lottery Results</title>
    <link href="https://pastijepe.online/" rel="canonical"/>
    <link href="https://pastijepe.online/assets/img/iconpapuapools.png" rel="icon"/>
    
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.5.1/css/all.min.css">
    
    <style>
        /* TEMA BEKASI - KUNING EMAS DOMINAN */
        
        body {
            background: #D4AF37; 
            background: linear-gradient(145deg, #F5D76E 0%, #D4AF37 40%, #B8860B 100%);
            color: #0a0a0a;
        }
        
        .gold-BEKASI { color: #D4AF37; }
        .bg-gold-BEKASI { background-color: #D4AF37; }
        .border-gold-BEKASI { border-color: #D4AF37; }
        
        .neon-gold {
            color: #0a0a0a;
            text-shadow: 0 0 10px rgba(255, 215, 0, 0.8), 0 0 20px rgba(255, 215, 0, 0.5);
        }
        
        .accent-red { color: #C0392B; }
        .accent-white { color: #ecf0f1; }

        .glass {
            background: rgba(10, 10, 10, 0.95);
            backdrop-filter: blur(10px);
            border: 2px solid #0a0a0a;
            box-shadow: 0 8px 32px rgba(0,0,0,0.3);
        }
        
        .glass-gold {
            background: rgba(10, 10, 10, 0.95);
            border: 2px solid #0a0a0a;
            box-shadow: 0 8px 32px rgba(0,0,0,0.3);
        }

        .digit-ball {
            background: #D4AF37;
            color: #0a0a0a;
            border: 2px solid #0a0a0a;
            box-shadow: 0 0 15px rgba(212, 175, 55, 0.4);
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
        }

        .header-bar { background: #D4AF37 !important; box-shadow: 0 4px 20px rgba(212, 175, 55, 0.3); }
        .logo-font { font-weight: 800; letter-spacing: 1px; }
        
        .stat-box {
            background: rgba(10, 10, 10, 0.85);
            border: 2px solid #D4AF37;
            border-radius: 24px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.3);
            color: #D4AF37;
        }
        .stat-box .stat-number { color: #F5D76E; }
        .stat-box .stat-label { color: #ffffff; }
        
        .neon-ijo {
            color: #0cff00;
            text-shadow: 0 0 10px rgba(12, 255, 0, 0.8), 0 0 20px rgba(255, 255, 255, 0.5);
        }
        
        /* --- RESPONSIVE MOBILE --- */
        @media (max-width: 640px) {
            nav .flex.items-center.gap-x-8 { display: none !important; }
            nav .flex.items-center.gap-x-3 .text-2xl { font-size: 1.1rem !important; }
            nav .w-10.h-10 { width: 32px !important; height: 32px !important; font-size: 1rem !important; }
            nav .px-6.py-4 { padding: 10px 16px !important; }
            
            .pt-24 { padding-top: 80px !important; }
            .pb-16 { padding-bottom: 40px !important; }
            .text-6xl { font-size: 2.5rem !important; line-height: 1.2 !important; }
            .text-2xl { font-size: 1.1rem !important; }
            .mb-12 { margin-bottom: 24px !important; }
            .px-6 { padding-left: 12px !important; padding-right: 12px !important; }
            
            .grid-cols-2 { gap: 8px !important; }
            .stat-box.p-6 { padding: 12px !important; }
            .stat-box .text-4xl { font-size: 1.5rem !important; }
            
            .market-card .px-8 { padding-left: 12px !important; padding-right: 12px !important; }
            .market-card .py-6 { padding-top: 12px !important; padding-bottom: 12px !important; }
            .market-card .text-3xl { font-size: 1.3rem !important; }
            .market-card .text-2xl { font-size: 1rem !important; }
            
            .digit-ball.text-3xl.w-14.h-14 { width: 40px !important; height: 40px !important; font-size: 1.2rem !important; }
            .digit-ball.text-xl.w-10.h-10 { width: 28px !important; height: 28px !important; font-size: 0.9rem !important; }
            .flex.gap-3 { gap: 6px !important; }
            .flex.gap-2 { gap: 4px !important; }
            .mb-10 { margin-bottom: 16px !important; }
            
            .grid-cols-2 { gap: 8px !important; }
            .text-4xl.font-bold { font-size: 1.2rem !important; }
            .px-8.py-6 { padding: 10px 12px !important; }
            .px-8.pb-8 { padding: 10px 12px !important; }
            .px-5.py-3 { padding: 8px 10px !important; }
            .inline-block.w-6.h-6 { width: 20px !important; height: 20px !important; font-size: 0.7rem !important; }
        }
    </style>
</head>
<body class="min-h-screen pb-12">

    <!-- KONTEN UTAMA -->
    <div class="max-w-7xl mx-auto px-4 sm:px-6">
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 sm:gap-8 mt-6 sm:mt-8">
            
            <?php foreach ($all_markets as $market): ?>
            <?php
                $market_result = $market_results[$market['market_name']] ?? null;
                $market_history = $market_histories[$market['market_name']] ?? [];
                $market_date = formatDisplayDate($market_result['draw_date'] ?? null, $bulanIndo);
                $result_time_display = substr($market['result_time'], 0, 5);
                
                // Cari waktu draw berikutnya
                $now = new DateTime();
                $target_time = new DateTime($now->format('Y-m-d') . ' ' . $market['result_time']);
                
                // Jika waktu target sudah lewat, tambahkan 1 hari
                if ($now > $target_time) {
                    $target_time->modify('+1 day');
                }
                
                $target_timestamp = $target_time->getTimestamp();
                $safe_market_id = preg_replace('/[^a-zA-Z0-9]/', '_', $market['market_name']);
            ?>
            
            <div class="market-card glass-gold rounded-3xl overflow-hidden border border-gold-BEKASI/30">
                <div class="bg-gradient-to-r from-[#1a1a1a] to-[#0a0a0a] px-4 sm:px-8 py-4 sm:py-6 flex items-center justify-between border-b border-gold-BEKASI/20">
                    <div>
                        <div class="uppercase tracking-[2px] sm:tracking-[3px] text-[10px] sm:text-xs gold-BEKASI/70 font-medium">PASARAN</div>
                        <h3 class="text-xl sm:text-3xl font-bold logo-font gold-BEKASI"><?= htmlspecialchars($market['display_name']) ?></h3>
                    </div>
                    <div class="text-right">
                        <div class="text-[10px] sm:text-xs text-gray-500">DRAW DATE</div>
                        <div class="text-sm sm:text-2xl font-mono font-semibold text-white">
                            <?= $market_date['day'] ?> <?= $market_date['month'] ?> <?= $market_date['year'] ?>
                        </div>
                    </div>
                </div>

                <div class="p-4 sm:p-8 bg-black/80">
                    <div class="text-gray-400 text-sm sm:text-2xl font-mono font-semibold mb-2 sm:mb-3 text-center">1ST PRIZE</div>
                    <div class="flex justify-center gap-2 sm:gap-3 mb-6 sm:mb-10 flex-wrap">
                        <?php if ($market_result && !empty($market_result['first_prize'])): ?>
                            <?php foreach (str_split($market_result['first_prize']) as $digit): ?>
                                <div class="digit-ball text-xl sm:text-3xl w-10 sm:w-14 h-10 sm:h-14 rounded-full"><?= htmlspecialchars($digit) ?></div>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <div class="text-gray-500 text-base sm:text-xl">Waiting for result...</div>
                        <?php endif; ?>
                    </div>

                    <div class="grid grid-cols-2 gap-3 sm:gap-6">
                        <div>
                            <div class="text-gray-400 text-xs sm:text-sm font-mono font-semibold mb-2 sm:mb-3 text-center">2ND PRIZE</div>
                            <div class="flex gap-1 sm:gap-2 justify-center flex-wrap">
                                <?php if ($market_result && !empty($market_result['second_prize'])): ?>
                                    <?php foreach (str_split($market_result['second_prize']) as $digit): ?>
                                        <div class="digit-ball text-sm sm:text-xl w-7 sm:w-10 h-7 sm:h-10 rounded-full"><?= htmlspecialchars($digit) ?></div>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </div>
                        </div>
                        <div>
                            <div class="text-gray-400 text-xs sm:text-sm font-mono font-semibold mb-2 sm:mb-3 text-center">3RD PRIZE</div>
                            <div class="flex gap-1 sm:gap-2 justify-center flex-wrap">
                                <?php if ($market_result && !empty($market_result['third_prize'])): ?>
                                    <?php foreach (str_split($market_result['third_prize']) as $digit): ?>
                                        <div class="digit-ball text-sm sm:text-xl w-7 sm:w-10 h-7 sm:h-10 rounded-full"><?= htmlspecialchars($digit) ?></div>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    
                    <div class="grid grid-cols-2 gap-3 sm:gap-6 mt-4 sm:mt-6">
                        <div>
                            <div class="text-gray-400 text-xs sm:text-sm font-mono font-semibold mb-2 sm:mb-3 text-center">STARTER</div>
                            <div class="flex gap-1 sm:gap-2 justify-center flex-wrap">
                                <?php if ($market_result && !empty($market_result['starter_prize'])): ?>
                                    <?php foreach (str_split($market_result['starter_prize']) as $digit): ?>
                                        <div class="digit-ball text-sm sm:text-xl w-7 sm:w-10 h-7 sm:h-10 rounded-full"><?= htmlspecialchars($digit) ?></div>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </div>
                        </div>
                        <div>
                            <div class="text-gray-400 text-xs sm:text-sm font-mono font-semibold mb-2 sm:mb-3 text-center">CONSOLATION</div>
                            <div class="flex gap-1 sm:gap-2 justify-center flex-wrap">
                                <?php if ($market_result && !empty($market_result['consolation_prize'])): ?>
                                    <?php foreach (str_split($market_result['consolation_prize']) as $digit): ?>
                                        <div class="digit-ball text-sm sm:text-xl w-7 sm:w-10 h-7 sm:h-10 rounded-full"><?= htmlspecialchars($digit) ?></div>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Countdown & Info -->
                <div class="border-t border-gold-BEKASI/20 bg-[#0d0a00] px-4 sm:px-8 py-4 sm:py-6">
                    <div class="flex flex-col sm:flex-row items-center justify-between gap-3 sm:gap-0">
                        <div>
                            <div class="text-[10px] sm:text-xs text-gray-500">NEXT DRAW</div>
                            <div class="text-base sm:text-lg font-medium gold-BEKASI"><?= $result_time_display ?></div>
                        </div>
                        
                        <div class="text-center">
                            <!-- PERBAIKAN: Gunakan data-target -->
                            <div id="countdown-<?= $safe_market_id ?>" 
                                 class="countdown text-xl sm:text-4xl font-bold font-mono text-white tabular-nums"
                                 data-target="<?= $target_timestamp ?>">
                               00:00:00
                            </div>
                        </div>
                        
                        <div class="text-right">
                            <a href="market.php?name=<?= urlencode($market['market_name']) ?>" 
                               class="inline-flex items-center gap-x-1 sm:gap-x-2 gold-BEKASI hover:text-yellow-500 transition-colors text-xs sm:text-sm font-medium">
                                FULL HISTORY 
                                <i class="fas fa-arrow-right"></i>
                            </a>
                        </div>
                    </div>
                </div>

                <!-- Mini History -->
                <div class="px-4 sm:px-8 pb-4 sm:pb-8 bg-[#0d0d0d]">
                    <div class="text-[10px] sm:text-xs uppercase tracking-widest text-gray-500 mb-3 sm:mb-4">Recent Results</div>
                    <div class="space-y-2 sm:space-y-3">
                        <?php foreach ($market_history as $row): ?>
                        <div class="flex items-center justify-between bg-white/5 hover:bg-gold-BEKASI/10 transition-colors rounded-2xl px-3 sm:px-5 py-2 sm:py-3 border border-white/5">
                            <div class="text-gray-400 text-xs sm:text-sm"><?= htmlspecialchars($row['draw_date']) ?></div>
                            <div class="flex gap-0.5 sm:gap-1">
                                <?php foreach (str_split($row['first_prize']) as $d): ?>
                                    <span style="color:#D4AF37;" class="inline-block w-5 sm:w-6 h-5 sm:h-6 bg-black gold-BEKASI border border-gold-BEKASI/30 text-[10px] sm:text-xs flex items-center justify-center rounded-lg"><?= $d ?></span>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
            
        </div>
    </div>

    <!-- FOOTER -->
    <footer class="mt-16 sm:mt-24 border-t border-black/40 py-8 sm:py-12 bg-[#0a0a0a]">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 text-center text-gray-500 text-xs sm:text-sm">
            <p>Must be 18+ • Play responsibly</p>
            <p class="mt-1">© 2026 BEKASI POOLS. All Rights Reserved.</p>
        </div>
    </footer>

    <script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
    <script>
        function startCountdowns() {
            // Loop semua elemen yang memiliki class countdown
            document.querySelectorAll('.countdown').forEach(function(el) {
                // Ambil timestamp target dari atribut data-target
                var targetTimestamp = parseInt(el.getAttribute('data-target'));
                
                if (!targetTimestamp) return;
                
                // Update setiap detik
                var timer = setInterval(function() {
                    var now = Math.floor(new Date().getTime() / 1000);
                    var timeLeft = targetTimestamp - now;
                    
                    if (timeLeft <= 0) {
                        clearInterval(timer);
                        el.innerHTML = '<span class="text-red-500 text-sm sm:text-xl">DRAWING NOW</span>';
                        return;
                    }
                    
                    var hours = Math.floor(timeLeft / 3600);
                    var minutes = Math.floor((timeLeft % 3600) / 60);
                    var seconds = timeLeft % 60;
                    
                    el.textContent = hours.toString().padStart(2, '0') + ':' + 
                                     minutes.toString().padStart(2, '0') + ':' + 
                                     seconds.toString().padStart(2, '0');
                }, 1000);
            });
        }
        
        $(document).ready(function() {
            startCountdowns();
            
            // Auto refresh every 60 seconds
            setTimeout(function() {
                window.location.reload();
            }, 60000);
        });
    </script>
</body>
</html>