<?php
// index.php (Halaman Utama / Bilik Suara)
session_start();

// =========================================================================
// == LOGIKA LOGOUT VOTER
// =========================================================================
if (isset($_GET['action']) && $_GET['action'] === 'voter_logout') {
    unset($_SESSION['voter_id']);
    unset($_SESSION['voter_name']);
    header('Location: index.php');
    exit;
}

require 'config/database.php'; // Hubungkan ke database

// =========================================================================
// == 0. CEK LOGIN ADMIN (Agar tidak tumpang tindih)
// =========================================================================
if (isset($_SESSION['user_id']) && isset($_SESSION['role'])) {
    if ($_SESSION['role'] === 'admin') {
        header("Location: admin/dashboard.php");
        exit();
    }
}

// =========================================================================
// == 1. INISIALISASI & PENGAMBILAN DATA
// =========================================================================
$pengaturan = [];
$tahun_aktif_data = null;
$kandidat_list = [];
$ketua_panitia = ['nama' => 'Ketua Panitia', 'sambutan' => 'Selamat datang di Pemilihan...'];
$logos = ['logo1' => null, 'logo2' => null, 'logo3' => null];
$footer_info = [
    'alamat' => '', 'no_telepon' => '', 'email' => '',
    'kontak' => [ 'Instagram' => '#', 'Tiktok' => '#' ]
];
$panitia_footer = [
    'Ketua' => [],
    'Sekretaris' => [],
    'Anggota' => []
];

$error_login_voter = ''; 
$error_login_admin = ''; 
$vote_success = false;
$is_putaran_2 = false; // Flag penanda putaran

try {
    // Ambil Pengaturan Umum
    $stmt_pengaturan = $pdo->query("SELECT * FROM pengaturan_aplikasi WHERE id = 1 LIMIT 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,
        ];
        $footer_info = [
            'alamat' => htmlspecialchars($pengaturan['alamat'] ?? ''),
            'no_telepon' => htmlspecialchars($pengaturan['no_telepon'] ?? ''),
            'email' => htmlspecialchars($pengaturan['email'] ?? ''),
            'kontak' => [
                'Instagram' => htmlspecialchars($pengaturan['link_instagram'] ?? '#'),
                'Tiktok' => htmlspecialchars($pengaturan['link_tiktok'] ?? '#'),
                'Youtube' => htmlspecialchars($pengaturan['link_youtube'] ?? '#')
            ]
        ];
        if (!empty($pengaturan['sambutan_ketua'])) {
            $ketua_panitia['sambutan'] = htmlspecialchars($pengaturan['sambutan_ketua']);
        }
    }

    // Ambil Tahun Pemilihan yang 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'];
        
        // --- [LOGIKA PUTARAN 2] ---
        // Cek apakah Putaran 2 Aktif
        if ($tahun_aktif_data['putaran2_status'] == 'aktif') {
            $is_putaran_2 = true;
        }

        // Siapkan Query Kandidat
        $sql_kandidat = "SELECT * FROM kandidat WHERE id_tahun_fk = ?";
        
        // Jika Putaran 2 Aktif, tambahkan filter hanya yang lolos
        if ($is_putaran_2) {
            $sql_kandidat .= " AND lolos_putaran_2 = 'ya'";
        }
        
        $sql_kandidat .= " ORDER BY no_urut ASC";
        
        // Eksekusi Query
        $stmt_kandidat = $pdo->prepare($sql_kandidat);
        $stmt_kandidat->execute([$id_tahun_aktif]);
        $kandidat_list = $stmt_kandidat->fetchAll(PDO::FETCH_ASSOC);
        
        // Ambil data panitia untuk footer
        $stmt_panitia = $pdo->prepare("SELECT nama_panitia, jabatan_panitia FROM panitia WHERE id_tahun_fk = ? ORDER BY FIELD(jabatan_panitia, 'Ketua Panitia', 'Sekretaris', 'Anggota'), nama_panitia");
        $stmt_panitia->execute([$id_tahun_aktif]);
        $all_panitia = $stmt_panitia->fetchAll(PDO::FETCH_ASSOC);
        
        $is_ketua_set = false;
        foreach ($all_panitia as $p) {
            $jabatan = $p['jabatan_panitia'];
            $nama = htmlspecialchars($p['nama_panitia']);

            if ($jabatan == 'Ketua Panitia') {
                $panitia_footer['Ketua'][] = $nama;
                if (!$is_ketua_set) {
                    $ketua_panitia['nama'] = $nama; 
                    $is_ketua_set = true;
                }
            } elseif ($jabatan == 'Sekretaris') {
                $panitia_footer['Sekretaris'][] = $nama;
            } elseif ($jabatan == 'Anggota') {
                $panitia_footer['Anggota'][] = $nama;
            }
        }
    }

} catch (PDOException $e) {
    die("Koneksi database gagal: " . $e->getMessage());
}

// =========================================================================
// == 2. LOGIKA STATUS WAKTU PEMILIHAN
// =========================================================================
$election_state = 'IDLE'; 
$countdown_target_date = null;
$countdown_target_announcement = null;
$putaran_aktif_nama = 'Pemilihan';
$is_voting_session = isset($_SESSION['voter_id']);

