<?php
require_once '../admin/config.php';
try {
    $db = new PDO('mysql:host=localhost;dbname=erniinrk_solo', 'erniinrk_solo', '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'
];
function calculateCountdown($last_draw_date, $result_time, $result_end_time = null) {
    if (!$result_time) return 0;
    $now = new DateTime();
    if (!$result_end_time) {
        $result_end_time = date('H:i:s', strtotime($result_time . ' +1 hour'));
    }
    $result_time_today = new DateTime($now->format('Y-m-d') . ' ' . $result_time);
    $result_end_time_today = new DateTime($now->format('Y-m-d') . ' ' . $result_end_time);
  
    if ($now > $result_time_today && $now < $result_end_time_today) {
        return 0;
    }
    if ($now > $result_end_time_today) {
        $result_time_today->modify('+1 day');
    }
    return max(0, $result_time_today->getTimestamp() - $now->getTimestamp());
}
function shouldShowCountdown($last_result, $result_time, $result_end_time = null) {
    $now = new DateTime();
    if (!$result_end_time) {
        $result_end_time = date('H:i:s', strtotime($result_time . ' +1 hour'));
    }
    $result_time_today = new DateTime($now->format('Y-m-d') . ' ' . $result_time);
    $result_end_time_today = new DateTime($now->format('Y-m-d') . ' ' . $result_end_time);
  
    if ($now > $result_end_time_today) return true;
    if (!$last_result) return true;
  
    $last_draw = new DateTime($last_result['draw_date'] . ' ' . $last_result['result_time']);
    return $last_draw < $result_time_today;
}
function formatDisplayDate($date, $bulanIndo) {
    if (!$date) return ['day' => '--', 'month' => '--', 'year' => '--', 'full' => '--'];
    $timestamp = strtotime($date);
    $dayName = ['Sunday'=>'Minggu','Monday'=>'Senin','Tuesday'=>'Selasa','Wednesday'=>'Rabu','Thursday'=>'Kamis','Friday'=>'Jumat','Saturday'=>'Sabtu'];
    return [
        'day' => date('d', $timestamp),
        'month' => $bulanIndo[date('F', $timestamp)] ?? date('F', $timestamp),
        'year' => date('Y', $timestamp),
        'full' => ($dayName[date('l', $timestamp)] ?? date('l', $timestamp)) . ', ' . date('d', $timestamp) . ' ' . ($bulanIndo[date('F', $timestamp)] ?? date('F', $timestamp)) . ' ' . date('Y', $timestamp)
    ];
}

// Pagination
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$per_page = 12;
$offset = ($page - 1) * $per_page;

// Ambil semua market
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);
}
foreach ($all_markets as &$market) {
    if (empty($market['display_name'])) $market['display_name'] = strtoupper($market['market_name']);
    if (empty($market['color_theme'])) $market['color_theme'] = 'color-1';
    if (empty($market['result_time'])) $market['result_time'] = '15:30:00';
}
unset($market);

// ====================== FOKUS 1 MARKET ======================
$primary_market = $all_markets[0] ?? null;
$total_rows = 0;
$total_pages = 1;
$histories = [];
$latest = null;

