<?php
// indexp.php (Fixed: Tombol Lihat Hasil Berfungsi Langsung)
session_start();
require '../config/database.php';

// =========================================================================
// == 1. INISIALISASI & PENGAMBILAN DATA
// =========================================================================
$pengaturan = [];
$tahun_aktif_data = null;
$kandidat_list_original = [];
$total_suara_masuk_pemilih = 0; 
$total_suara_graph = 0;         
$putaran_aktif_nama = 'Pemilihan';
$show_real_results = false;     
$show_interim_results = false;  
$waktu_pengumuman_str = null;
$countdown_target_announcement = null;
$is_putaran_2 = false;
$enable_auto_refresh = true; 

// [LOGIKA BARU] Cek apakah tombol diklik
$force_show_results = isset($_GET['mode']) && $_GET['mode'] === 'hasil';

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

try {
    // 1. Ambil Pengaturan
    $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,
        ];
    }

    // 2. 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'];
        
        // --- FILTER KANDIDAT ---
        $sql_kandidat = "SELECT * FROM kandidat WHERE id_tahun_fk = ?";
        if ($tahun_aktif_data['putaran2_status'] == 'aktif') {
            $sql_kandidat .= " AND lolos_putaran_2 = 'ya'"; // Filter Putaran 2
            $is_putaran_2 = true;
        }
        $sql_kandidat .= " ORDER BY no_urut ASC";
        
        $stmt_kandidat = $pdo->prepare($sql_kandidat);
        $stmt_kandidat->execute([$id_tahun_aktif]);
        $kandidat_list_original = $stmt_kandidat->fetchAll(PDO::FETCH_ASSOC);
        
        // Hitung total suara graph
        foreach ($kandidat_list_original as $k) {
            $total_suara_graph += $k['total_suara'];
        }

        // Hitung Suara Masuk (Absensi)
        $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_pemilih = $stmt_suara_masuk->fetchColumn();

        // 3. Logika Waktu
        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'];
            }
        }

        // Setup Countdown
        $waktu_pengumuman_obj = null;
        $waktu_pengumuman_obj_plus_buffer = null;
        if ($tanggal_cek && $jam_pengumuman_cek) {
             try {
                $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');
                $countdown_target_announcement = $waktu_pengumuman_obj->format('Y-m-d\TH:i:s');
                $waktu_pengumuman_obj_plus_buffer = (clone $waktu_pengumuman_obj)->add(new DateInterval('PT1M')); // Buffer 1 menit
             } catch (Exception $e) { $waktu_pengumuman_obj = null; }
        }

        // Tentukan STATUS PEMILU
        $election_state = 'IDLE';
        
        // [FIX LOGIKA] Jika tombol sudah diklik ($force_show_results), langsung set ke FINISHED
        if ($force_show_results) {
            $election_state = 'AFTER_FINISHED';
        } 
        elseif ($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 {
                if ($waktu_pengumuman_obj && $now < $waktu_pengumuman_obj) {
                    $election_state = 'AFTER_PENDING';
                } elseif ($waktu_pengumuman_obj_plus_buffer && $now < $waktu_pengumuman_obj_plus_buffer) {
                    $election_state = 'AFTER_ANNOUNCEMENT_BUFFER';
                } else {
                    $election_state = 'AFTER_FINISHED';
                }
            }
        } else {
            $election_state = 'AFTER_FINISHED';
        }

        // Tentukan LOGIKA TAMPILAN DATA & REFRESH
        if ($election_state == 'DURING') {
            $show_interim_results = true; 
            $show_real_results = false; 
        } elseif ($election_state == 'AFTER_FINISHED') {
            $show_real_results = true;
            // Matikan refresh jika sudah hasil resmi
            $enable_auto_refresh = false; 
        }
        
        $kandidat_list_tampil = $kandidat_list_original;
        
        if ($election_state == 'DURING') {
            shuffle($kandidat_list_tampil); 
        }
    }
} catch (PDOException $e) {
    die("Koneksi gagal: " . $e->getMessage());
}