if ($tahun_aktif_data) {
    date_default_timezone_set('Asia/Jakarta');
    $now = new DateTime();
    $tgl = null; $mulai = null; $selesai = null;
    $jam_pengumuman_cek = null;

    // Cek Status Putaran (Prioritas Putaran 2)
    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;
        $putaran_aktif_nama = $tahun_aktif_data['putaran2_nama'];
        $is_putaran_2 = true;
    }
    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;
        $putaran_aktif_nama = $tahun_aktif_data['putaran1_nama'];
    } else {
        // Fallback jika tidak ada yang aktif (misal selesai semua)
        // Kita asumsikan selesai di putaran terakhir yang diset
        $tgl = $tahun_aktif_data['putaran2_tanggal'];
        $jam_pengumuman_cek = $tahun_aktif_data['putaran2_jam_pengumuman'] ?? null;
        $putaran_aktif_nama = $tahun_aktif_data['putaran2_nama'];
        
        // Jika tanggal putaran 2 kosong, berarti masih putaran 1
        if(empty($tgl) || $tgl == '0000-00-00') { 
             $tgl = $tahun_aktif_data['putaran1_tanggal'];
             $jam_pengumuman_cek = $tahun_aktif_data['putaran1_jam_pengumuman'] ?? null;
             $putaran_aktif_nama = $tahun_aktif_data['putaran1_nama'];
        } else {
             // Jika ada tanggal putaran 2, anggap itu yang terakhir
             $is_putaran_2 = true;
        }
    }

    // Set Countdown Pengumuman
    if ($tgl && $jam_pengumuman_cek) {
        try {
            $waktu_pengumuman_obj = new DateTime("$tgl $jam_pengumuman_cek");
            $countdown_target_announcement = $waktu_pengumuman_obj->format('Y-m-d\TH:i:s');
            $waktu_pengumuman_obj_plus_5min = (clone $waktu_pengumuman_obj)->add(new DateInterval('PT2M')); 
        } catch (Exception $e) { }
    }

    // Tentukan State (Before, During, After)
    if ($tgl && $mulai && $selesai) {
        $start_time = new DateTime("$tgl $mulai");
        $end_time = new DateTime("$tgl $selesai");
        
        if ($now < $start_time) {
            $election_state = 'BEFORE'; 
            $countdown_target_date = $start_time->format('Y-m-d\TH:i:s');
        } elseif ($now >= $start_time && $now <= $end_time) {
            $election_state = 'DURING'; 
        } else {
            if (isset($waktu_pengumuman_obj) && $now < $waktu_pengumuman_obj) {
                $election_state = 'AFTER_PENDING'; 
            } elseif (isset($waktu_pengumuman_obj_plus_5min) && $now < $waktu_pengumuman_obj_plus_5min) {
                $election_state = 'AFTER_ANNOUNCEMENT_BUFFER';
            } else {
                $election_state = 'AFTER_FINISHED'; 
            }
        }
    } else {
        $election_state = 'AFTER_FINISHED';
    }
}

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];
}

// =========================================================================
// == 3. PROSES FORM (LOGIN & VOTE)
// =========================================================================

// --- LOGIN ADMIN ---
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['admin_login_submit'])) {
    $username = $_POST['username'] ?? '';
    $password = $_POST['password'] ?? '';

    if (empty($username) || empty($password)) {
        $error_login_admin = 'Username dan password tidak boleh kosong!';
    } else {
        try {
            $stmt = $pdo->prepare("SELECT id, username, password, nama_lengkap, role FROM users WHERE username = ?");
            $stmt->execute([$username]);
            $user = $stmt->fetch();

            if ($user && password_verify($password, $user['password'])) {
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['role'] = $user['role'];
                $_SESSION['nama_lengkap'] = $user['nama_lengkap'];
                
                if ($user['role'] === 'admin') {
                    header("Location: admin/dashboard.php");
                } else {
                    $error_login_admin = 'Halaman ini hanya untuk Admin.';
                }
                exit();
            } else {
                $error_login_admin = 'Username atau password salah!';
            }
        } catch (PDOException $e) {
            $error_login_admin = "Terjadi masalah dengan koneksi database.";
        }
    }
}

// --- LOGIN VOTER ---
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['token'])) {
    if ($election_state == 'DURING') {
        $token = $_POST['token'];
        if (empty($token)) {
            $error_login_voter = 'Token tidak boleh kosong.';
        } else {
            $stmt = $pdo->prepare("SELECT * FROM pemilih WHERE nis_token = ? AND id_tahun_fk = ?");
            $stmt->execute([$token, $id_tahun_aktif]);
            $pemilih = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($pemilih) {
                if ($pemilih['status_memilih'] == 'sudah') {
                    $error_login_voter = 'Token ini sudah digunakan untuk memilih.';
                } else {
                    $_SESSION['voter_id'] = $pemilih['id_pemilih'];
                    $_SESSION['voter_name'] = $pemilih['nama_lengkap'];
                    header("Location: index.php");
                    exit;
                }
            } else {
                $error_login_voter = 'Token tidak valid atau tidak terdaftar.';
            }
        }
    }
}

// --- SUBMIT VOTE ---
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['submit_vote'])) {
    if (isset($_SESSION['voter_id']) && isset($_POST['kandidat_id']) && $election_state == 'DURING') {
        $voter_id = $_SESSION['voter_id'];
        $kandidat_id = $_POST['kandidat_id'];
        
        $putaran_saat_ini = ($is_putaran_2) ? 2 : 1;
        
        try {
            $pdo->beginTransaction();
            // Cek status memilih sekali lagi untuk keamanan
            $stmt_pemilih = $pdo->prepare("UPDATE pemilih SET status_memilih = 'sudah' WHERE id_pemilih = ? AND status_memilih = 'belum'");
            $stmt_pemilih->execute([$voter_id]);

            if ($stmt_pemilih->rowCount() > 0) {
                // Update Total Suara di Kandidat (Opsional, untuk backup)
                $stmt_kandidat = $pdo->prepare("UPDATE kandidat SET total_suara = total_suara + 1 WHERE id_kandidat = ?");
                $stmt_kandidat->execute([$kandidat_id]);
                
                // Insert ke Tabel Suara
                $stmt_suara = $pdo->prepare("INSERT INTO suara (id_tahun_fk, id_kandidat_fk, id_pemilih_fk, putaran) VALUES (?, ?, ?, ?)");
                $stmt_suara->execute([$id_tahun_aktif, $kandidat_id, $voter_id, $putaran_saat_ini]);
                
                $pdo->commit();
                $_SESSION['vote_success'] = true;
            } else {
                $pdo->rollBack();
                $error_login_voter = 'Suara Anda sudah tercatat sebelumnya.';
            }
        } catch (PDOException $e) {
            $pdo->rollBack();
            $error_login_voter = 'Terjadi kesalahan teknis. Silakan coba lagi.';
        }
        
        unset($_SESSION['voter_id']);
        unset($_SESSION['voter_name']);
        header("Location: index.php");
        exit;
    }
}

