<?php
require_once 'admin/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'
];

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' => '--'];
    
    $timestamp = strtotime($date);
    return [
        'day' => date('d', $timestamp),
        'month' => $bulanIndo[date('F', $timestamp)] ?? date('F', $timestamp),
        'year' => date('Y', $timestamp)
    ];
}

// Get market name from URL
$market_name = isset($_GET['name']) ? $_GET['name'] : '';
if (empty($market_name)) {
    die('Market not specified');
}

// Get market data
try {
    $stmt = $db->prepare("SELECT * FROM markets WHERE market_name = ?");
    $stmt->execute([$market_name]);
    $market = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$market) {
        die('Market not found');
    }
} catch (Exception $e) {
    die('Error loading market data');
}

// Get latest result
try {
    $stmt = $db->prepare("SELECT * FROM lottery_results WHERE market = ? ORDER BY draw_date DESC, created_at DESC LIMIT 1");
    $stmt->execute([$market_name]);
    $market_result = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $market_result = null;
}

// Get history
try {
    $stmt = $db->prepare("SELECT * FROM lottery_results WHERE market = ? ORDER BY draw_date DESC LIMIT 10");
    $stmt->execute([$market_name]);
    $market_history = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $market_history = array_slice($market_history, 0, 4);
} catch (Exception $e) {
    $market_history = [];
}

// Prepare display variables
$market_date = formatDisplayDate($market_result['draw_date'] ?? null, $bulanIndo);
$result_time = date('H:i:s', strtotime($market['result_time'] ?? '00:00:00'));
$result_end_time = $market['result_end_time'] ?? date('H:i:s', strtotime($market['result_time'] . ' +1 hour'));

$show_countdown = shouldShowCountdown($market_result, $market['result_time'], $result_end_time);
$countdown_seconds = calculateCountdown($market_result['draw_date'] ?? null, $market['result_time'], $result_end_time);

$now = new DateTime();
$result_time_today = new DateTime($now->format('Y-m-d') . ' ' . $market['result_time']);
$result_end_time_today = new DateTime($now->format('Y-m-d') . ' ' . $result_end_time);
$is_calculation_period = ($now > $result_time_today && $now < $result_end_time_today);

