<?php
session_start();

if (!isset($_SESSION['admin_logged_in'])) {
    header('Location: admin_login.php');
    exit;
}

$pemilih_data = json_decode(file_get_contents('../data/pemilih.json'), true);

// --- LOGIKA PENCARIAN & PAGINASI ---
$search_query = isset($_GET['search']) ? trim($_GET['search']) : '';
$filtered_data = $pemilih_data;

// Jika ada query pencarian, filter data
if (!empty($search_query)) {
    $filtered_data = array_filter($pemilih_data, function ($pemilih) use ($search_query) {
        // Cari berdasarkan nama (case-insensitive)
        return stripos($pemilih['nama'], $search_query) !== false;
    });
}

$data_per_halaman = 10;
$total_data = count($filtered_data);
$total_halaman = ceil($total_data / $data_per_halaman);
$halaman_saat_ini = isset($_GET['halaman']) ? (int)$_GET['halaman'] : 1;

// Pastikan halaman yang diminta valid
if ($halaman_saat_ini < 1) $halaman_saat_ini = 1;
if ($halaman_saat_ini > $total_halaman && $total_halaman > 0) $halaman_saat_ini = $total_halaman;

$mulai_data = ($halaman_saat_ini - 1) * $data_per_halaman;
$data_halaman_ini = array_slice($filtered_data, $mulai_data, $data_per_halaman);
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manajemen Pemilih</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>

<body class="bg-gray-100 p-8">
    <div class="container mx-auto">
        <div class="flex justify-between items-center mb-4">
            <h1 class="text-3xl font-bold">Manajemen Data Pemilih</h1>
            <div class="flex items-center space-x-2">
                <a href="admin_cetak_kartu_pdf.php" target="_blank" class="bg-green-600 text-white px-4 py-2 rounded hover:bg-green-700 transition-colors duration-300 mr-2">
                    Cetak Kartu Pemilih
                </a>
                <a href="../src/delete_all_pemilih.php" class="bg-red-600 text-white px-4 py-2 rounded hover:bg-red-700 transition-colors duration-300" onclick="return confirm('PERINGATAN! Anda akan menghapus SEMUA data pemilih. Apakah Anda yakin?');">
                    Hapus Semua Data
                </a>
            </div>
        </div>

        <div class="mb-4">
            <form action="" method="GET">
                <div class="flex">
                    <input type="text" name="search" placeholder="Cari nama pemilih..." value="<?php echo htmlspecialchars($search_query); ?>" class="w-full px-4 py-2 border rounded-l-md focus:outline-none focus:ring focus:border-blue-300">
                    <button type="submit" class="bg-blue-500 text-white px-4 py-2 rounded-r-md hover:bg-blue-600">Cari</button>
                </div>
            </form>
        </div>

        <div class="bg-white p-6 rounded-lg shadow-md overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200" id="pemilihTable">
                <thead class="bg-gray-50">
                    <tr>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">No. Pemilih</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Nama</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Kelas</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status Memilih</th>
                        <th scope="col" class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">Aksi</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    <?php foreach ($data_halaman_ini as $pemilih): ?>
                        <tr>
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"><?php echo htmlspecialchars($pemilih['no_pilih']); ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500"><?php echo htmlspecialchars($pemilih['nama']); ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500"><?php echo htmlspecialchars($pemilih['kelas']); ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-center">
                                <?php if ($pemilih['sudah_memilih']): ?>
                                    <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800">Sudah</span>
                                <?php else: ?>
                                    <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-red-100 text-red-800">Belum</span>
                                <?php endif; ?>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-center text-sm font-medium">
                                <a href="admin_edit_pemilih.php?no_pilih=<?php echo urlencode($pemilih['no_pilih']); ?>" class="text-indigo-600 hover:text-indigo-900">Edit</a>
                                <a href="../src/delete_pemilih.php?no_pilih=<?php echo urlencode($pemilih['no_pilih']); ?>" class="text-red-600 hover:text-red-900 ml-4" onclick="return confirm('Apakah Anda yakin ingin menghapus data pemilih ini?');">Hapus</a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <div class="mt-6 flex justify-center">
            <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
                <?php
                // Tentukan query string untuk paginasi, termasuk parameter pencarian
                $query_string = !empty($search_query) ? '&search=' . urlencode($search_query) : '';

                // Tombol "Previous"
                if ($halaman_saat_ini > 1) {
                    echo '<a href="?halaman=' . ($halaman_saat_ini - 1) . $query_string . '" class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50">';
                    echo '    <span class="sr-only">Previous</span>';
                    echo '    <svg class="h-5 w-5" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">';
                    echo '        <path fill-rule="evenodd" d="M12.707 5.293a1 1 0 010 1.414L9.414 10l3.293 3.293a1 1 0 01-1.414 1.414l-4-4a1 1 0 010-1.414l4-4a1 1 0 011.414 0z" clip-rule="evenodd" />';
                    echo '    </svg>';
                    echo '</a>';
                }

                // Logika untuk menampilkan nomor halaman yang ringkas
                $link_range = 2; // Jumlah halaman yang ditampilkan di sekitar halaman saat ini
                $start_page = max(1, $halaman_saat_ini - $link_range);
                $end_page = min($total_halaman, $halaman_saat_ini + $link_range);

                if ($start_page > 1) {
                    echo '<a href="?halaman=1' . $query_string . '" class="relative inline-flex items-center px-4 py-2 border text-sm font-medium ' . ($halaman_saat_ini == 1 ? 'z-10 bg-indigo-50 border-indigo-500 text-indigo-600' : 'bg-white border-gray-300 text-gray-700 hover:bg-gray-50') . '">1</a>';
                    if ($start_page > 2) {
                        echo '<span class="relative inline-flex items-center px-4 py-2 border border-gray-300 bg-white text-sm font-medium text-gray-700">...</span>';
                    }
                }

                for ($i = $start_page; $i <= $end_page; $i++) {
                    echo '<a href="?halaman=' . $i . $query_string . '" class="relative inline-flex items-center px-4 py-2 border text-sm font-medium ' . ($i == $halaman_saat_ini ? 'z-10 bg-indigo-50 border-indigo-500 text-indigo-600' : 'bg-white border-gray-300 text-gray-700 hover:bg-gray-50') . '">';
                    echo $i;
                    echo '</a>';
                }

                if ($end_page < $total_halaman) {
                    if ($end_page < $total_halaman - 1) {
                        echo '<span class="relative inline-flex items-center px-4 py-2 border border-gray-300 bg-white text-sm font-medium text-gray-700">...</span>';
                    }
                    echo '<a href="?halaman=' . $total_halaman . $query_string . '" class="relative inline-flex items-center px-4 py-2 border text-sm font-medium ' . ($halaman_saat_ini == $total_halaman ? 'z-10 bg-indigo-50 border-indigo-500 text-indigo-600' : 'bg-white border-gray-300 text-gray-700 hover:bg-gray-50') . '">' . $total_halaman . '</a>';
                }

                // Tombol "Next"
                if ($halaman_saat_ini < $total_halaman) {
                    echo '<a href="?halaman=' . ($halaman_saat_ini + 1) . $query_string . '" class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50">';
                    echo '    <span class="sr-only">Next</span>';
                    echo '    <svg class="h-5 w-5" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">';
                    echo '        <path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clip-rule="evenodd" />';
                    echo '    </svg>';
                    echo '</a>';
                }
                ?>
            </nav>
        </div>

        <div class="mt-6 text-center">
            <a href="admin_view.php" class="text-blue-500 hover:underline">Kembali ke Halaman Admin</a>
        </div>
    </div>
</body>

</html>