if (isset($_SESSION['vote_success'])) {
    $vote_success = true;
    unset($_SESSION['vote_success']);
}

// =========================================================================
// == 4. LOGIKA HITUNG HASIL (PERBAIKAN: AGAR MUNCUL SAAT SELESAI)
// =========================================================================
$total_suara_masuk = 0;
$kandidat_list_sorted = [];
$putaran_selesai = 1; // Default

// Tentukan putaran mana yang akan ditampilkan hasilnya
if ($is_putaran_2) {
    $putaran_selesai = 2;
}

// Hanya hitung jika sudah masuk masa pengumuman atau selesai
if ($election_state == 'AFTER_FINISHED' || $election_state == 'AFTER_ANNOUNCEMENT_BUFFER') {
    
    // Iterasi kandidat yang ada
    foreach ($kandidat_list as $k) {
        // Hitung suara real-time dari tabel 'suara' berdasarkan putaran yang aktif
        $stmt_hitung = $pdo->prepare("SELECT COUNT(*) FROM suara WHERE id_kandidat_fk = ? AND putaran = ? AND id_tahun_fk = ?");
        $stmt_hitung->execute([$k['id_kandidat'], $putaran_selesai, $id_tahun_aktif]);
        $jumlah_suara = $stmt_hitung->fetchColumn();

        // Masukkan jumlah suara ke array kandidat
        $k['total_suara'] = $jumlah_suara; 
        
        $kandidat_list_sorted[] = $k;
        $total_suara_masuk += $jumlah_suara;
    }

    // Urutkan array kandidat berdasarkan suara terbanyak (Descending)
    usort($kandidat_list_sorted, function($a, $b) {
        return $b['total_suara'] <=> $a['total_suara'];
    });
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PILKASIM - <?= htmlspecialchars($pengaturan['nama_sekolah'] ?? 'MA Darul Ulum Palangka Raya') ?></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; --footer-bg: #8c0060;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            color: #333;
            background: linear-gradient(135deg, var(--primary), var(--bg-light), var(--dark), var(--primary));
            background-size: 400% 400%;
            animation: gradientMove 25s ease infinite;
            overflow-x: hidden;
        }
        
        @keyframes gradientMove {
            0% { background-position: 0% 50%; }
            50% { background-position: 100% 50%; }
            100% { background-position: 0% 50%; }
        }

        .main-container { max-width: 960px; margin: 0 auto; padding: 1rem; }
        
        .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 img { height: 60px; width: 60px; } }
        
        .welcome-section, .election-info-section {
            text-align: center; padding: 2.5rem 1.5rem; background-color: #fff;
            border-radius: 1rem; box-shadow: 0 4px 25px rgba(0,0,0,0.05); margin-bottom: 2.5rem;
        }
        .welcome-section h1, .election-info-section h1 {
            color: var(--primary); font-weight: 700; margin-bottom: 1rem;
        }
        .welcome-section .lead { font-size: 1rem; color: #555; max-width: 700px; margin: 0 auto 1.5rem; }
        .welcome-section .signature { font-weight: 600; color: var(--dark); }

        .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;
        }
        .countdown-section h3 { font-weight: 300; letter-spacing: 1px; }
        #countdown-timer, #announcement-countdown-timer { display: flex; justify-content: center; gap: 0.9rem; margin-top: 1.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; }
        .timer-box .label { font-size: 0.8rem; opacity: 0.8; text-transform: uppercase; }
        
        .campaign-carousel {
            margin-bottom: 2.5rem;
            border-radius: 1rem;
            overflow: hidden; 
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        }
        .campaign-carousel .carousel-item img,
        .campaign-carousel .carousel-item iframe {
            width: 100%;
            height: auto;
        }
        .campaign-carousel .carousel-item a { display: block; }
        .carousel-caption {
            background: linear-gradient(180deg, rgba(0,0,0,0) 0%, rgba(0,0,0,0.8) 100%);
            bottom: 0; left: 0; right: 0; padding: 1.5rem;
        }
        .carousel-caption h5 {
          font-weight: 700; display: inline-block; padding: 0.5rem 0.75rem;
          border-radius: 0.375rem; color: #fff; background-color: var(--bs-primary, #0d6efd);
        }
         .carousel-caption p {
          font-weight: 500; display: inline-block; padding: 0.5rem 0.75rem;
          border-radius: 0.375rem; color: #fff; background-color: var(--bs-success, #198754);
        }

        .login-section {
            padding: 2rem; background-color: #fff; border-radius: 1rem;
            box-shadow: 0 4px 25px rgba(0,0,0,0.05); max-width: 500px; margin: 2.5rem auto;
        }
        .login-section h2 { text-align: center; color: var(--primary); font-weight: 700; margin-bottom: 1.5rem; }
        .btn-login {
            background-color: var(--accent); border-color: var(--accent);
            width: 100%; padding: 0.75rem; font-weight: 600;
        }
        .btn-login:hover { background-color: #800057; border-color: #800057; }
        
        .voting-section { padding: 2rem; background-color: #fff; border-radius: 1rem; box-shadow: 0 4px 25px rgba(0,0,0,0.05); margin: 2.5rem auto; }
        .kandidat-card-vote {
            border: 3px solid #e9ecef;
            border-radius: 1rem;
            margin-bottom: 1.5rem;
            cursor: pointer;
            transition: all 0.2s ease;
            background-color: #fff;
            overflow: hidden;
            width: 275px;
            height: 100%; min-height: 400px;
        }
        .kandidat-card-vote .vote-no-urut {
            font-size: 3.5rem; font-weight: 900; color: var(--primary);
            margin-top: 1rem; line-height: 1; text-align: center;
        }
        .kandidat-card-vote img { height: 200px; width: 100%; object-fit: cover; }
        .kandidat-card-vote .card-body { text-align: center; padding: 1.5rem; }
        .kandidat-card-vote .card-title { font-weight: 700; color: var(--dark); font-size: 1.2rem; }
        .kandidat-card-vote .card-text { font-size: 0.9rem; font-style: italic; color: #555; }
        
        .kandidat-card-vote.grayscale { filter: grayscale(100%); opacity: 0.7; }
        .kandidat-card-vote.selected {
            border-color: var(--primary);
            box-shadow: 0 0 20px rgba(74, 139, 223, 0.5);
            transform: scale(1.03); filter: grayscale(0%); opacity: 1;
        }
        .btn-vote {
            background-color: var(--primary); border-color: var(--primary);
            padding: 0.75rem; font-size: 1.1rem; font-weight: 600;
        }
        .btn-vote:hover { background-color: var(--dark); border-color: var(--dark); }

        .thankyou-section {
            text-align: center; padding: 4rem 2rem; background-color: #fff;
            border-radius: 1rem; box-shadow: 0 4px 25px rgba(0,0,0,0.05);
            margin: 2.5rem auto; max-width: 600px;
        }
        .thankyou-icon { font-size: 5rem; color: var(--primary); margin-bottom: 1.5rem; }
        
        .hasil-akhir-section {
            padding: 2.5rem 1.5rem; background-color: #fff;
            border-radius: 1rem; box-shadow: 0 4px 25px rgba(0,0,0,0.05); margin-bottom: 2.5rem;
        }
        .hasil-akhir-section h2 { text-align: center; color: var(--primary); font-weight: 700; margin-bottom: 2rem; }
        .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; }
        .progress-bar.bar-winner { background-color: var(--accent); }
        .progress-bar.bar-top3 { background-color: var(--accent); }
        
        .footer-section { background-color: var(--footer-bg); color: #f8f9fa; padding: 3rem 1.5rem; margin-top: 3rem; }
        .footer-section h5 { font-weight: 700; color: white; margin-bottom: 1rem; text-transform: uppercase; letter-spacing: 1px; font-size: 0.9rem; }
        .footer-links { list-style: none; padding: 0; }
        .footer-links li { margin-bottom: 0.5rem; }
        .footer-links a { color: #e9ecef; text-decoration: none; transition: all 0.2s ease; font-size: 0.9rem; }
        .footer-links a:hover { color: white; padding-left: 5px; }
        .footer-contact p { font-size: 0.9rem; line-height: 1.6; color: #e9ecef; margin-bottom: 0.5rem; }
        .footer-contact p strong { color: white; }
        
        /* Modal Admin Styles */
        #adminLoginModal .login-card { max-width: none; width: 100%; border: none; border-radius: 0; box-shadow: none; overflow: hidden; }
        #adminLoginModal .modal-header { background-color: var(--primary); color: white; padding: 2rem; text-align: center; border-bottom: 0; display: block; }
        #adminLoginModal .modal-header .btn-close { position: absolute; top: 1rem; right: 1rem; filter: invert(1) grayscale(100%) brightness(200%); }
        #adminLoginModal .logo-circle { width: 70px; height: 70px; background: rgba(255, 255, 255, 0.2); border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 1rem; font-size: 2.5rem; color: white; }
        #adminLoginModal .logo-circle img { width: 100%; height: 100%; object-fit: cover; border-radius: 50%; }
        #adminLoginModal .login-header h3 { margin: 0; font-weight: 700; }
        #adminLoginModal .login-header p { margin: 0.25rem 0 0; opacity: 0.9; font-size: 0.9rem; }
        #adminLoginModal .modal-body { padding: 2rem; }
        #adminLoginModal .modal-footer { display: none; }
        #adminLoginModal .form-label { font-weight: 500; font-size: 0.875rem; }
        #adminLoginModal .input-group .form-control { border-left: 0; padding-left: 0.5rem; }
        #adminLoginModal .input-group .form-control:focus { box-shadow: none; border-color: var(--primary); }
        #adminLoginModal .input-group .input-group-text { background-color: #f8f9fa; border-right: 0; color: var(--primary); }
        #adminLoginModal .input-group { transition: all 0.2s ease-in-out; }
        #adminLoginModal .input-group:focus-within { box-shadow: 0 0 0 0.25rem rgba(74, 139, 223, 0.25); }
        #adminLoginModal .btn-login { display: block; width: 100%; padding: 0.75rem; background-color: var(--primary); color: white; border: none; border-radius: 0.5rem; font-weight: 600; font-size: 1rem; transition: all 0.2s ease; margin-top: 1.5rem; }
        #adminLoginModal .btn-login:hover { background-color: var(--dark); }
        #adminLoginModal .btn-login:disabled { opacity: 0.7; cursor: wait; }

        .link-hasil {color: yellowgreen; text-decoration: none; }
        .link-hasil:visited { color: yellowgreen; }
        .link-hasil:hover { color: #ccff66; }
    </style>
</head>
<body>

    <div class="main-container">
        
        <a href="#"
        data-bs-toggle="modal" 
        data-bs-target="#adminLoginModal"
        style="
            position: absolute; top: 1rem; left: 1rem;
            color: var(--dark);
            font-weight: 600;
            text-decoration: none;
            padding: 4px 8px;
            border-radius: 4px;
            transition: all 0.2s ease;
            background: rgba(255,255,255,0.8);
            box-shadow: 0 2px 4px rgba(0,0,0,0.15);
            z-index: 10;
            font-size: 0.8rem;
            text-transform: uppercase;">LOGIN ADMIN
        </a>

        <header class="logo-header">
            <?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>

        <main>
            
            <?php if (!$tahun_aktif_data): ?>
                
                <div class="welcome-section">
                    <h1>Pemilihan Belum Dikonfigurasi</h1>
                    <p class="lead">Saat ini belum ada jadwal pemilihan yang diatur oleh administrator. Silakan kembali lagi nanti.</p>
                </div>

            <?php elseif ($vote_success): ?>

                <div class="thankyou-section">
                    <div class="thankyou-icon bi bi-check-circle-fill"></div>
                    <h2>Terima Kasih!</h2>
                    <p class="lead">Suara Anda telah berhasil dicatat untuk <?= htmlspecialchars($putaran_aktif_nama) ?>. Partisipasi Anda sangat berarti.</p>
                    <p class="text-muted small">Anda akan diarahkan kembali ke halaman utama...</p>
                </div>

            <?php elseif ($is_voting_session): ?>
                
                <div class="voting-section">
                    
                    <div class="text-start mb-3">
                        <a href="index.php?action=voter_logout" class="btn btn-sm btn-outline-danger" onclick="return confirm('Apakah Anda yakin ingin keluar? Anda harus memasukkan token lagi.')">
                            <i class="bi bi-arrow-left me-1"></i> Keluar
                        </a>
                    </div>
                    <h2 class="text-center">Selamat Datang, <?= htmlspecialchars($_SESSION['voter_name']) ?>!</h2>
                    <p class="text-center text-muted mb-4">Silakan pilih satu kandidat. Pilihan Anda akan otomatis ditandai. Klik "Kirim Suara" jika sudah yakin.</p>
                    
                    <form method="POST" id="voteForm">
                        <input type="hidden" name="submit_vote" value="1">
                        <input type="hidden" name="kandidat_id" id="kandidat_id_input" required>
                        
                        <div class="row row-cols-1 row-cols-md-3 g-4 justify-content-center">
                            <?php foreach ($kandidat_list as $k): ?>
                                <div class="col d-flex justify-content-center">
                                    <div class="card kandidat-card-vote" data-kandidat-id="<?= $k['id_kandidat'] ?>">
                                        <div class="card-body">
                                            <div class="vote-no-urut"><?= htmlspecialchars($k['no_urut']) ?></div>
                                            <img src="assets/img/kandidat/<?= htmlspecialchars($k['foto_paslon']) ?>" class="card-img-top my-3 rounded" alt="Foto Kandidat">
                                            <h5 class="card-title"><?= htmlspecialchars($k['nama_ketua']) ?> & <?= htmlspecialchars($k['nama_wakil']) ?></h5>
                                            <p class="card-text">"<?= htmlspecialchars($k['slogan']) ?>"</p>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                        
                        <button type="submit" class="btn btn-primary w-100 btn-lg btn-vote mt-4" disabled>
                            Kirim Suara Anda
                        </button>
                    </form>
                </div>

            <?php else: ?>

                <?php if ($election_state == 'BEFORE'): ?>
                    <section class="welcome-section">
                        <h1><?= htmlspecialchars($putaran_aktif_nama) ?> </h1>
                        <?php if(!empty($ketua_panitia['sambutan'])): ?>
                            <p class="lead"><?= $ketua_panitia['sambutan'] ?></p>
                            <p class="signature mb-0"><?= $ketua_panitia['nama'] ?><br>Ketua Komisi Pemilihan OSIM</p>
                        <?php endif; ?>
                    </section>
                    
                    <section class="countdown-section">
                        <h3>Pemungutan Suara : <?= tgl_indo($tgl) ?> </h3>
                        
                        <?php if($is_putaran_2): ?>
                            <p class="mb-2"><a href="hasil_putaran_1.php" target="_blank" class="link-hasil fw-bold">Lihat Arsip Hasil Putaran 1</a></p>
                        <?php endif; ?>

                        <div id="countdown-timer" data-target-date="<?= htmlspecialchars($countdown_target_date) ?>">
                            <div class="timer-box"><span id="days">00</span> <span class="label">Hari</span></div>
                            <div class="timer-box"><span id="hours">00</span> <span class="label">Jam</span></div>
                            <div class="timer-box"><span id="minutes">00</span> <span class="label">Menit</span></div>
                            <div class="timer-box"><span id="seconds">00</span> <span class="label">Detik</span></div>
                        </div>
                    </section>
                    
                    <section class="campaign-section">
                        <h2 class="mb-4">Banner Kampanye Kandidat</h2>
                        <div id="campaignCarousel" class="carousel slide campaign-carousel" data-bs-ride="carousel">
                            <div class="carousel-indicators">
                                <?php $i = 0; foreach ($kandidat_list as $k): ?>
                                    <?php if (!empty($k['file_banner'])): ?>
                                        <button type="button" data-bs-target="#campaignCarousel" data-bs-slide-to="<?= $i ?>" class="<?= $i == 0 ? 'active' : '' ?>"></button>
                                    <?php $i++; endif; ?>
                                <?php endforeach; ?>
                            </div>
                            <div class="carousel-inner">
                                <?php $i = 0; foreach ($kandidat_list as $k): ?>
                                    <?php if (!empty($k['file_banner'])): 
                                        $banner_path = 'assets/img/banner/' . htmlspecialchars($k['file_banner']);
                                        $is_pdf = strtolower(pathinfo($banner_path, PATHINFO_EXTENSION)) == 'pdf';
                                    ?>
                                        <div class="carousel-item <?= $i == 0 ? 'active' : '' ?>">
                                            <a href="<?= $banner_path ?>" target="_blank">
                                                <?php if ($is_pdf): ?>
                                                    <iframe src="<?= $banner_path ?>" title="Banner PDF"></iframe>
                                                <?php else: ?>
                                                    <img src="<?= $banner_path ?>" class="d-block" alt="Banner Kandidat">
                                                <?php endif; ?>
                                                <div class="carousel-caption d-none d-md-block">
                                                    <h5>Nomor Urut <?= htmlspecialchars($k['no_urut']) ?></h5><br>
                                                    <p><?= htmlspecialchars($k['nama_ketua']) ?> & <?= htmlspecialchars($k['nama_wakil']) ?></p>
                                                </div>
                                            </a>
                                        </div>
                                    <?php $i++; endif; ?>
                                <?php endforeach; ?>
                            </div>
                            <button class="carousel-control-prev" type="button" data-bs-target="#campaignCarousel" data-bs-slide="prev">
                                <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                                <span class="visually-hidden">Previous</span>
                            </button>
                            <button class="carousel-control-next" type="button" data-bs-target="#campaignCarousel" data-bs-slide="next">
                                <span class="carousel-control-next-icon" aria-hidden="true"></span>
                                <span class="visually-hidden">Next</span>
                            </button>
                        </div>
                    </section>
                <?php endif; ?>

                <?php if ($election_state == 'DURING'): ?>
                    <section class="election-info-section text-center">
                        <h1 class="mb-2"><?= htmlspecialchars($putaran_aktif_nama) ?> </h1>
                        <h5><?= tgl_indo($tgl) ?> </h5>
                        </section>
                <?php endif; ?>
                
                <?php if ($election_state == 'AFTER_PENDING'): ?>
                    <section class="election-info-section text-center">
                        <h1 class="mb-2"><?= htmlspecialchars($putaran_aktif_nama) ?> </h1>
                        <h5><?= tgl_indo($tgl) ?> </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>
                <?php endif; ?>

                <?php if ($election_state == 'AFTER_ANNOUNCEMENT_BUFFER'): ?>
                    <section class="welcome-section">
                        <h1 class="mb-2"><?= htmlspecialchars($putaran_aktif_nama) ?> </h1>
                        <h5><?= tgl_indo($tgl) ?> </h5>
                    </section>
                    
                    <section class="election-info-section text-center">
                        <h3 class="text-success">Waktu Pengumuman Telah Tiba!</h3>
                        <a href="index.php" class="btn btn-lg btn-danger mt-3">
                            <i class="bi bi-trophy-fill me-2"></i> LIHAT HASIL AKHIR
                        </a>
                    </section>
                <?php endif; ?>

                <?php if ($election_state == 'AFTER_FINISHED'): ?>
                    <section class="welcome-section">
                        <h1 class="mb-2"><?= htmlspecialchars($putaran_aktif_nama) ?> </h1>
                        <h5><?= tgl_indo($tgl) ?> </h5>
                        
                        <?php if(!empty($ketua_panitia['sambutan'])): ?>
                            <p class="lead"><?= $ketua_panitia['sambutan'] ?></p>
                            <p class="signature mb-0"><?= $ketua_panitia['nama'] ?><br>Ketua Komisi Pemilihan OSIM</p>
                        <?php endif; ?>
                    </section>
                    
                    <section class="hasil-akhir-section">
                        <h2>Hasil Akhir Pemilihan</h2>
                        
                        <?php if ($total_suara_masuk > 0): ?>
                            <?php
                            $rank = 1;
                            foreach ($kandidat_list_sorted as $k):
                                $persen_kandidat = round(($k['total_suara'] / $total_suara_masuk) * 100, 1);
                                
                                $bar_class = '';
                                if ($putaran_selesai == 2 && $rank == 1) {
                                    $bar_class = 'bar-winner';
                                } elseif ($putaran_selesai == 1 && $rank <= 3) {
                                    $bar_class = 'bar-top3';
                                }
                            ?>
                                <div class="chart-bar-wrapper">
                                    <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 <?= $bar_class ?>" role="progressbar" 
                                             style="width: <?= $persen_kandidat ?>%;" 
                                             aria-valuenow="<?= $persen_kandidat ?>">
                                            <b><?= htmlspecialchars($k['total_suara']) ?> Suara</b>
                                        </div>
                                    </div>
                                </div>
                            <?php
                                $rank++;
                            endforeach;
                            ?>
                            <hr>
                            <div class="text-center text-muted">Total Suara Masuk: <strong><?= $total_suara_masuk ?></strong></div>
                        <?php else: ?>
                            <div class="alert alert-info text-center">Belum ada suara yang masuk.</div>
                        <?php endif; ?>
                    </section>
                    
                    <?php if($is_putaran_2): ?>
                    <div class="text-center mt-4">
                         <a href="hasil_putaran_1.php" class="btn btn-outline-primary mb-5">Lihat Arsip Hasil Putaran 1</a>
                    </div>
                    <?php endif; ?>

                    <section class="campaign-section mt-5">
                        <h2 class="mb-4">Banner Kampanye</h2>
                        <div id="campaignCarousel" class="carousel slide campaign-carousel" data-bs-ride="carousel">
                            <div class="carousel-inner">
                                <?php $i = 0; foreach ($kandidat_list as $k): ?>
                                    <?php if (!empty($k['file_banner'])): 
                                        $banner_path = 'assets/img/banner/' . htmlspecialchars($k['file_banner']);
                                        $is_pdf = strtolower(pathinfo($banner_path, PATHINFO_EXTENSION)) == 'pdf';
                                    ?>
                                        <div class="carousel-item <?= $i == 0 ? 'active' : '' ?>">
                                            <a href="<?= $banner_path ?>" target="_blank">
                                                <?php if ($is_pdf): ?>
                                                    <iframe src="<?= $banner_path ?>" title="Banner PDF"></iframe>
                                                <?php else: ?>
                                                    <img src="<?= $banner_path ?>" class="d-block" alt="Banner Kandidat">
                                                <?php endif; ?>
                                                <div class="carousel-caption d-none d-md-block">
                                                    <h5>Nomor Urut <?= htmlspecialchars($k['no_urut']) ?></h5>
                                                    <p><?= htmlspecialchars($k['nama_ketua']) ?> & <?= htmlspecialchars($k['nama_wakil']) ?></p>
                                                </div>
                                            </a>
                                        </div>
                                    <?php $i++; endif; ?>
                                <?php endforeach; ?>
                            </div>
                            <button class="carousel-control-prev" type="button" data-bs-target="#campaignCarousel" data-bs-slide="prev">
                                <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                                <span class="visually-hidden">Previous</span>
                            </button>
                            <button class="carousel-control-next" type="button" data-bs-target="#campaignCarousel" data-bs-slide="next">
                                <span class="carousel-control-next-icon" aria-hidden="true"></span>
                                <span class="visually-hidden">Next</span>
                            </button>
                        </div>
                    </section>
                <?php endif; ?>

                <?php if ($election_state == 'DURING'): ?>
                    <section class="login-section">
                        <h2>Bilik Suara</h2>
                        <?php if ($error_login_voter): ?>
                            <div class="alert alert-danger"><?= htmlspecialchars($error_login_voter) ?></div>
                        <?php endif; ?>

                        <form method="POST" action="index.php" id="tokenForm">
                            <div class="mb-3">
                                <label for="token" class="form-label">Masukkan NIS/Token Anda</label>
                                <input type="text" class="form-control form-control-lg" id="token" name="token" required>
                            </div>
                            <button type="submit" class="btn btn-primary btn-lg btn-login" name="token_submit" value="1">
                                Masuk Bilik Suara
                            </button>
                        </form>
                    </section>
                <?php endif; ?>

            <?php endif; // Akhir dari cek session vote/sukses ?>
            
        </main>
    </div>

     <footer class="footer-section">
        <div class="container">
            <div class="row">
                
                <div class="col-md-4">
                    <h5>KOMISI PEMILIHAN OSIM</h5>
                    <div class="footer-contact">
                        <p>
                            <?php 
                            // Gabungkan Ketua dan Sekretaris
                            $panitia_display = [];
                            if(!empty($panitia_footer['Ketua'])) {
                                $panitia_display[] = implode(', ', $panitia_footer['Ketua']) . ' <b>(Ketua)</b>';
                            }
                            if(!empty($panitia_footer['Sekretaris'])) {
                                $panitia_display[] = implode(', ', $panitia_footer['Sekretaris']) . ' <b>(Sekretaris)</b>'; 
                            }
                            echo implode(' | ', $panitia_display);
                            ?>
                        
                        <?php if(!empty($panitia_footer['Anggota'])): ?>
                            <b>Anggota : </b><?= implode(', ', $panitia_footer['Anggota']) ?></p>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="col-md-4 mb-4 mb-md-0 text-center"> <h5>Media Sosial</h5> 
                    <ul class="footer-links d-inline-block text-start"> 
                        <?php foreach ($footer_info['kontak'] as $nama => $link): ?>
                            <?php if (!empty($link) && $link !== '#'): ?>
                                <li><a href="<?= htmlspecialchars($link) ?>" target="_blank"><i class="bi bi-<?= strtolower($nama) ?>"></i> <?= htmlspecialchars($nama) ?></a></li>
                            <?php endif; ?>
                        <?php endforeach; ?>
                    </ul>
                </div>
                <div class="col-md-4 mb-4 mb-md-0">
                    <h5>Kontak Kami</h5>
                    <div class="footer-contact">
                        <p>
                            <?php 
                            $kontak_display = [];
                            if(!empty($footer_info['alamat'])) { $kontak_display[] = $footer_info['alamat']; }
                            if(!empty($footer_info['no_telepon'])) { $kontak_display[] = 'Tel. ' . $footer_info['no_telepon']; }
                            if(!empty($footer_info['email'])) { $kontak_display[] = $footer_info['email']; }
                            echo implode(' | ', $kontak_display);
                            ?>
                        </p>
                    </div>
                </div>
                
            </div>
            
            <hr class="my-4" style="border-color: rgba(255,255,255,0.2);">
            <p class="text-center text-white-50 mb-0 small">
                &copy; <?= date('Y'); ?> PILKASIM - <?= htmlspecialchars($pengaturan['nama_sekolah'] ?? 'MA Darul Ulum Palangka Raya') ?>. All rights reserved.
            </p>
        </div>
    </footer>

    <div class="modal fade" id="confirmVoteModal" tabindex="-1" aria-labelledby="confirmVoteModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header" style="background-color: var(--primary); color: white;">
                    <h5 class="modal-title" id="confirmVoteModalLabel">Konfirmasi Pilihan Anda</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p class="fs-5">Apakah Anda yakin dengan pilihan Anda?</p>
                    <p class="text-danger"><strong>Suara tidak dapat diubah setelah disimpan.</strong></p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                    <button type="button" class="btn btn-primary" id="btn-confirm-vote">Ya, Saya Yakin</button>
                </div>
            </div>
        </div>
    </div>
    
    <div class="modal fade" id="adminLoginModal" tabindex="-1" aria-labelledby="adminLoginModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content" style="border-radius: 1rem; overflow: hidden;">
                <div class="login-card">
                    <div class="modal-header login-header">
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        <h3>ADMIN PILKASIM</h3>
                        <p><b><?= htmlspecialchars($pengaturan['nama_sekolah'] ?? 'MA Darul Ulum Palangka Raya') ?></b></p>
                    </div>

                    <div class="modal-body login-body">
                        <?php if ($error_login_admin): ?>
                            <div class="alert alert-danger d-flex align-items-center" role="alert">
                                <i class="bi bi-exclamation-triangle-fill me-2"></i>
                                <div><?= htmlspecialchars($error_login_admin) ?></div>
                            </div>
                        <?php endif; ?>

                        <form action="index.php" method="post" id="adminLoginForm">
                            <input type="hidden" name="admin_login_submit" value="1">
                            
                            <div class="mb-3">
                                 <label for="username" class="form-label">Username</label>
                                 <div class="input-group">
                                    <span class="input-group-text"><i class="bi bi-person"></i></span>
                                    <input type="text" class="form-control" id="admin_username" name="username" required>
                                 </div>
                            </div>
                             <div class="mb-3">
                                <label for="password" class="form-label">Password</label>
                                 <div class="input-group">
                                    <span class="input-group-text"><i class="bi bi-shield-lock"></i></span>
                                    <input type="password" class="form-control" id="admin_password" name="password" required>
                                 </div>
                            </div>
                            <button type="submit" class="btn-login" id="adminLoginBtn">
                                <span class="spinner-border spinner-border-sm d-none" role="status" aria-hidden="true"></span>
                                <span class="login-text">Login</span>
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
    document.addEventListener("DOMContentLoaded", function() {

        // --- Logika 1: Countdown Timer (PEMILIHAN) ---
        const countdownTimer = document.getElementById('countdown-timer');
        if (countdownTimer) {
            const targetDateStr = countdownTimer.getAttribute('data-target-date');
            const targetDate = new Date(targetDateStr).getTime();
            const interval = setInterval(function() {
                const now = new Date().getTime();
                const distance = targetDate - now;
                if (distance < 0) {
                    clearInterval(interval);
                    window.location.reload(); 
                    return;
                }
                document.getElementById('days').innerText = Math.floor(distance / (1000 * 60 * 60 * 24)).toString().padStart(2, '0');
                document.getElementById('hours').innerText = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)).toString().padStart(2, '0');
                document.getElementById('minutes').innerText = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)).toString().padStart(2, '0');
                document.getElementById('seconds').innerText = Math.floor((distance % (1000 * 60)) / 1000).toString().padStart(2, '0');
            }, 1000);
        }
        
        // --- Logika 2: Countdown Timer (PENGUMUMAN) ---
        const announcementTimer = document.getElementById('announcement-countdown-timer');
        if (announcementTimer) {
            const targetDateStr = announcementTimer.getAttribute('data-target-date');
            const targetDate = new Date(targetDateStr).getTime();

            const interval = setInterval(function() {
                const now = new Date().getTime();
                const distance = targetDate - now;

                if (distance < 0) {
                    clearInterval(interval);
                    window.location.reload(); 
                    return;
                }
                
                const daysEl = document.getElementById('ann_days');
                const hoursEl = document.getElementById('ann_hours');
                const minutesEl = document.getElementById('ann_minutes');
                const secondsEl = document.getElementById('ann_seconds');

                if (daysEl) daysEl.innerText = Math.floor(distance / (1000 * 60 * 60 * 24)).toString().padStart(2, '0');
                if (hoursEl) hoursEl.innerText = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)).toString().padStart(2, '0');
                if (minutesEl) minutesEl.innerText = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)).toString().padStart(2, '0');
                if (secondsEl) secondsEl.innerText = Math.floor((distance % (1000 * 60)) / 1000).toString().padStart(2, '0');
            }, 1000);
        }

        // --- Logika 3: Pemilihan Kartu Kandidat (Efek Grayscale) ---
        const voteForm = document.getElementById('voteForm');
        if (voteForm) {
            const kandidatCards = voteForm.querySelectorAll('.kandidat-card-vote');
            const hiddenInput = voteForm.querySelector('#kandidat_id_input');
            const submitButton = voteForm.querySelector('.btn-vote');
            const confirmVoteModal = new bootstrap.Modal(document.getElementById('confirmVoteModal'));
            const btnConfirmVote = document.getElementById('btn-confirm-vote');

            kandidatCards.forEach(card => {
                card.addEventListener('click', function() {
                    const selectedId = this.getAttribute('data-kandidat-id');
                    kandidatCards.forEach(c => {
                        c.classList.remove('selected');
                        c.classList.remove('grayscale');
                    });
                    this.classList.add('selected');
                    kandidatCards.forEach(c => {
                        if (c.getAttribute('data-kandidat-id') !== selectedId) {
                            c.classList.add('grayscale');
                        }
                    });
                    hiddenInput.value = selectedId;
                    submitButton.disabled = false;
                });
            });
            
            voteForm.addEventListener('submit', function(event) {
                event.preventDefault(); 
                confirmVoteModal.show(); 
            });

            btnConfirmVote.addEventListener('click', function() {
                voteForm.submit(); 
            });
        }
        
        // --- Logika 4: Redirect Halaman Terima Kasih ---
        const thankyouSection = document.querySelector('.thankyou-section');
        if (thankyouSection) {
            setTimeout(function() {
                window.location.href = 'index.php';
            }, 4000); 
        }
        
        // --- Logika 5: Fokus ke input token jika ada ---
        const tokenInput = document.getElementById('token');
        if(tokenInput) {
            tokenInput.focus();
        }

        // --- Logika 6: Spinner Tombol Login Admin ---
        document.getElementById('adminLoginForm')?.addEventListener('submit', function() {
            const btn = document.getElementById('adminLoginBtn');
            const spinner = btn.querySelector('.spinner-border');
            const text = btn.querySelector('.login-text');
            
            btn.disabled = true;
            spinner.classList.remove('d-none');
            text.textContent = 'Memproses...';
        });
        
        // --- Logika 7: Fokus ke input username admin saat modal muncul ---
        const adminLoginModalEl = document.getElementById('adminLoginModal');
        if(adminLoginModalEl) {
            adminLoginModalEl.addEventListener('shown.bs.modal', function() {
                document.getElementById('admin_username')?.focus();
            });
        }

    });
    </script>
    
    <?php
    // --- Logika 8: Buka Modal Admin jika ada Error ---
    if (!empty($error_login_admin)): 
    ?>
    <script>
        document.addEventListener("DOMContentLoaded", function() {
            var adminLoginModal = new bootstrap.Modal(document.getElementById('adminLoginModal'));
            adminLoginModal.show();
        });
    </script>
    <?php endif; ?>
    
</body>
</html>