$safe_market_id = preg_replace('/[^a-zA-Z0-9]/', '_', $market['market_name']);
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <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="<?= htmlspecialchars($market['display_name']) ?> - Live Draw Results"/>
    <title><?= htmlspecialchars($market['display_name']) ?> • Live Draw</title>
    
    <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">
    
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            background: #0a0a0a;
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }

        .gold-BEKASI { color: #D4AF37; }
        .bg-gold-BEKASI { background-color: #D4AF37; }
        .border-gold-BEKASI { border-color: #D4AF37; }

        .market-card {
            background: linear-gradient(145deg, rgba(20, 20, 20, 0.98), rgba(10, 10, 10, 0.99));
            border: 2px solid rgba(212, 175, 55, 0.4);
            border-radius: 20px;
            overflow: hidden;
            box-shadow: 0 10px 60px rgba(212, 175, 55, 0.15);
            max-width: 500px;
            width: 100%;
            margin: 0 auto;
        }

        .market-header {
            background: linear-gradient(135deg, rgba(212, 175, 55, 0.15), rgba(10, 10, 10, 0.9));
            padding: 20px 24px;
            border-bottom: 2px solid rgba(212, 175, 55, 0.3);
            text-align: center;
        }

        .market-title {
            font-size: 2rem;
            font-weight: 800;
            letter-spacing: 2px;
            background: linear-gradient(135deg, #D4AF37, #F5D76E, #D4AF37);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }

        .market-subtitle {
            color: rgba(255, 255, 255, 0.5);
            font-size: 0.8rem;
            letter-spacing: 1px;
            margin-top: 4px;
        }

        .prize-section {
            padding: 24px;
            background: rgba(0, 0, 0, 0.5);
        }

        .prize-digits {
            display: flex;
            gap: 10px;
            justify-content: center;
            flex-wrap: wrap;
        }

        .prize-digit {
            width: 60px;
            height: 60px;
            border-radius: 14px;
            background: linear-gradient(145deg, #D4AF37, #b8960f);
            color: #0a0a0a;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 2rem;
            font-weight: 800;
            border: 2px solid rgba(255, 255, 255, 0.1);
            box-shadow: 0 4px 20px rgba(212, 175, 55, 0.3);
            transition: all 0.3s ease;
        }

        .prize-digit.small {
            width: 44px;
            height: 44px;
            font-size: 1.3rem;
            border-radius: 10px;
        }

        .prize-digit.calculating {
            animation: pulseGold 0.5s ease-in-out infinite alternate;
        }

        @keyframes pulseGold {
            0% {
                transform: scale(1);
                background: linear-gradient(145deg, #D4AF37, #b8960f);
            }
            100% {
                transform: scale(1.1);
                background: linear-gradient(145deg, #ffd700, #ff8c00);
                box-shadow: 0 0 40px rgba(212, 175, 55, 0.6);
            }
        }

        .prize-label {
            color: rgba(255, 255, 255, 0.7);
            font-size: 0.7rem;
            text-transform: uppercase;
            letter-spacing: 2px;
            font-weight: 600;
            margin-bottom: 8px;
        }

        .info-section {
            padding: 16px 24px;
            background: rgba(0, 0, 0, 0.7);
            border-top: 1px solid rgba(212, 175, 55, 0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 12px;
        }

        .time-info {
            display: flex;
            align-items: center;
            gap: 16px;
            flex-wrap: wrap;
        }

        .time-item {
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .time-item .label {
            font-size: 0.6rem;
            color: rgba(255, 255, 255, 0.4);
            text-transform: uppercase;
            letter-spacing: 1px;
        }

        .time-item .value {
            font-size: 1rem;
            font-weight: 700;
            color: #D4AF37;
        }

        .countdown-status {
            padding: 8px 16px;
            border-radius: 8px;
            font-weight: bold;
            display: inline-block;
            font-size: 1.2rem;
        }

        .countdown-calculation {
            background-color: #ffc107;
            color: #000000;
            animation: blink 1s infinite;
        }

        @keyframes blink {
            0% { opacity: 1; }
            50% { opacity: 0.3; }
            100% { opacity: 1; }
        }

        .countdown-ended {
            background-color: #6c757d;
            color: white;
        }

        .countdown-display {
            font-size: 2rem;
            font-weight: 800;
            font-family: 'Courier New', monospace;
            color: #ffffff;
            text-shadow: 0 0 20px rgba(212, 175, 55, 0.3);
            background: rgba(212, 175, 55, 0.1);
            padding: 8px 20px;
            border-radius: 12px;
            border: 1px solid rgba(212, 175, 55, 0.2);
        }

        .history-section {
            padding: 16px 24px 24px;
            background: rgba(0, 0, 0, 0.4);
        }

        .history-item {
            background: rgba(255, 255, 255, 0.03);
            border-radius: 10px;
            padding: 10px 16px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border: 1px solid rgba(255, 255, 255, 0.05);
            margin-bottom: 6px;
        }

        .history-item:last-child {
            margin-bottom: 0;
        }

        .history-date {
            color: rgba(255, 255, 255, 0.5);
            font-size: 0.8rem;
            font-weight: 500;
        }

        .history-digits {
            display: flex;
            gap: 4px;
        }

        .history-digit {
            width: 28px;
            height: 28px;
            border-radius: 6px;
            background: rgba(212, 175, 55, 0.15);
            color: #D4AF37;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 0.8rem;
            font-weight: 700;
            border: 1px solid rgba(212, 175, 55, 0.1);
        }

        .status-badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.7rem;
            font-weight: 600;
            letter-spacing: 0.5px;
        }

        .status-live {
            background: #00ff24;
            color: #000;
            animation: pulse 1s infinite;
        }

        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.5; }
            100% { opacity: 1; }
        }

        .status-waiting {
            background: #6c757d;
            color: #fff;
        }

        .status-calculating {
            background: #ffc107;
            color: #000;
            animation: blink 1s infinite;
        }

        @media (max-width: 480px) {
            body {
                padding: 10px;
            }
            
            .market-title {
                font-size: 1.5rem;
            }
            
            .prize-digit {
                width: 48px;
                height: 48px;
                font-size: 1.5rem;
            }
            
            .prize-digit.small {
                width: 36px;
                height: 36px;
                font-size: 1rem;
            }
            
            .prize-digits {
                gap: 6px;
            }
            
            .countdown-display {
                font-size: 1.5rem;
                padding: 6px 14px;
            }
            
            .info-section {
                flex-direction: column;
                gap: 8px;
            }
            
            .time-info {
                justify-content: center;
            }
        }
    </style>
</head>
<body>
    <div class="market-card">
        <!-- Header -->
        <div class="market-header">
            <div class="market-title"><?= htmlspecialchars($market['display_name']) ?></div>
            <div class="market-subtitle">
                <?= $market_date['day'] ?> <?= $market_date['month'] ?> <?= $market_date['year'] ?>
                <span class="mx-2">•</span>
                <?php if ($is_calculation_period): ?>
                    <span class="status-badge status-calculating">⚡ CALCULATING</span>
                <?php elseif ($market_result): ?>
                    <span class="status-badge status-live">● LIVE</span>
                <?php else: ?>
                    <span class="status-badge status-waiting">○ WAITING</span>
                <?php endif; ?>
            </div>
        </div>

        <!-- Prize Section -->
        <div class="prize-section">
            <!-- 1st Prize -->
            <div class="text-center mb-6">
                <div class="prize-label">🏆 1st Prize</div>
                <div class="prize-digits">
                    <?php if ($market_result && !empty($market_result['first_prize'])): ?>
                        <?php foreach (str_split($market_result['first_prize']) as $digit): ?>
                            <div class="prize-digit <?= $is_calculation_period ? 'calculating' : '' ?>">
                                <?= htmlspecialchars($digit) ?>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <span style="color: rgba(255,255,255,0.3); font-size: 1.2rem;">-- -- -- --</span>
                    <?php endif; ?>
                </div>
            </div>

            <!-- 2nd & 3rd Prize -->
            <div class="grid grid-cols-2 gap-4 mb-4">
                <div class="text-center">
                    <div class="prize-label">🥈 2nd Prize</div>
                    <div class="prize-digits">
                        <?php if ($market_result && !empty($market_result['second_prize'])): ?>
                            <?php foreach (str_split($market_result['second_prize']) as $digit): ?>
                                <div class="prize-digit small <?= $is_calculation_period ? 'calculating' : '' ?>">
                                    <?= htmlspecialchars($digit) ?>
                                </div>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <span style="color: rgba(255,255,255,0.3); font-size: 0.9rem;">-- -- -- --</span>
                        <?php endif; ?>
                    </div>
                </div>
                <div class="text-center">
                    <div class="prize-label">🥉 3rd Prize</div>
                    <div class="prize-digits">
                        <?php if ($market_result && !empty($market_result['third_prize'])): ?>
                            <?php foreach (str_split($market_result['third_prize']) as $digit): ?>
                                <div class="prize-digit small <?= $is_calculation_period ? 'calculating' : '' ?>">
                                    <?= htmlspecialchars($digit) ?>
                                </div>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <span style="color: rgba(255,255,255,0.3); font-size: 0.9rem;">-- -- -- --</span>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Starter & Consolation -->
            <div class="grid grid-cols-2 gap-4">
                <div class="text-center">
                    <div class="prize-label">🎯 Starter</div>
                    <div class="prize-digits">
                        <?php if ($market_result && !empty($market_result['starter_prize'])): ?>
                            <?php foreach (str_split($market_result['starter_prize']) as $digit): ?>
                                <div class="prize-digit small <?= $is_calculation_period ? 'calculating' : '' ?>">
                                    <?= htmlspecialchars($digit) ?>
                                </div>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <span style="color: rgba(255,255,255,0.3); font-size: 0.9rem;">-- -- -- --</span>
                        <?php endif; ?>
                    </div>
                </div>
                <div class="text-center">
                    <div class="prize-label">💫 Consolation</div>
                    <div class="prize-digits">
                        <?php if ($market_result && !empty($market_result['consolation_prize'])): ?>
                            <?php foreach (str_split($market_result['consolation_prize']) as $digit): ?>
                                <div class="prize-digit small <?= $is_calculation_period ? 'calculating' : '' ?>">
                                    <?= htmlspecialchars($digit) ?>
                                </div>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <span style="color: rgba(255,255,255,0.3); font-size: 0.9rem;">-- -- -- --</span>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>


    <script>
        function startCountdowns() {
            document.querySelectorAll('.countdown-display').forEach(function(el) {
                var timeLeft = parseInt(el.getAttribute('data-seconds'));
                if (isNaN(timeLeft) || timeLeft <= 0) return;
                
                var timer = setInterval(function() {
                    if (timeLeft <= 0) {
                        clearInterval(timer);
                        el.innerHTML = '<span style="color: #ffc107; font-size: 0.8rem;">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');
                    timeLeft--;
                }, 1000);
            });
        }

        function startCalculationAnimation() {
            var balls = document.querySelectorAll('.prize-digit.calculating');
            
            if (balls.length > 0) {
                setInterval(function() {
                    balls.forEach(function(ball) {
                        ball.textContent = Math.floor(Math.random() * 10);
                    });
                }, 300);
            }
        }
        
        document.addEventListener('DOMContentLoaded', function() {
            startCountdowns();
            startCalculationAnimation();
        });
    </script>
</body>
</html>