<?php
// Read candidate and result data
$kandidat_data = json_decode(file_get_contents('../data/kandidat.json'), true);
$hasil_data = json_decode(file_get_contents('../data/hasil.json'), true);
$pemilih_data = json_decode(file_get_contents('../data/pemilih.json'), true);

// Initial data load for the first page render
$total_pemilih = count($pemilih_data);
$total_suara_mentah = array_sum($hasil_data);
$total_suara = min($total_suara_mentah, $total_pemilih);
$pemenang = null;
$suara_tertinggi = 0;
$is_imbang = false; // Tambahkan variabel is_imbang
if (!empty($hasil_data)) {
    arsort($hasil_data);
    $suara_tertinggi = reset($hasil_data);

    // Check for a tie
    $suara_tertinggi_count = 0;
    foreach ($hasil_data as $suara) {
        if ($suara == $suara_tertinggi) {
            $suara_tertinggi_count++;
        }
    }

    if ($suara_tertinggi_count > 1) {
        $is_imbang = true;
    }

    if ($is_imbang) {
        $pemenang = "Imbang";
    } else {
        $pemenang_id = key($hasil_data);
        foreach ($kandidat_data as $kandidat) {
            if ($kandidat['id'] == $pemenang_id) {
                $pemenang = $kandidat['nama'];
                break;
            }
        }
    }
}
$partisipasi = ($total_pemilih > 0) ? round(($total_suara / $total_pemilih) * 100, 2) : 0;

?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hasil Pemilihan OSIS - SMK Al Ikhlas Tarokan Kediri</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        .progress-bar {
            transition: width 0.5s ease-in-out;
        }

        .card-kandidat {
            @apply relative overflow-hidden rounded-xl shadow-lg transition-transform duration-300 ease-in-out hover:scale-105;
        }

        .card-image-wrapper {
            @apply relative w-full pt-[100%];
        }

        .card-kandidat img {
            @apply absolute inset-0 w-full h-full object-cover;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(20px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        @keyframes pulse-winner {

            0%,
            100% {
                box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06), 0 0 0 4px rgba(253, 230, 138, 0);
            }

            50% {
                box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06), 0 0 0 4px rgba(253, 230, 138, 1);
            }
        }

        .animate-fade-in {
            animation: fadeIn 0.8s ease-out forwards;
        }

        .animate-pulse-winner {
            animation: pulse-winner 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
        }
    </style>
</head>