function tgl_indo($tgl) {
    $bulan = [1 => 'Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'];
    $pecah = explode('-', $tgl);
    if (count($pecah) < 3) return $tgl;
    return $pecah[2] . ' ' . $bulan[(int)$pecah[1]] . ' ' . $pecah[0];
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <?php if ($enable_auto_refresh): ?>
        <meta http-equiv="refresh" content="180">
    <?php endif; ?>

    <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; --terong: #6B1B9A; --terong-light: #9C27B0; }
        body { background-color: var(--bg-light); font-family: sans-serif; scroll-behavior: smooth; }
        .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 { background: linear-gradient(135deg, var(--bg-light) 0%, var(--dark) 100%); padding: 1rem; color: secondary; text-align: center; border-radius: 0 0 1.5rem 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; }
        
        .countdown-section { text-align: center; padding: 2.5rem 1.5rem; background: linear-gradient(135deg, var(--primary) 0%, var(--dark) 100%); border-radius: 1rem; color: white; box-shadow: 0 10px 30px rgba(74, 139, 223, 0.3); margin-bottom: 2.5rem; }
        .timer-box { background: rgba(255,255,255,0.15); padding: 1rem; border-radius: 0.5rem; min-width: 70px; }
        .timer-box span { display: block; font-size: 2.2rem; font-weight: 700; }
        #announcement-countdown-timer { display: flex; justify-content: center; gap: 0.9rem; margin-top: 1.5rem; }
        .link-hasil {color: yellowgreen; text-decoration: none; } .link-hasil:hover { color: #ccff66; }

        .chart-vertical-container { 
            display: flex; 
            justify-content: space-around; 
            align-items: flex-start; /* Fixed Alignment */
            gap: 1rem; 
            padding: 2rem 1rem; 
            min-height: 350px; 
        }
        
        .chart-vertical-item { flex: 1; display: flex; flex-direction: column; align-items: center; max-width: 120px; }
        
        .chart-vertical-bar-container { 
            width: 100%; 
            height: 250px; 
            display: flex; 
            flex-direction: column; 
            justify-content: flex-end; 
        }
        
        .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; 
            transition: height 30s ease-in-out; 
        }
        
        .chart-vertical-bar.winner { background: linear-gradient(to top, var(--terong), var(--terong-light)); }
        .chart-vertical-bar.will-animate { height: 30px !important; }
        
        .chart-vertical-percent { position: absolute; top: -35px; left: 50%; transform: translateX(-50%); font-weight: 700; color: var(--dark); background: white; padding: 0.2rem 0.6rem; border-radius: 4px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
        
        .chart-vertical-suara { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); font-weight: 700; color: white; white-space: nowrap; }
        
        .chart-vertical-label { 
            margin-top: 1rem; 
            text-align: center; 
            color: var(--dark); 
            font-size: 0.9rem; 
            width: 100%;
            display: flex;
            flex-direction: column;
            justify-content: flex-start;
        }
        
        .chart-vertical-label .no-urut { display: block; font-size: 1.5rem; color: var(--primary); font-weight: 700; }
        .chart-vertical-item.winner-item .chart-vertical-label .no-urut.winner-label { color: var(--terong-light); font-size: 1.8rem; }

        #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; }
        @media (max-width: 768px) { .logo-header img { height: 60px; width: 60px; } .chart-vertical-container { min-height: 300px; } .chart-vertical-bar-container { height: 250px; } }
    </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>-->
        <?php if ($waktu_pengumuman_str): ?>
            <p class="lead mb-0">Pengumuman Hasil <?= htmlspecialchars($putaran_aktif_nama) ?>: <strong><?= $waktu_pengumuman_str ?> WIB.</strong></p> 
        <?php endif; ?>
        
        
    </header>

    <div class="container my-5">
        
        <?php if ($election_state == 'AFTER_PENDING'): ?>
            <div class="content-card">
                <section class="election-info-section text-center">
                    <h1 class="mb-2"><?= htmlspecialchars($putaran_aktif_nama) ?> </h1>
                    <h5><?= tgl_indo($tanggal_cek) ?> </h5>
                </section>
                <section class="countdown-section">
                    <h3> 
                    <?php if($is_putaran_2): ?><a href="hasil_putaran_1.php" target="_blank" class="link-hasil">Hasil P1</a> | <?php endif; ?>
                    Hitung Mundur Pengumuman:</h3>
                    <div id="announcement-countdown-timer" data-target-date="<?= htmlspecialchars($countdown_target_announcement) ?>">
                        <div class="timer-box"><span id="ann_days">00</span> <span class="label">Hari</span></div>
                        <div class="timer-box"><span id="ann_hours">00</span> <span class="label">Jam</span></div>
                        <div class="timer-box"><span id="ann_minutes">00</span> <span class="label">Menit</span></div>
                        <div class="timer-box"><span id="ann_seconds">00</span> <span class="label">Detik</span></div>
                    </div>
                </section>
            </div>
        
        <?php elseif ($election_state == 'AFTER_ANNOUNCEMENT_BUFFER'): ?>
            <div class="content-card text-center p-5">
                <section class="welcome-section">
                    <h1 class="mb-2"><?= htmlspecialchars($putaran_aktif_nama) ?> </h1>
                    <h5><?= tgl_indo($tanggal_cek) ?> </h5>
                </section>
                <section class="election-info-section text-center mt-4">
                    <h3 class="text-success fw-bold">Waktu Pengumuman Telah Tiba!</h3>
                    <a href="index.php?mode=hasil" class="btn btn-lg btn-danger mt-3 px-5 py-3">
                        <i class="bi bi-trophy-fill me-2"></i> LIHAT HASIL AKHIR
                    </a>
                </section>
            </div>

        <?php else: ?>
            <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 && !$show_real_results): ?>
                            Hasil Sementara <small class="text-muted">(Diperbarui berkala)</small>
                        <?php else: ?>
                            Perolehan Suara Akhir
                        <?php endif; ?>
                        <?php if ($enable_auto_refresh): ?>
                            <p class="lead mb-0 mt-3" id="refresh-countdown-text" style="opacity: 0.7; font-size: 1rem;">
                                <b>Merefresh data dalam 20 detik...</b>
                            </p>
                        <?php endif; ?>
                    </h5>
                </div>

                <?php if ($show_interim_results && !$show_real_results): ?>
                    <!--<div class="alert alert-warning border-warning" style="background-color: #fff3cd; color: #856404;">
                        <i class="bi bi-info-circle-fill me-2"></i> 
                        <b>Ini adalah Hasil Sementara.</b> Identitas kandidat disembunyikan dan urutan diacak selama proses pemilihan berlangsung.
                    </div>-->
                <?php elseif ($show_real_results): ?>
                    <!--<div class="alert alert-success">
                        <i class="bi bi-trophy-fill"></i> <b>Hasil Resmi</b>
                    </div>-->
                <?php endif; ?>

                <?php if ($total_suara_graph == 0): ?>
                    <div class="alert alert-info text-center">Belum ada suara yang masuk.</div>
                <?php else: ?>
                    
                    <?php
                    $kandidat_sorted = $kandidat_list_tampil;
                    if ($show_real_results) {
                        usort($kandidat_sorted, function($a, $b) { return $a['no_urut'] - $b['no_urut']; });
                        
                        $pemenang_ids = [];
                        $jumlah_pemenang = ($is_putaran_2 || !empty($tahun_aktif_data['putaran2_tanggal'])) ? 1 : 3;
                        $kandidat_by_suara = $kandidat_sorted;
                        usort($kandidat_by_suara, function($a, $b) { return $b['total_suara'] - $a['total_suara']; });
                        for ($i = 0; $i < min($jumlah_pemenang, count($kandidat_by_suara)); $i++) {
                            $pemenang_ids[] = $kandidat_by_suara[$i]['no_urut'];
                        }
                    }
                    ?>
                    
                    <div class="chart-vertical-container">
                        <?php foreach ($kandidat_sorted as $k): 
                            $persen_kandidat = 0;
                            if ($total_suara_graph > 0) {
                                $persen_kandidat = round(($k['total_suara'] / $total_suara_graph) * 100, 1);
                            }
                            
                            $is_winner = false;
                            if ($show_real_results && in_array($k['no_urut'], $pemenang_ids)) {
                                $is_winner = true;
                            }
                            
                            $tinggi_bar = max($persen_kandidat * 3.2, 30);
                            
                            $animate_status = $show_real_results ? 'true' : 'false';
                            $initial_height = $show_real_results ? '30px' : $tinggi_bar . 'px';
                            $css_class_animate = $show_real_results ? 'will-animate' : '';
                            $initial_percent_text = $show_real_results ? '0%' : $persen_kandidat . '%';
                        ?>
                            <div class="chart-vertical-item <?= $is_winner ? 'winner-item' : '' ?>">
                                <div class="chart-vertical-bar-container">
                                    
                                    <div class="chart-vertical-bar <?= $css_class_animate ?>" 
                                         style="height: <?= $initial_height ?>;"
                                         data-final-height="<?= $tinggi_bar ?>"
                                         data-animate="<?= $animate_status ?>" 
                                         data-is-winner="<?= $is_winner ? 'true' : 'false' ?>"
                                         data-final-percent="<?= $persen_kandidat ?>"
                                         data-final-votes="<?= htmlspecialchars($k['total_suara']) ?>">
                                        
                                        <div class="chart-vertical-percent" data-current-percent="0"><?= $initial_percent_text ?></div>
                                        
                                        <?php if ($show_real_results): ?>
                                            <div class="chart-vertical-suara">0 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 fs-2 text-muted">***</span>
                                        <small class="text-muted">Kandidat</small>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    <hr>
                    <div class="text-center text-muted">Total Suara Masuk: <strong><?= $total_suara_masuk_pemilih ?></strong></div>
                <?php endif; ?>
            </div>
        <?php endif; ?>
    </div>

    <script>
    document.addEventListener("DOMContentLoaded", function() {
        const countdownOverlay = document.getElementById('countdown-overlay');
        const mainResults = document.getElementById('main-results');
        
        function animateNumbers() {
            const verticalBars = document.querySelectorAll('.chart-vertical-bar[data-animate="true"]');
            verticalBars.forEach((bar) => {
                const percentElement = bar.querySelector('.chart-vertical-percent');
                const voteElement = bar.querySelector('.chart-vertical-suara');
                const finalPercent = parseFloat(bar.getAttribute('data-final-percent'));
                const finalVotes = parseInt(bar.getAttribute('data-final-votes'));
                const duration = 30000; const startTime = Date.now();
                
                function updateValues() {
                    const elapsed = Date.now() - startTime;
                    const progress = Math.min(elapsed / duration, 1);
                    const currentPercent = (progress * finalPercent).toFixed(1);
                    const currentVotes = Math.floor(progress * finalVotes);
                    
                    percentElement.textContent = currentPercent + '%';
                    if(voteElement) voteElement.textContent = currentVotes + ' suara';
                    
                    if (progress < 1) requestAnimationFrame(updateValues);
                    else {
                        percentElement.textContent = finalPercent.toFixed(1) + '%';
                        if(voteElement) voteElement.textContent = finalVotes + ' suara';
                    }
                }
                updateValues();
            });
        }
        
        function animateVerticalBars() {
            const verticalBars = document.querySelectorAll('.chart-vertical-bar[data-animate="true"]');
            if (verticalBars.length === 0) return;
            
            setTimeout(() => {
                verticalBars.forEach((bar) => {
                    const finalHeight = bar.getAttribute('data-final-height');
                    bar.classList.remove('will-animate');
                    bar.style.height = finalHeight + 'px';
                });
                animateNumbers();
                setTimeout(() => {
                    verticalBars.forEach((bar) => {
                        const isWinner = bar.getAttribute('data-is-winner') === 'true';
                        if (isWinner) {
                            bar.classList.add('winner');
                            bar.querySelector('.chart-vertical-percent').classList.add('winner-percent');
                            bar.closest('.chart-vertical-item').querySelector('.no-urut').classList.add('winner-label');
                        }
                    });
                }, 30000); 
            }, 200);
        }
        
        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';
                        animateVerticalBars();
                    }, 500); 
                }
            }, 1000);
        } else {
            if(document.querySelectorAll('.chart-vertical-bar[data-animate="true"]').length > 0) {
                animateVerticalBars();
            }
        }

        const announcementTimer = document.getElementById('announcement-countdown-timer');
        if (announcementTimer) {
            const targetDate = new Date(announcementTimer.getAttribute('data-target-date')).getTime();
            const interval = setInterval(() => {
                const now = new Date().getTime(); const distance = targetDate - now;
                if (distance < 0) { clearInterval(interval); window.location.reload(); return; }
                document.getElementById('ann_days').innerText = Math.floor(distance / (1000 * 60 * 60 * 24)).toString().padStart(2, '0');
                document.getElementById('ann_hours').innerText = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)).toString().padStart(2, '0');
                document.getElementById('ann_minutes').innerText = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)).toString().padStart(2, '0');
                document.getElementById('ann_seconds').innerText = Math.floor((distance % (1000 * 60)) / 1000).toString().padStart(2, '0');
            }, 1000);
        }

        let refreshTime = 20; 
        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>