if ($primary_market) {
    // Hasil terbaru
    $stmt = $db->prepare("SELECT * FROM lottery_results WHERE market = ? ORDER BY draw_date DESC, created_at DESC LIMIT 1");
    $stmt->execute([$primary_market['market_name']]);
    $latest = $stmt->fetch(PDO::FETCH_ASSOC);

    // Hitung total untuk pagination
    $countStmt = $db->prepare("SELECT COUNT(*) FROM lottery_results WHERE market = ?");
    $countStmt->execute([$primary_market['market_name']]);
    $total_rows = (int)$countStmt->fetchColumn();
    $total_pages = max(1, (int)ceil($total_rows / $per_page));

    if ($page > $total_pages) {
        $page = $total_pages;
        $offset = ($page - 1) * $per_page;
    }

    // Riwayat dengan pagination (max 10 per halaman)
    $stmt = $db->prepare("SELECT * FROM lottery_results WHERE market = ? ORDER BY draw_date DESC LIMIT ? OFFSET ?");
    $stmt->bindValue(1, $primary_market['market_name'], PDO::PARAM_STR);
    $stmt->bindValue(2, $per_page, PDO::PARAM_INT);
    $stmt->bindValue(3, $offset, PDO::PARAM_INT);
    $stmt->execute();
    $histories = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

$result_time = $primary_market['result_time'] ?? '15:30:00';
$result_end_time = $primary_market['result_end_time'] ?? date('H:i:s', strtotime($result_time . ' +1 hour'));
$show_countdown = shouldShowCountdown($latest, $result_time, $result_end_time);
$countdown_seconds = calculateCountdown($latest['draw_date'] ?? null, $result_time, $result_end_time);
$now = new DateTime();
$result_time_today = new DateTime($now->format('Y-m-d') . ' ' . $result_time);
$result_end_time_today = new DateTime($now->format('Y-m-d') . ' ' . $result_end_time);
$is_calculating = ($now > $result_time_today && $now < $result_end_time_today);
$display_date = formatDisplayDate($latest['draw_date'] ?? null, $bulanIndo);
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>SOLO POOLS • Hasil Harian</title>
    <link href="https://pastijepe.online/assets/img/faviconSOLO.png" rel="icon"/>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
       
        body {
            font-family: 'Segoe UI', system-ui, -apple-system, sans-serif;
            background: 
                linear-gradient(180deg, rgba(10,26,58,0.75) 0%, rgba(10,26,58,0.55) 100%),
                url('https://pastijepe.online/assets/img/SOLO.jpg') center/cover no-repeat;
            color: #333;
            line-height: 1.5;
        }

        /* ===== NAVBAR ===== */
        .navbar {
            background: linear-gradient(90deg, #0a1a3a 0%, #12254d 100%);
            padding: 0 20px;
            height: 70px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            position: sticky;
            top: 0;
            z-index: 1000;
            box-shadow: 0 4px 20px rgba(0,0,0,0.3);
        }
       
        .navbar-logo {
            display: flex;
            align-items: center;
            gap: 10px;
            text-decoration: none;
        }
       
        .navbar-logo img {
            height: 48px;
            width: auto;
        }
       
        .navbar-logo span {
            color: #D4AF37;
            font-weight: 800;
            font-size: 1.4rem;
            letter-spacing: 1px;
        }
       
        .navbar-menu {
            display: flex;
            gap: 8px;
            align-items: center;
        }
       
        .navbar-menu a {
            color: #fff;
            text-decoration: none;
            padding: 8px 16px;
            border-radius: 6px;
            font-size: 0.85rem;
            font-weight: 600;
            background: rgba(255,255,255,0.08);
            transition: all 0.25s ease;
        }
       
        .navbar-menu a:hover {
            background: #D4AF37;
            color: #0a1a3a;
        }
       
        .navbar-menu .lang {
            background: #D4AF37;
            color: #0a1a3a;
        }

        /* ===== HERO BANNER ===== */
        .hero {
            position: relative;
            background: 
                linear-gradient(180deg, rgba(10,26,58,0.75) 0%, rgba(10,26,58,0.55) 100%),
                url('https://pastijepe.online/assets/img/SOLO.jpg') center/cover no-repeat;
            height: 320px;
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
        }
       
        .hero-content {
            text-align: center;
            position: relative;
            z-index: 2;
            padding: 20px;
        }
       
        .hero-balls {
            display: flex;
            justify-content: center;
            gap: 14px;
            margin-bottom: 18px;
            flex-wrap: wrap;
        }
       
        .hero-ball {
            width: 58px;
            height: 58px;
            border-radius: 50%;
            background: radial-gradient(circle at 30% 30%, #fff 0%, #D4AF37 50%, #B8860B 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.7rem;
            font-weight: 800;
            color: #1a1a1a;
            box-shadow: 0 6px 20px rgba(0,0,0,0.4), inset -4px -4px 12px rgba(0,0,0,0.2);
            animation: floatBall 3s ease-in-out infinite;
        }
       
        .hero-ball:nth-child(2) { animation-delay: 0.3s; }
        .hero-ball:nth-child(3) { animation-delay: 0.6s; }
        .hero-ball:nth-child(4) { animation-delay: 0.9s; }
        .hero-ball:nth-child(5) { animation-delay: 1.2s; }
       
        @keyframes floatBall {
            0%, 100% { transform: translateY(0); }
            50% { transform: translateY(-12px); }
        }
       
        .hero h1 {
            color: #D4AF37;
            font-size: 2.2rem;
            font-weight: 800;
            text-shadow: 0 3px 15px rgba(0,0,0,0.5);
            letter-spacing: 1px;
            margin-bottom: 6px;
        }
       
        .hero h2 {
            color: #fff;
            font-size: 1.6rem;
            font-weight: 700;
            text-shadow: 0 2px 10px rgba(0,0,0,0.5);
        }

        /* ===== MAIN RESULT BOX ===== */
        .main-result {
            max-width: 780px;
            margin: -50px auto 30px;
            position: relative;
            z-index: 10;
            background: #fff;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 15px 40px rgba(0,0,0,0.15);
        }
       
        .result-header {
            background: linear-gradient(90deg, #8B0000, #C0392B);
            color: #fff;
            padding: 16px 24px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 10px;
        }
       
        .result-header h3 {
            font-size: 1.3rem;
            font-weight: 700;
        }
       
        .result-header .date {
            font-size: 0.9rem;
            opacity: 0.9;
        }
       
        .result-balls-main {
            display: flex;
            justify-content: center;
            gap: 16px;
            padding: 28px 20px;
            background: linear-gradient(180deg, #1a1a2e 0%, #16213e 100%);
        }
       
        .ball {
            width: 72px;
            height: 72px;
            border-radius: 50%;
            background: radial-gradient(circle at 30% 25%, #fff 0%, #D4AF37 45%, #B8860B 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 2.2rem;
            font-weight: 800;
            color: #1a1a1a;
            box-shadow: 0 8px 25px rgba(212,175,55,0.4), inset -5px -5px 15px rgba(0,0,0,0.25);
            position: relative;
        }
       
        .ball::after {
            content: '';
            position: absolute;
            top: 12%;
            left: 22%;
            width: 28%;
            height: 18%;
            background: radial-gradient(ellipse, rgba(255,255,255,0.7), transparent);
            border-radius: 50%;
        }
       
        .ball.empty {
            background: radial-gradient(circle at 30% 25%, #555, #222);
            color: #666;
            box-shadow: none;
        }
       
        .ball.calculating {
            animation: spinBall 0.5s ease-in-out infinite alternate;
        }
       
        @keyframes spinBall {
            from { transform: scale(1) rotate(-4deg); }
            to { transform: scale(1.06) rotate(4deg); }
        }

        /* Sub prizes */
        .sub-prizes {
            display: grid;
            grid-template-columns: 1fr 1fr;
            background: #f8f9fa;
        }
       
        .sub-prize {
            padding: 18px 16px;
            text-align: center;
            border: 1px solid #e9ecef;
        }
       
        .sub-prize h4 {
            font-size: 0.95rem;
            color: #8B0000;
            margin-bottom: 12px;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
       
        .sub-prize .balls {
            display: flex;
            justify-content: center;
            gap: 8px;
        }
       
        .sub-prize .ball {
            width: 48px;
            height: 48px;
            font-size: 1.4rem;
        }

        /* ===== COUNTDOWN ===== */
        .countdown-box {
            max-width: 780px;
            margin: 0 auto 30px;
            background: linear-gradient(90deg, #0a1a3a, #12254d);
            border-radius: 12px;
            padding: 18px 24px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 16px;
            box-shadow: 0 8px 25px rgba(0,0,0,0.15);
            color: #fff;
        }
       
        .countdown-info h4 {
            font-size: 1rem;
            color: #D4AF37;
            margin-bottom: 4px;
        }
       
        .countdown-info p {
            font-size: 0.85rem;
            opacity: 0.85;
        }
       
        .countdown-timer {
            display: flex;
            gap: 6px;
            font-family: 'Courier New', monospace;
        }
       
        .countdown-timer span {
            background: #D4AF37;
            color: #0a1a3a;
            font-size: 1.6rem;
            font-weight: 800;
            padding: 6px 10px;
            border-radius: 6px;
            min-width: 42px;
            text-align: center;
        }

        .history-section { max-width: 1100px; margin: 0 auto 50px; padding: 0 16px; }
        .history-title { text-align: center; background: linear-gradient(90deg, #0a1a3a, #12254d); color: #fff; padding: 14px; border-radius: 10px 10px 0 0; font-size: 1.15rem; font-weight: 700; letter-spacing: 1px; }
        .history-info { text-align: center; background: #fff; padding: 10px; font-size: 0.85rem; color: #666; border-bottom: 1px solid #eee; }
        .history-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 16px; background: #fff; padding: 20px; box-shadow: 0 8px 25px rgba(0,0,0,0.08); }
        .history-card { border: 1px solid #e0e0e0; border-radius: 10px; overflow: hidden; }
        .history-card-header { background: linear-gradient(90deg, #0a1a3a, #1a3a6e); color: #fff; padding: 12px 16px; text-align: center; }
        .history-card-header h5 { font-size: 0.95rem; font-weight: 700; }
        .history-card-header p { font-size: 0.8rem; opacity: 0.85; margin-top: 2px; }
        .history-card-body { padding: 16px; background: #f8fafc; }
        .history-row { display: flex; justify-content: space-between; align-items: center; padding: 8px 0; border-bottom: 1px solid #e9ecef; }
        .history-row:last-child { border-bottom: none; }
        .history-row .label { font-size: 0.85rem; font-weight: 600; color: #555; }
        .history-row .balls { display: flex; gap: 5px; }
        .history-row .ball { width: 34px; height: 34px; font-size: 1rem; }


        /* ===== FOOTER ===== */
        footer {
            background: #0a1a3a;
            color: rgba(255,255,255,0.6);
            text-align: center;
            padding: 24px 16px;
            font-size: 0.85rem;
        }
       
        footer p { margin: 4px 0; }

        /* ===== RESPONSIVE ===== */
        @media (max-width: 768px) {
            .navbar { height: 60px; padding: 0 12px; }
            .navbar-logo span { font-size: 1.1rem; }
            .navbar-menu a { padding: 6px 10px; font-size: 0.75rem; }
            .navbar-menu a span { display: none; }
           
            .hero { height: 260px; }
            .hero h1 { font-size: 1.5rem; }
            .hero h2 { font-size: 1.15rem; }
            .hero-ball { width: 46px; height: 46px; font-size: 1.3rem; }
           
            .main-result { margin: -40px 12px 24px; }
            .ball { width: 58px; height: 58px; font-size: 1.7rem; }
            .sub-prizes { grid-template-columns: 1fr; }
           
            .countdown-box { margin: 0 12px 24px; flex-direction: column; text-align: center; }
            .countdown-timer span { font-size: 1.3rem; min-width: 36px; }
        }
       
        @media (max-width: 480px) {
            .hero-balls { gap: 8px; }
            .hero-ball { width: 40px; height: 40px; font-size: 1.1rem; }
            .ball { width: 50px; height: 50px; font-size: 1.5rem; }
            .result-balls-main { gap: 10px; padding: 20px 12px; }
        }
        
        .pagination-wrap { background: #fff; padding: 16px 20px 20px; border-radius: 0 0 12px 12px; box-shadow: 0 8px 25px rgba(0,0,0,0.08); }
        .pagination { display: flex; justify-content: center; align-items: center; gap: 6px; flex-wrap: wrap; list-style: none; margin: 0; padding: 0; }
        .pagination a, .pagination span { display: inline-flex; align-items: center; justify-content: center; min-width: 38px; height: 38px; padding: 0 12px; border-radius: 8px; font-size: 0.9rem; font-weight: 600; text-decoration: none; transition: all 0.2s; }
        .pagination a { background: #f0f2f5; color: #0a1a3a; }
        .pagination a:hover { background: #D4AF37; color: #0a1a3a; }
        .pagination .active span { background: linear-gradient(90deg, #0a1a3a, #1a3a6e); color: #fff; }
        .pagination .disabled span { background: #f0f2f5; color: #bbb; cursor: not-allowed; }
        .pagination .dots span { background: transparent; color: #999; }
        footer { background: #0a1a3a; color: rgba(255,255,255,0.6); text-align: center; padding: 24px 16px; font-size: 0.85rem; }
        footer p { margin: 4px 0; }
        @media (max-width: 768px) {
            .navbar { height: 60px; padding: 0 12px; }
            .navbar-logo span { font-size: 1.1rem; }
            .navbar-menu a { padding: 6px 10px; font-size: 0.75rem; }
            .navbar-menu a span { display: none; }
            .hero { height: 220px; }
            .hero h1 { font-size: 1.5rem; }
            .hero h2 { font-size: 1.15rem; }
            .countdown-box { margin: -30px 12px 24px; flex-direction: column; text-align: center; }
            .countdown-timer span { font-size: 1.3rem; min-width: 36px; }
            .history-row .ball { width: 30px; height: 30px; font-size: 0.9rem; }
        }

    </style>
</head>
<body>
    <nav class="navbar">
        <a href="index.php" class="navbar-logo">
            <img src="https://i.ibb.co/1tStwTtk/Chat-GPT-Image-24-Jul-2026-14-31-09.png" alt="SOLO POOLS">
            <span>SOLO POOLS</span>
        </a>
        <div class="navbar-menu">
            <a href="index.php"><i class="fas fa-home"></i> <span>BERANDA</span></a>
            <a href="live.php"><i class="fas fa-broadcast-tower"></i> <span>UNDIAN LANGSUNG</span></a>
            <a href="/history"><i class="fas fa-history"></i> <span>RIWAYAT</span></a>
            <a href="#" class="lang"><i class="fas fa-globe"></i> BAHASA</a>
        </div>
    </nav>

    <section class="hero">
        <div class="hero-content">
            <h1>SOLO POOLS HASIL HARIAN</h1>
            <h2>MEMENANGKAN NOMOR KEBERUNTUNGAN</h2>
        </div>
    </section>

    <!-- MAIN RESULT -->
    <div class="main-result">
        <div class="result-header">
            <h3>1st Prize POOL</h3>
            <div class="date"><?= $display_date['full'] ?></div>
        </div>
       
        <div class="result-balls-main">
            <?php if ($latest && !empty($latest['first_prize'])): ?>
                <?php foreach (str_split($latest['first_prize']) as $digit): ?>
                    <div class="ball <?= $is_calculating ? 'calculating' : '' ?>">
                        <?= htmlspecialchars($digit) ?>
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <?php for ($i = 0; $i < 4; $i++): ?>
                    <div class="ball empty">?</div>
                <?php endfor; ?>
            <?php endif; ?>
        </div>
       
        <!-- Sub prizes (sementara pakai data history / placeholder) -->
        <div class="sub-prizes">
            <div class="sub-prize">
                <h4>2nd Prize</h4>
                <div class="balls">
                    <?php
                    $second = $latest['second_prize'] ?? null;  
                    if ($second) {
                        foreach (str_split($second) as $d) echo '<div class="ball">'.$d.'</div>';
                    } else {
                        for ($i=0;$i<4;$i++) echo '<div class="ball empty">?</div>';
                    }
                    ?>
                </div>
            </div>
            <div class="sub-prize">
                <h4>3rd Prize</h4>
                <div class="balls">
                    <?php
                    $third  = $latest['third_prize'] ?? null;   
                    if ($third) {
                        foreach (str_split($third) as $d) echo '<div class="ball">'.$d.'</div>';
                    } else {
                        for ($i=0;$i<4;$i++) echo '<div class="ball empty">?</div>';
                    }
                    ?>
                </div>
            </div>
        </div>
    </div>
    
    <div class="countdown-box">
        <div class="countdown-info">
            <h4><i class="fas fa-clock"></i> Hitung Mundur Undian Langsung</h4>
            <p>
                <?php if ($is_calculating): ?>
                    Sedang proses pengundian...
                <?php elseif ($show_countdown && $countdown_seconds > 0): ?>
                    Undian akan dimulai pada waktu yang ditentukan
                <?php else: ?>
                    Menunggu hasil berikutnya
                <?php endif; ?>
            </p>
        </div>
        <div class="countdown-timer" id="countdown" data-seconds="<?= $is_calculating ? 0 : $countdown_seconds ?>">
            <span class="h">00</span>
            <span class="m">00</span>
            <span class="s">00</span>
        </div>
    </div>

    <footer>
        <p>Must be 18+ • Play responsibly</p>
        <p>© 2026 SOLO POOLS. All Rights Reserved.</p>
    </footer>

    <script>
        function startCountdown() {
            const el = document.getElementById('countdown');
            if (!el) return;
            let timeLeft = parseInt(el.getAttribute('data-seconds')) || 0;
            const hEl = el.querySelector('.h');
            const mEl = el.querySelector('.m');
            const sEl = el.querySelector('.s');
            if (timeLeft <= 0) {
                hEl.textContent = '00';
                mEl.textContent = '00';
                sEl.textContent = '00';
                return;
            }
            const timer = setInterval(() => {
                if (timeLeft <= 0) {
                    clearInterval(timer);
                    location.reload();
                    return;
                }
                const h = Math.floor(timeLeft / 3600);
                const m = Math.floor((timeLeft % 3600) / 60);
                const s = timeLeft % 60;
                hEl.textContent = h.toString().padStart(2, '0');
                mEl.textContent = m.toString().padStart(2, '0');
                sEl.textContent = s.toString().padStart(2, '0');
                timeLeft--;
            }, 1000);
        }
        setTimeout(() => location.reload(), 60000);
        document.addEventListener('DOMContentLoaded', () => {
            startCountdown();
        });
    </script>
</body>
</html>