<body class="bg-gradient-to-br from-gray-200 to-gray-300 font-sans min-h-screen">
    <div class="container mx-auto p-4 sm:p-8">
        <header class="flex flex-col md:flex-row justify-between items-center bg-white rounded-xl shadow-lg p-4 mb-8 transition-all duration-500 animate-fade-in">
            <div class="flex flex-col md:flex-row items-center space-x-0 md:space-x-4 mb-4 md:mb-0 text-center md:text-left">
                <img src="../public/assets/images/logo_sekolah.png" alt="Logo Sekolah" class="w-16 h-16 md:w-20 md:h-20 object-contain mb-2 md:mb-0">
                <div>
                    <h1 class="text-xl md:text-3xl font-extrabold text-gray-800">SMK Al Ikhlas Tarokan Kediri</h1>
                    <p class="text-sm md:text-lg text-gray-600">Pemilihan Ketua OSIS Periode 2024/2025</p>
                </div>
            </div>
            <a href="login.php" class="bg-blue-600 text-white py-2 px-6 rounded-lg hover:bg-blue-700 transition-colors duration-300 font-semibold shadow-md">
                Vote Sekarang
            </a>
        </header>

        <div class="grid grid-cols-1 sm:grid-cols-3 gap-4 mb-8 text-center transition-all duration-500 animate-fade-in">
            <div class="bg-white p-6 rounded-xl shadow-lg border-b-4 border-blue-500">
                <p class="text-sm text-gray-500 uppercase font-semibold">Total Pemilih</p>
                <p class="text-3xl font-extrabold text-blue-600 mt-2" id="total-pemilih"><?php echo $total_pemilih; ?></p>
            </div>
            <div class="bg-white p-6 rounded-xl shadow-lg border-b-4 border-green-500">
                <p class="text-sm text-gray-500 uppercase font-semibold">Total Suara Terkumpul</p>
                <p class="text-3xl font-extrabold text-green-600 mt-2" id="total-suara"><?php echo $total_suara; ?></p>
            </div>
            <div class="bg-white p-6 rounded-xl shadow-lg border-b-4 border-yellow-500">
                <p class="text-sm text-gray-500 uppercase font-semibold">Partisipasi</p>
                <p class="text-3xl font-extrabold text-yellow-600 mt-2" id="partisipasi"><?php echo $partisipasi; ?>%</p>
            </div>
        </div>

        <div id="status-box" class="bg-white rounded-xl shadow-lg p-6 mb-8 text-center border-l-4 border-yellow-500 animate-pulse-once">
            <?php if ($total_suara == 0): ?>
                <h2 class="text-xl md:text-2xl font-bold text-gray-700">Status Pemilihan</h2>
                <p class="text-2xl md:text-3xl font-extrabold text-gray-500 mt-2">Belum ada suara yang masuk</p>
            <?php elseif ($is_imbang): ?>
                <h2 class="text-xl md:text-2xl font-bold text-gray-700">Pemimpin Sementara</h2>
                <p class="text-3xl md:text-4xl font-extrabold text-yellow-700 mt-2" id="pemenang-nama">
                    Imbang
                </p>
                <p class="text-sm md:text-md text-gray-600 mt-1">dengan total suara: <span class="font-bold" id="pemenang-suara"><?php echo $suara_tertinggi; ?></span></p>
            <?php elseif ($total_suara == $total_pemilih): ?>
                <h2 class="text-xl md:text-2xl font-bold text-green-700">Ketua OSIS Terpilih</h2>
                <p class="text-3xl md:text-4xl font-extrabold text-green-700 mt-2" id="pemenang-nama">
                    <?php echo htmlspecialchars($pemenang); ?>
                </p>
                <p class="text-sm md:text-md text-gray-600 mt-1">dengan total suara: <span class="font-bold" id="pemenang-suara"><?php echo $suara_tertinggi; ?></span></p>
            <?php else: ?>
                <h2 class="text-xl md:text-2xl font-bold text-gray-700">Pemimpin Sementara</h2>
                <p class="text-3xl md:text-4xl font-extrabold text-yellow-700 mt-2" id="pemenang-nama">
                    <?php echo htmlspecialchars($pemenang); ?>
                </p>
                <p class="text-sm md:text-md text-gray-600 mt-1">dengan total suara: <span class="font-bold" id="pemenang-suara"><?php echo $suara_tertinggi; ?></span></p>
            <?php endif; ?>
        </div>

        <div class="flex flex-wrap justify-center gap-6">
            <?php foreach ($kandidat_data as $index => $kandidat):
                $suara_kandidat = isset($hasil_data[$kandidat['id']]) ? $hasil_data[$kandidat['id']] : 0;
                $persentase = ($total_suara > 0) ? round(($suara_kandidat / $total_suara) * 100, 1) : 0;
                $is_kandidat_pemenang_sementara = ($suara_kandidat == $suara_tertinggi);
            ?>
                <div class="card-kandidat w-full sm:w-1/2 lg:w-1/3 xl:w-1/4 animate-fade-in" style="animation-delay: <?php echo $index * 0.1; ?>s;">
                    <div class="border-4 <?php echo $is_kandidat_pemenang_sementara ? 'border-yellow-500 animate-pulse-winner' : 'border-transparent'; ?>" id="card-<?php echo $kandidat['id']; ?>">
                        <div class="card-image-wrapper">
                            <img src="../public/assets/images/<?php echo htmlspecialchars($kandidat['foto']); ?>" alt="Foto <?php echo htmlspecialchars($kandidat['nama']); ?>">
                        </div>

                        <div class="bg-white p-4 text-center">
                            <h2 class="text-2xl font-bold text-gray-800"><?php echo htmlspecialchars($kandidat['nama']); ?></h2>
                            <p class="text-sm font-semibold text-gray-600">Kandidat No. <?php echo htmlspecialchars($kandidat['id']); ?></p>

                            <div class="text-3xl font-extrabold text-green-600 mt-4" id="suara-<?php echo $kandidat['id']; ?>">
                                <?php echo $suara_kandidat; ?>
                            </div>
                            <p class="text-sm text-gray-500 mt-1" id="persentase-<?php echo $persentase; ?>">Suara (<?php echo $persentase; ?>%)</p>
                            <div class="w-full bg-gray-200 rounded-full h-2.5 mt-2">
                                <div class="progress-bar h-2.5 rounded-full <?php echo $is_kandidat_pemenang_sementara ? 'bg-yellow-500' : 'bg-green-500'; ?>" id="progress-<?php echo $kandidat['id']; ?>" style="width: <?php echo $persentase; ?>%;"></div>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>

        <div class="mt-8 text-center transition-all duration-500 animate-fade-in" style="animation-delay: <?php echo count($kandidat_data) * 0.1; ?>s;">
            <a href="admin_login.php" class="text-gray-500 hover:text-gray-700 hover:underline text-sm md:text-base">Halaman Admin</a>
        </div>
    </div>

    <script>
        function updateResults() {
            fetch('get_data.php')
                .then(response => response.json())
                .then(data => {
                    // Update total vote stats
                    document.getElementById('total-suara').innerText = data.total_suara;
                    document.getElementById('partisipasi').innerText = data.partisipasi + '%';

                    // Update leading candidate info
                    const statusBox = document.getElementById('status-box');

                    if (data.total_suara === 0) {
                        statusBox.innerHTML = `
                            <h2 class="text-xl md:text-2xl font-bold text-gray-700">Status Pemilihan</h2>
                            <p class="text-2xl md:text-3xl font-extrabold text-gray-500 mt-2">Belum ada suara yang masuk</p>
                        `;
                    } else if (data.is_imbang) { // Check for the new 'is_imbang' status
                        statusBox.innerHTML = `
                            <h2 class="text-xl md:text-2xl font-bold text-gray-700">Pemimpin Sementara</h2>
                            <p class="text-3xl md:text-4xl font-extrabold text-yellow-700 mt-2">Imbang</p>
                            <p class="text-sm md:text-md text-gray-600 mt-1">dengan total suara: <span class="font-bold">${data.suara_tertinggi}</span></p>
                        `;
                    } else if (data.total_suara === <?php echo $total_pemilih; ?>) {
                        statusBox.innerHTML = `
                            <h2 class="text-xl md:text-2xl font-bold text-green-700">Ketua OSIS Terpilih</h2>
                            <p class="text-3xl md:text-4xl font-extrabold text-green-700 mt-2">${data.pemenang}</p>
                            <p class="text-sm md:text-md text-gray-600 mt-1">dengan total suara: <span class="font-bold">${data.suara_tertinggi}</span></p>
                        `;
                    } else {
                        statusBox.innerHTML = `
                            <h2 class="text-xl md:text-2xl font-bold text-gray-700">Pemimpin Sementara</h2>
                            <p class="text-3xl md:text-4xl font-extrabold text-yellow-700 mt-2">${data.pemenang}</p>
                            <p class="text-sm md:text-md text-gray-600 mt-1">dengan total suara: <span class="font-bold">${data.suara_tertinggi}</span></p>
                        `;
                    }

                    // Update individual candidate votes
                    data.kandidat_results.forEach(kandidat => {
                        const suaraElem = document.getElementById(`suara-${kandidat.id}`);
                        const persentaseElem = document.getElementById(`persentase-${kandidat.id}`);
                        const progressElem = document.getElementById(`progress-${kandidat.id}`);
                        const cardElem = document.getElementById(`card-${kandidat.id}`);

                        if (suaraElem) {
                            suaraElem.innerText = kandidat.suara;
                            persentaseElem.innerText = `Suara (${kandidat.persentase}%)`;
                            progressElem.style.width = kandidat.persentase + '%';

                            // Handle winner highlight and animation
                            if (kandidat.is_pemenang) {
                                cardElem.classList.add('border-yellow-500', 'animate-pulse-winner');
                                cardElem.classList.remove('border-transparent');
                            } else {
                                cardElem.classList.remove('border-yellow-500', 'animate-pulse-winner');
                                cardElem.classList.add('border-transparent');
                            }
                        }
                    });
                })
                .catch(error => console.error('Error fetching data:', error));
        }

        // Run the update function every 5 seconds
        setInterval(updateResults, 5000);
    </script>
</body>

</html>