<?php
// p_hasil_akhir.php (Papan Skor dengan Bar Vertikal + Animasi Pemenang)
session_start();
require '../config/database.php';

// =========================================================================
// == 1. INISIALISASI & PENGAMBILAN DATA
// =========================================================================
$pengaturan = [];
$tahun_aktif_data = null;
$kandidat_list_original = [];
$total_suara_masuk = 0;
$putaran_aktif_nama = 'Pemilihan';
$show_real_results = false;
$show_interim_results = false;
$waktu_pengumuman_str = null;

$logos = ['logo1' => null, 'logo2' => null, 'logo3' => null];

try {
    $stmt_pengaturan = $pdo->query("SELECT * FROM pengaturan_aplikasi WHERE id = 1");
    $pengaturan = $stmt_pengaturan->fetch(PDO::FETCH_ASSOC);

    if ($pengaturan) {
        $logos = [
            'logo1' => $pengaturan['logo_sekolah'] ? '../assets/img/logo/' . htmlspecialchars($pengaturan['logo_sekolah']) : null,
            'logo2' => $pengaturan['logo_osim'] ? '../assets/img/logo/' . htmlspecialchars($pengaturan['logo_osim']) : null,
            'logo3' => $pengaturan['logo_kegiatan'] ? '../assets/img/logo/' . htmlspecialchars($pengaturan['logo_kegiatan']) : null,
        ];
    }

    $stmt_tahun = $pdo->prepare("SELECT * FROM tahun_pemilihan WHERE status = 'aktif' LIMIT 1");
    $stmt_tahun->execute();
    $tahun_aktif_data = $stmt_tahun->fetch(PDO::FETCH_ASSOC);

    if ($tahun_aktif_data) {
        $id_tahun_aktif = $tahun_aktif_data['id_tahun'];
        
        $stmt_kandidat = $pdo->prepare("SELECT * FROM kandidat WHERE id_tahun_fk = ? ORDER BY no_urut ASC");
        $stmt_kandidat->execute([$id_tahun_aktif]);
        $kandidat_list_original = $stmt_kandidat->fetchAll(PDO::FETCH_ASSOC);
        
        $stmt_suara_masuk = $pdo->prepare("SELECT COUNT(id_pemilih) FROM pemilih WHERE status_memilih = 'sudah' AND id_tahun_fk = ?");
        $stmt_suara_masuk->execute([$id_tahun_aktif]);
        $total_suara_masuk = $stmt_suara_masuk->fetchColumn();

        date_default_timezone_set('Asia/Jakarta');
        $now = new DateTime();
        $tanggal_cek = null;
        $jam_pengumuman_cek = null;
        $mulai = null;
        $selesai = null;

        if ($tahun_aktif_data['putaran2_status'] == 'aktif') {
            $tgl = $tahun_aktif_data['putaran2_tanggal'];
            $mulai = $tahun_aktif_data['putaran2_jam_mulai'];
            $selesai = $tahun_aktif_data['putaran2_jam_selesai'];
            $jam_pengumuman_cek = $tahun_aktif_data['putaran2_jam_pengumuman'] ?? null;
            $tanggal_cek = $tgl;
            $putaran_aktif_nama = $tahun_aktif_data['putaran2_nama'];
        }
        elseif ($tahun_aktif_data['putaran1_status'] == 'aktif') {
            $tgl = $tahun_aktif_data['putaran1_tanggal'];
            $mulai = $tahun_aktif_data['putaran1_jam_mulai'];
            $selesai = $tahun_aktif_data['putaran1_jam_selesai'];
            $jam_pengumuman_cek = $tahun_aktif_data['putaran1_jam_pengumuman'] ?? null;
            $tanggal_cek = $tgl;
            $putaran_aktif_nama = $tahun_aktif_data['putaran1_nama'];
        } else {
            $tgl = $tahun_aktif_data['putaran2_tanggal'];
            $jam_pengumuman_cek = $tahun_aktif_data['putaran2_jam_pengumuman'] ?? null;
            $tanggal_cek = $tgl;
            $putaran_aktif_nama = $tahun_aktif_data['putaran2_nama'];
            if(empty($tgl)) {
                 $tgl = $tahun_aktif_data['putaran1_tanggal'];
                 $jam_pengumuman_cek = $tahun_aktif_data['putaran1_jam_pengumuman'] ?? null;
                 $tanggal_cek = $tgl;
                 $putaran_aktif_nama = $tahun_aktif_data['putaran1_nama'];
            }
        }

        if ($tanggal_cek && $jam_pengumuman_cek) {
             $waktu_pengumuman_obj = new DateTime("$tanggal_cek $jam_pengumuman_cek");
             $waktu_pengumuman_str = $waktu_pengumuman_obj->format('d M Y \p\u\k\u\l H:i');
        } else {
            $waktu_pengumuman_obj = null;
        }

        $election_state = 'IDLE';
        if ($tgl && $mulai && $selesai) {
            $start_time = new DateTime("$tgl $mulai");
            $end_time = new DateTime("$tgl $selesai");
            if ($now < $start_time) $election_state = 'BEFORE';
            elseif ($now >= $start_time && $now <= $end_time) $election_state = 'DURING';
            else $election_state = 'AFTER';
        }

        if ($election_state == 'DURING') {
            $show_interim_results = true;
        } elseif ($election_state == 'AFTER') {
            if ($waktu_pengumuman_obj && $now < $waktu_pengumuman_obj) {
                $show_interim_results = true;
            } else {
                $show_real_results = true;
            }
        }
        
        $kandidat_list_tampil = $kandidat_list_original;
        if ($show_interim_results) {
            shuffle($kandidat_list_tampil);
        }
        
    }
} catch (PDOException $e) {
    die("Koneksi database gagal: " . $e->getMessage());
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="refresh" content="180"> 
    <title>Hasil Pemilihan - PILKASIM</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <style>
        :root {
            --primary: #4A8BDF; 
            --dark: #2c5b9c; 
            --accent: #A0006D;
            --bg-light: #EFFAFD;
        }
        body {
            background-color: var(--bg-light);
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            scroll-behavior: smooth;
        }
        
        /* LOGO HEADER */
        .logo-header { 
            display: flex; 
            justify-content: center; 
            align-items: center; 
            gap: 2rem; 
            padding: 2rem 0; 
        }
        .logo-header img {
            height: 80px; 
            width: 80px; 
            object-fit: contain;
            filter: drop-shadow(0 4px 6px rgba(0,0,0,0.1));
        }
        
        /* HEADER HASIL */
        .header-hasil {
            background: linear-gradient(135deg, var(--primary) 0%, var(--dark) 100%);
            padding: 1.5rem 1.5rem;
            color: white;
            text-align: center;
            border-bottom-left-radius: 1.5rem;
            border-bottom-right-radius: 1.5rem;
        }
        .header-hasil h1 { 
            font-weight: 700; 
        }
        
        /* CONTENT CARD */
        .content-card {
            background: white;
            border-radius: 1rem;
            padding: 1.5rem;
            box-shadow: 0 4px 25px rgba(0,0,0,0.05);
            margin-top: -2rem; 
            position: relative;
        }
        
        /* ===================================================================
           VERTICAL BAR (KOLOM) - UNTUK SEMUA FASE
        =================================================================== */
        .chart-vertical-container {
            display: flex;
            justify-content: space-around;
            align-items: flex-end;
            gap: 1rem;
            padding: 2rem 1rem;
            min-height: 450px;
            position: relative;
        }
        
        .chart-vertical-item {
            flex: 1;
            display: flex;
            flex-direction: column;
            align-items: center;
            max-width: 120px;
            position: relative;
        }
        
        .chart-vertical-bar-container {
            width: 100%;
            height: 350px;
            display: flex;
            flex-direction: column;
            justify-content: flex-end;
            position: relative;
            overflow: visible;
        }
        
        .chart-vertical-bar {
            width: 100%;
            background: linear-gradient(to top, var(--primary), var(--dark));
            border-radius: 8px 8px 0 0;
            position: relative;
            box-shadow: 0 -4px 15px rgba(74, 139, 223, 0.3);
            min-height: 30px;
        }
        
        /* Warna EMAS untuk pemenang - TANPA ANIMASI */
        .chart-vertical-bar.winner {
            background: linear-gradient(to top, #FFD700, #FFA500);
            box-shadow: 0 -4px 20px rgba(255, 215, 0, 0.5);
        }
        
        .chart-vertical-percent {
            position: absolute;
            top: -35px;
            left: 50%;
            transform: translateX(-50%);
            font-size: 1.3rem;
            font-weight: 700;
            color: var(--dark);
            white-space: nowrap;
            background: white;
            padding: 0.2rem 0.6rem;
            border-radius: 6px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        
        /* Warna emas untuk persen pemenang */
        .chart-vertical-item.winner-item .chart-vertical-percent {
            background: linear-gradient(135deg, #FFD700, #FFA500);
            color: white;
            font-size: 1.5rem;
            font-weight: 800;
        }
        
        .chart-vertical-suara {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            font-size: 1.1rem;
            font-weight: 700;
            color: white;
            text-shadow: 0 2px 4px rgba(0,0,0,0.3);
            white-space: nowrap;
        }
        
        .chart-vertical-label {
            margin-top: 1rem;
            text-align: center;
            font-weight: 600;
            color: var(--dark);
            font-size: 0.9rem;
            line-height: 1.3;
        }
        
        .chart-vertical-label .no-urut {
            display: block;
            font-size: 1.5rem;
            color: var(--primary);
            margin-bottom: 0.3rem;
            font-weight: 700;
        }
        
        /* Pemenang punya nomor urut emas */
        .chart-vertical-item.winner-item .chart-vertical-label .no-urut {
            color: #FFA500;
            font-size: 1.8rem;
            font-weight: 900;
        }
        
        .chart-vertical-label .nama-kandidat {
            display: block;
            font-size: 0.85rem;
            line-height: 1.2;
            margin-top: 0.3rem;
        }

        
        /* ===================================================================
           COUNTDOWN OVERLAY
        =================================================================== */
        #countdown-overlay {
            position: fixed;
            top: 0; left: 0; right: 0; bottom: 0;
            background: rgba(0,0,0,0.9);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-direction: column;
            z-index: 1060;
            opacity: 0;
            transition: opacity 0.5s ease;
        }
        #countdown-overlay.visible {
            opacity: 1;
        }
        #countdown-number {
            font-size: 15rem;
            font-weight: 900;
        }
        #countdown-text {
            font-size: 2rem;
            font-weight: 300;
        }
        
        /* ===================================================================
           RESPONSIVE
        =================================================================== */
        @media (max-width: 768px) {
            .logo-header { 
                padding-top: 1rem; 
                padding-bottom: 1rem; 
                gap: 1rem;
            }
            .logo-header img { 
                height: 60px; 
                width: 60px; 
            }
            .chart-vertical-container {
                gap: 0.5rem;
                padding: 1rem 0.5rem;
                min-height: 300px;
            }
            .chart-vertical-item {
                max-width: 80px;
            }
            .chart-vertical-bar-container {
                height: 250px;
            }
            .chart-vertical-label {
                font-size: 0.7rem;
            }
            .chart-vertical-label .no-urut {
                font-size: 1.2rem;
            }
            .chart-vertical-label .nama-kandidat {
                font-size: 0.65rem;
            }
            .chart-vertical-percent {
                font-size: 0.9rem;
                top: -25px;
            }
            .chart-vertical-suara {
                font-size: 0.8rem;
            }
            .winner-icon {
                font-size: 1.5rem;
                top: -40px;
            }
    </style>
</head>
<body>

    <?php if ($show_real_results && $waktu_pengumuman_obj): ?>
    <div id="countdown-overlay">
        <div id="countdown-text">Hasil Akan Tampil Dalam...</div>
        <div id="countdown-number">5</div>
    </div>
    <?php endif; ?>

    <header class="logo-header container">
        <?php if($logos['logo1']): ?><img src="<?= $logos['logo1'] ?>" alt="Logo 1"><?php endif; ?>
        <?php if($logos['logo2']): ?><img src="<?= $logos['logo2'] ?>" alt="Logo 2"><?php endif; ?>
        <?php if($logos['logo3']): ?><img src="<?= $logos['logo3'] ?>" alt="Logo 3"><?php endif; ?>
    </header>

    <header class="header-hasil">
        <h1>Hasil <?= htmlspecialchars($putaran_aktif_nama) ?></h1>
        <p class="lead mb-0">Pengumuman Hasil akhir : <strong><?= $waktu_pengumuman_str ?> WIB.</strong></p> 
        <p class="lead mb-0 mt-3" id="refresh-countdown-text" style="opacity: 0.7; font-size: 1rem;">
            <b>Merefresh data dalam 180 detik...</b>
        </p>
    </header>

    <div class="container my-5">
        <div class="content-card" id="main-results" 
             style="<?= ($show_real_results && $waktu_pengumuman_obj) ? 'visibility: hidden;' : '' ?>">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h5>
                    <?php if ($show_interim_results): ?>
                        Hasil Sementara
                    <?php else: ?>
                        Perolehan Suara
                    <?php endif; ?>
                </h5>
            </div>

            <?php if ($show_interim_results): ?>
                <div class="alert alert-warning">
                    <i class="bi bi-clock-fill"></i> 
                    <b>Ini adalah Hasil Sementara.</b>
                    <?php if ($waktu_pengumuman_str): ?>
                        Hasil resmi akan diumumkan pada <strong><?= $waktu_pengumuman_str ?> WIB</strong>.
                    <?php else: ?>
                        Data diperbarui secara berkala.
                    <?php endif; ?>
                </div>
            <?php else: ?>
                <div class="alert alert-success">
                    <i class="bi bi-trophy-fill"></i> 
                    <b>Hasil Resmi - <?= htmlspecialchars($putaran_aktif_nama) ?></b>
                    <?php if ($tahun_aktif_data): ?>
                        <?php if ($tahun_aktif_data['putaran1_status'] == 'aktif'): ?>
                            <br><small>Top 3 kandidat terbaik akan lolos ke putaran berikutnya</small>
                        <?php elseif ($tahun_aktif_data['putaran2_status'] == 'aktif'): ?>
                            <br><small>Pemenang dengan suara terbanyak</small>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
            <?php endif; ?>

            <?php if (empty($kandidat_list_tampil)): ?>
                <div class="alert alert-warning text-center">Belum ada kandidat.</div>
            <?php elseif ($total_suara_masuk == 0): ?>
                <div class="alert alert-info text-center">Belum ada suara yang masuk.</div>
            <?php else: ?>
                
                <?php
                // Urutkan kandidat berdasarkan suara untuk menentukan pemenang
                $kandidat_sorted = $kandidat_list_tampil;
                if ($show_real_results) {
                    // Urutkan dari tertinggi ke terendah
                    usort($kandidat_sorted, function($a, $b) {
                        return $b['total_suara'] - $a['total_suara'];
                    });
                }
                
                // ===================================================================
                // LOGIKA PENENTU JUMLAH PEMENANG BERDASARKAN PUTARAN
                // ===================================================================
                $jumlah_pemenang = 1; // Default
                
                if ($tahun_aktif_data) {
                    // CEK 1: Apakah sedang putaran 2 aktif?
                    if ($tahun_aktif_data['putaran2_status'] == 'aktif') {
                        $jumlah_pemenang = 1; // Putaran 2 aktif = 1 pemenang
                    }
                    // CEK 2: Apakah sedang putaran 1 aktif?
                    elseif ($tahun_aktif_data['putaran1_status'] == 'aktif') {
                        $jumlah_pemenang = 3; // Putaran 1 aktif = 3 pemenang
                    }
                    // CEK 3: Kalau sudah selesai, cek putaran mana yang terakhir
                    else {
                        // Jika putaran 2 pernah dilaksanakan (ada tanggal P2)
                        if (!empty($tahun_aktif_data['putaran2_tanggal'])) {
                            $jumlah_pemenang = 1; // Hasil final P2 = 1 pemenang
                        }
                        // Jika hanya putaran 1 saja (tidak ada P2)
                        else {
                            $jumlah_pemenang = 3; // Hasil final P1 = 3 pemenang
                        }
                    }
                }
                ?>
                
                <!-- VERTICAL BAR (KOLOM) - UNTUK SEMUA FASE -->
                <div class="chart-vertical-container">
                    <?php 
                    $rank = 0;
                    foreach ($kandidat_sorted as $k): 
                        $persen_kandidat = 0;
                        if ($total_suara_masuk > 0) {
                            $persen_kandidat = round(($k['total_suara'] / $total_suara_masuk) * 100, 1);
                        }
                        
                        // Tentukan apakah kandidat ini pemenang
                        $is_winner = false;
                        if ($show_real_results) {
                            $rank++;
                            if ($rank <= $jumlah_pemenang) {
                                $is_winner = true;
                            }
                        }
                        
                        // Hitung tinggi bar berdasarkan persentase
                        $tinggi_bar = max($persen_kandidat * 3.2, 30);
                    ?>
                        <div class="chart-vertical-item <?= $is_winner ? 'winner-item' : '' ?>">
                            <div class="chart-vertical-bar-container">
                                <div class="chart-vertical-bar <?= $is_winner ? 'winner' : '' ?>" 
                                     style="height: <?= $tinggi_bar ?>px;">
                                    <div class="chart-vertical-percent"><?= $persen_kandidat ?>%</div>
                                    <?php if ($show_real_results): ?>
                                        <div class="chart-vertical-suara"><?= htmlspecialchars($k['total_suara']) ?> suara</div>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <div class="chart-vertical-label">
                                <?php if ($show_real_results): ?>
                                    <span class="no-urut">No. <?= htmlspecialchars($k['no_urut']) ?></span>
                                    <span class="nama-kandidat">
                                        <?= htmlspecialchars($k['nama_ketua']) ?><br>
                                        <?= htmlspecialchars($k['nama_wakil']) ?>
                                    </span>
                                <?php else: ?>
                                    <span class="no-urut">***</span>
                                    <small>Kandidat</small>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
                
                <hr>
                <div class="text-center text-muted">
                    Total Suara Masuk: <strong><?= $total_suara_masuk ?></strong>
                </div>
                
            <?php endif; ?>
            
        </div>
    </div>

    <script>
    document.addEventListener("DOMContentLoaded", function() {
        const countdownOverlay = document.getElementById('countdown-overlay');
        const mainResults = document.getElementById('main-results');
        
        // =====================================================================
        // === COUNTDOWN OVERLAY (UNTUK PENGUMUMAN RESMI)
        // =====================================================================
        if (countdownOverlay && mainResults) {
            let count = 5;
            const countdownNumber = document.getElementById('countdown-number');
            countdownOverlay.classList.add('visible');
            
            const interval = setInterval(() => {
                count--;
                countdownNumber.textContent = count;
                if (count <= 0) {
                    clearInterval(interval);
                    countdownOverlay.style.opacity = '0';
                    mainResults.style.visibility = 'visible';
                    
                    setTimeout(() => {
                        countdownOverlay.style.display = 'none';
                    }, 500); 
                }
            }, 1000);
        }

        // =====================================================================
        // === REFRESH COUNTDOWN
        // =====================================================================
        let refreshTime = 180; 
        const countdownText = document.getElementById('refresh-countdown-text');

        if (countdownText) {
            const refreshInterval = setInterval(() => {
                refreshTime--;
                
                if (refreshTime <= 0) {
                    clearInterval(refreshInterval);
                    countdownText.textContent = "Sedang merefresh data...";
                    window.location.reload();
                } else if (refreshTime <= 5) {
                    countdownText.innerHTML = `<span class="spinner-border spinner-border-sm" role="status"></span> Merefresh data...`;
                } else {
                    countdownText.textContent = `Merefresh data dalam ${refreshTime} detik...`;
                }

            }, 1000); 
        }
    });
    </script>
</body>
</html>