<?php
// p_hasil_akhir.php (Papan Skor)
session_start();
require '../config/database.php'; // Path diubah ke ../

// =========================================================================
// == 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;

// === PERUBAHAN: Tambahkan variabel logo ===
$logos = ['logo1' => null, 'logo2' => null, 'logo3' => null];

try {
    // === PERUBAHAN: Ambil semua pengaturan, bukan hanya nama sekolah ===
    $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, // Path diubah ke ../assets/img/logo/
            'logo2' => $pengaturan['logo_osim'] ? '../assets/img/logo/' . htmlspecialchars($pengaturan['logo_osim']) : null,     // Path diubah ke ../assets/img/logo/
            'logo3' => $pengaturan['logo_kegiatan'] ? '../assets/img/logo/' . htmlspecialchars($pengaturan['logo_kegiatan']) : null, // Path diubah ke ../assets/img/logo/
        ];
    }
    // === AKHIR PERUBAHAN ===

    // Ambil Tahun Aktif
    $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'];
        
        // Ambil Kandidat
        $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);
        
        // Ambil Total Suara Masuk
        $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();

        // =================================================================
        // === 2. LOGIKA TAMPILAN HASIL (KAPAN HARUS TAMPIL)
        // =================================================================
        date_default_timezone_set('Asia/Jakarta');
        $now = new DateTime();
        $tanggal_cek = null;
        $jam_pengumuman_cek = 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 {
            // Pemilu selesai, default ke data P2 (Final)
            $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)) { // Fallback ke P1 jika P2 tidak ada
                 $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'];
            }
        }

        // Tentukan Waktu Pengumuman
        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;
        }

        // Tentukan Status Halaman
        $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';
        }

        // Tentukan Apa yang Ditampilkan
        if ($election_state == 'DURING') {
            $show_interim_results = true; // Tampilkan hasil acak
        } elseif ($election_state == 'AFTER') {
            if ($waktu_pengumuman_obj && $now < $waktu_pengumuman_obj) {
                // Sudah selesai, tapi belum jam pengumuman
                $show_interim_results = true; // Tampilkan hasil acak
            } else {
                // Sudah selesai DAN sudah jam pengumuman (atau jam tdk diset)
                $show_real_results = true; // Tampilkan hasil asli
            }
        }
        
        // Acak data jika hasil sementara
        $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;
        }
        /* === CSS BARU UNTUK 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));
        }
        @media (max-width: 576px) { 
            .logo-header { padding-top: 1rem; padding-bottom: 1rem; gap: 1rem;}
            .logo-header img { height: 60px; width: 60px; } 
        }
        /* === AKHIR CSS BARU === */
        
        .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 {
            background: white;
            border-radius: 1rem;
            padding: 1.5rem;
            box-shadow: 0 4px 25px rgba(0,0,0,0.05);
            margin-top: -2rem; 
            position: relative;
        }
        .chart-bar-wrapper { margin-bottom: 1.5rem; }
        .chart-label {
            display: flex;
            justify-content: space-between;
            font-weight: 600;
            color: var(--dark);
            margin-bottom: 0.5rem;
        }
        .chart-label .percent { font-size: 1.2rem; color: var(--primary); }
        .progress { height: 35px; font-size: 1rem; }
        .progress-bar { font-weight: 700; }
        
        #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;
        }
    </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.</p></strong> 
        <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): ?>
                    
                    <?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): ?>
                        
                    <?php else: ?>
                        Data diperbarui secara acak.
                    <?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 foreach ($kandidat_list_tampil as $k): ?>
                    <?php
                    $persen_kandidat = 0;
                    if ($total_suara_masuk > 0) {
                        $persen_kandidat = round(($k['total_suara'] / $total_suara_masuk) * 100, 1);
                    }
                    ?>
                    <div class="chart-bar-wrapper">
                        
                        <?php if ($show_real_results): ?>
                            <div class="chart-label">
                                <span><b>No. <?= htmlspecialchars($k['no_urut']) ?>:</b> <?= htmlspecialchars($k['nama_ketua']) ?> & <?= htmlspecialchars($k['nama_wakil']) ?></span>
                                <span class="percent"><?= $persen_kandidat ?>%</span>
                            </div>
                            <div class="progress">
                                <div class="progress-bar" role="progressbar" 
                                     style="width: <?= $persen_kandidat ?>%;" 
                                     aria-valuenow="<?= $persen_kandidat ?>">
                                    <b><?= htmlspecialchars($k['total_suara']) ?> Suara</b>
                                </div>
                            </div>
                        <?php else: ?>
                            <div class="chart-label">
                                <span>Nomor Urut ***</span>
                            </div>
                            <div class="progress">
                                <div class="progress-bar" role="progressbar" 
                                     style="width: <?= $persen_kandidat ?>%;" 
                                     aria-valuenow="<?= $persen_kandidat ?>">
                                </div>
                            </div>
                        <?php endif; ?>
                        
                    </div>
                <?php endforeach; ?>
                
                <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');
        
        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);
        }

        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>