<?php
session_start();
require_once "../../config.php";
requireRole("admin");
$conn = connectDB();

$error = "";
$success = "";

// Clear import errors
if (isset($_GET["clear_import_errors"])) {
    unset($_SESSION["import_errors"]);
    if (
        !empty($_SERVER["HTTP_X_REQUESTED_WITH"]) &&
        strtolower($_SERVER["HTTP_X_REQUESTED_WITH"]) == "xmlhttprequest"
    ) {
        echo json_encode(["success" => true]);
        exit();
    }
    header("Location: " . strtok($_SERVER["REQUEST_URI"], "?"));
    exit();
}

// Tambah peserta baru
if (
    $_SERVER["REQUEST_METHOD"] == "POST" &&
    isset($_POST["action"]) &&
    $_POST["action"] == "add"
) {
    $nama_peserta = sanitizeInput(strtoupper($_POST["nama_peserta"]));
    $domisili = sanitizeInput($_POST["domisili"]);
    $npsn = sanitizeInput(strtoupper($_POST["npsn"]));

    $stmt = $conn->prepare(
        "SELECT id FROM peserta_terdaftar WHERE Nama_Peserta = ? AND NPSN = ? AND domisili = ?"
    );
    $stmt->bind_param("sss", $nama_peserta, $npsn, $domisili);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        $error = "Data peserta sudah ada!";
    } else {
        $stmt = $conn->prepare(
            "INSERT INTO peserta_terdaftar (Nama_Peserta, domisili, NPSN) VALUES (?, ?, ?)"
        );
        $stmt->bind_param("sss", $nama_peserta, $domisili, $npsn);
        if ($stmt->execute()) {
            $success = "Data peserta berhasil ditambahkan!";
        } else {
            $error = "Gagal menambahkan data.";
        }
    }
}

// Delete peserta
if (
    $_SERVER["REQUEST_METHOD"] == "POST" &&
    isset($_POST["action"]) &&
    $_POST["action"] == "delete"
) {
    if (isset($_POST["id"])) {
        $id = (int) $_POST["id"]; // Get the ID from the form
        $stmt = $conn->prepare("DELETE FROM peserta_terdaftar WHERE id = ?");
        $stmt->bind_param("i", $id);
        if ($stmt->execute()) {
            $success = "Data peserta berhasil dihapus!";
        } else {
            $error = "Gagal menghapus data.";
        }
    } else {
        $error = "ID tidak ditemukan."; // Add this error message if ID is not set
    }
}

// Delete all data
if (
    $_SERVER["REQUEST_METHOD"] == "POST" &&
    isset($_POST["action"]) &&
    $_POST["action"] == "delete_all"
) {
    $stmt = $conn->prepare("DELETE FROM peserta_terdaftar");
    if ($stmt->execute()) {
        $success = "Semua data peserta berhasil dihapus!";
    } else {
        $error = "Gagal menghapus semua data.";
    }
}

if (
    $_SERVER["REQUEST_METHOD"] == "POST" &&
    isset($_POST["action"]) &&
    $_POST["action"] == "import"
) {
    $file = $_FILES["csv_file"]["tmp_name"];
    $ext = strtolower(
        pathinfo($_FILES["csv_file"]["name"], PATHINFO_EXTENSION)
    );
    $allowed_mime_csv = ["text/csv", "text/plain", "application/csv"];

    if (!in_array($_FILES["csv_file"]["type"], $allowed_mime_csv)) {
        $error =
            "Format file tidak didukung! Harap upload file dengan ekstensi .csv.";
    } elseif ($ext === "csv") {
        $handle = fopen($file, "r");
        if (!$handle) {
            $error = "Gagal membuka file CSV";
        } else {
            $log_errors = [];
            $berhasil = $gagal = $duplikat = 0;
            while (($data = fgetcsv($handle, 1000, ";")) !== false) {
                if ($data[0] === "Nama_Peserta") {
                    continue;
                } // skip header
                if (count($data) < 3) {
                    $gagal++;
                    $log_errors[] =
                        "Baris " .
                        ($berhasil + $gagal + $duplikat) .
                        ": Data tidak lengkap";
                    continue;
                }
                $nama_peserta = strtoupper(trim($data[0]));
                $npsn = strtoupper(trim($data[1]));
                $domisili = strtolower(trim($data[2]));

                if (!in_array($domisili, ["kabupaten semarang", "kabupaten demak", "kota salatiga"])) {
                    $gagal++;
                    $log_errors[] =
                        "Baris " .
                        ($berhasil + $gagal + $duplikat) .
                        ": Domisili tidak valid";
                    continue;
                }

                $stmt = $conn->prepare(
                    "SELECT id FROM peserta_terdaftar WHERE Nama_Peserta = ? AND NPSN = ? AND domisili = ?"
                );
                $stmt->bind_param("sss", $nama_peserta, $npsn, $domisili);
                $stmt->execute();
                $result = $stmt->get_result();

                if ($result->num_rows > 0) {
                    $duplikat++;
                } else {
                    $stmt = $conn->prepare(
                        "INSERT INTO peserta_terdaftar (Nama_Peserta, NPSN, domisili) VALUES (?, ?, ?)"
                    );
                    $stmt->bind_param("sss", $nama_peserta, $npsn, $domisili);
                    if ($stmt->execute()) {
                        $berhasil++;
                    } else {
                        $gagal++;
                        $log_errors[] =
                            "Baris " .
                            ($berhasil + $gagal + $duplikat) .
                            ": Gagal menyimpan data";
                    }
                }
            }
            fclose($handle);
            if ($berhasil > 0) {
                $success = "$berhasil data berhasil diimpor.";
                if ($duplikat > 0) {
                    $success .= " $duplikat duplikat dilewati.";
                }
                if ($gagal > 0) {
                    $success .= " $gagal gagal diproses.";
                }
            } else {
                $error = "Tidak ada data yang berhasil diimpor.";
            }
            if (!empty($log_errors)) {
                $_SESSION["import_errors"] = $log_errors;
            }
        }
    } else {
        $error = "Hanya file CSV yang diperbolehkan.";
    }
}

// Filter dan Pagination
$domisiliFilter = isset($_GET["filter_domisili"])
    ? sanitizeInput($_GET["filter_domisili"])
    : "";
$searchTerm = isset($_GET["search"]) ? sanitizeInput($_GET["search"]) : "";
$page = isset($_GET["page"]) ? (int) $_GET["page"] : 1;
$records_per_page = 100;
$offset = ($page - 1) * $records_per_page;

$where_conditions = [];
if ($domisiliFilter) {
    $where_conditions[] = "domisili = '$domisiliFilter'";
}
if ($searchTerm) {
    $where_conditions[] = "(Nama_Peserta LIKE '%$searchTerm%' OR NPSN LIKE '%$searchTerm%')";
}
$where_clause = !empty($where_conditions)
    ? " WHERE " . implode(" AND ", $where_conditions)
    : "";

$count_sql = "SELECT COUNT(*) as total FROM peserta_terdaftar" . $where_clause;
$total_rows = $conn->query($count_sql)->fetch_assoc()["total"];
$total_pages = ceil($total_rows / $records_per_page);

$sql = "SELECT id, Nama_Peserta, NPSN, domisili, created_at FROM peserta_terdaftar" . $where_clause . " ORDER BY created_at ASC LIMIT $offset, $records_per_page";
$result = $conn->query($sql);
?>


<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="shortcut icon" href="../../../assets/logoFLS3N.png" type="image/x-icon">
    <title>Kelola Peserta - Sistem FLS3N</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        .pagination {
            margin-top: 20px;
        }
        .highlight {
            background: rgba(255, 255, 0, 0.2);
        }
    </style>
</head>
<body>
    <?php include '../sidebar.php'; ?>
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">Kelola Peserta</h1>
                    <div>
                        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addPesertaModal">
                            <i class="fas fa-plus"></i> Tambah Peserta
                        </button>
                        <button type="button" class="btn btn-danger ms-2" data-bs-toggle="modal" data-bs-target="#deleteAllModal">
                            <i class="fas fa-trash"></i> Hapus Semua Data
                        </button>
                        <button type="button" class="btn btn-success ms-2" data-bs-toggle="modal" data-bs-target="#importPesertaModal">
                            <i class="fas fa-file-import"></i> Import Data
                        </button>
                    </div>
                </div>

                <?php if (!empty($error)): ?>
                    <div class="alert alert-danger"><?php echo $error; ?></div>
                <?php endif; ?>

                <?php if (!empty($success)): ?>
                    <div class="alert alert-success"><?php echo $success; ?></div>
                <?php endif; ?>

                <!-- Filter dan Pencarian -->
                <div class="card mb-4">
                    <div class="card-body">
                        <form action="" method="get" class="row g-3">
                            <div class="col-md-4">
                                <label for="filter_domisili" class="form-label">Filter Domisili</label>
                                <select class="form-select" id="filter_domisili" name="filter_domisili">
                                    <option value="">Semua Domisili</option>
                                    <option value="kabupaten semarang" <?php echo $domisiliFilter ==
                                    "kabupaten semarang"
                                        ? "selected"
                                        : ""; ?>>Kabupaten Semarang</option>

                                    <option value="kabupaten demak" <?php echo $domisiliFilter ==
                                    "kabupaten demak"
                                        ? "selected"
                                        : ""; ?>>Kabupaten Demak</option>

                                    <option value="kota salatiga" <?php echo $domisiliFilter ==
                                    "kota salatiga"
                                        ? "selected"
                                        : ""; ?>>Kota Salatiga</option>

                                </select>
                            </div>
                            <div class="col-md-6">
                                <label for="search" class="form-label">Cari Peserta</label>
                                <input type="text" class="form-control" id="search" name="search" value="<?php echo htmlspecialchars(
                                    $searchTerm
                                ); ?>" placeholder="Cari nama peserta atau NPSN...">
                            </div>
                            <div class="col-md-2 d-flex align-items-end">
                                <button type="submit" class="btn btn-primary w-100">
                                    <i class="fas fa-search"></i> Cari
                                </button>
                            </div>
                        </form>
                    </div>
                </div>

                <div class="card">
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-striped table-hover">
                                <thead>
                                    <tr>
                                        <th>Nama Peserta</th>
                                        <th>NPSN</th>
                                        <th>Domisili</th>
                                        <th>Tgl Dibuat</th>
                                        <th>Aksi</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php // Query untuk mengambil data tanpa ID
                                    if ($result = $conn->query($sql)) {
                                        if ($result->num_rows > 0) {
                                            while (
                                                $row = $result->fetch_assoc()
                                            ) {
                                                echo "<tr>";
                                                echo "<td>" .
                                                    $row["Nama_Peserta"] .
                                                    "</td>";
                                                echo "<td>" .
                                                    $row["NPSN"] .
                                                    "</td>";
                                                echo "<td>" .
                                                    ucfirst($row["domisili"]) .
                                                    "</td>";
                                                echo "<td>" .
                                                    date(
                                                        "d-m-Y H:i",
                                                        strtotime(
                                                            $row["created_at"]
                                                        )
                                                    ) .
                                                    "</td>";
                                                echo "<td>";
                                                echo "<button type='button' class='btn btn-sm btn-danger' data-bs-toggle='modal' data-bs-target='#deletePesertaModal' data-id='" .
                                                    $row["id"] .
                                                    "' data-nama='" .
                                                    $row["Nama_Peserta"] .
                                                    "'><i class='fas fa-trash'></i></button>";
                                                echo "</td>";
                                                echo "</tr>";
                                            }
                                        } else {
                                            echo "<tr><td colspan='5' class='text-center'>Tidak ada data peserta</td></tr>";
                                        }
                                    } else {
                                        echo "Error: " . $conn->error; // Add this for debugging query errors
                                    } ?>
                                </tbody>
                            </table>
                        </div>

                        <!-- Pagination -->
                        <?php if ($total_pages > 1): ?>
                        <nav aria-label="Page navigation">
                            <ul class="pagination justify-content-center">
                                <li class="page-item <?php echo $current_page <=
                                1
                                    ? "disabled"
                                    : ""; ?>">
                                    <a class="page-link" href="?page=<?php
                                    echo $current_page - 1;
                                    echo !empty($domisiliFilter)
                                        ? "&filter_domisili=" . $domisiliFilter
                                        : "";
                                    echo !empty($searchTerm)
                                        ? "&search=" . urlencode($searchTerm)
                                        : "";
                                    ?>" aria-label="Previous">
                                        <span aria-hidden="true">&laquo;</span>
                                    </a>
                                </li>

                                <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                                <li class="page-item <?php echo $current_page ==
                                $i
                                    ? "active"
                                    : ""; ?>">
                                    <a class="page-link" href="?page=<?php
                                    echo $i;
                                    echo !empty($domisiliFilter)
                                        ? "&filter_domisili=" . $domisiliFilter
                                        : "";
                                    echo !empty($searchTerm)
                                        ? "&search=" . urlencode($searchTerm)
                                        : "";
                                    ?>">
                                        <?php echo $i; ?>
                                    </a>
                                </li>
                                <?php endfor; ?>

                                <li class="page-item <?php echo $current_page >=
                                $total_pages
                                    ? "disabled"
                                    : ""; ?>">
                                    <a class="page-link" href="?page=<?php
                                    echo $current_page + 1;
                                    echo !empty($domisiliFilter)
                                        ? "&filter_domisili=" . $domisiliFilter
                                        : "";
                                    echo !empty($searchTerm)
                                        ? "&search=" . urlencode($searchTerm)
                                        : "";
                                    ?>" aria-label="Next">
                                        <span aria-hidden="true">&raquo;</span>
                                    </a>
                                </li>
                            </ul>
                        </nav>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- Modal Hapus Peserta -->
    <div class="modal fade" id="deletePesertaModal" tabindex="-1" aria-labelledby="deletePesertaModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="deletePesertaModalLabel">Konfirmasi Hapus</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>Apakah Anda yakin ingin menghapus data peserta <span id="delete-nama" class="fw-bold"></span>?</p>
                    <p class="text-danger mb-0">Perhatian: Tindakan ini tidak dapat dibatalkan.</p>
                </div>
                <div class="modal-footer">
                    <form method="post" action="">
                        <input type="hidden" name="action" value="delete">
                        <input type="hidden" name="id" id="delete-id"> <!-- The ID will be inserted here -->
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                        <button type="submit" class="btn btn-danger">Hapus</button>
                    </form>
                </div>
            </div>
        </div>
    </div>



    <!-- Modal Tambah Peserta -->
    <div class="modal fade" id="addPesertaModal" tabindex="-1" aria-labelledby="addPesertaModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addPesertaModalLabel">Tambah Data Peserta</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="post" action="">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="add">
                        <div class="mb-3">
                            <label for="nama_peserta" class="form-label">Nama Peserta</label>
                            <input type="text" class="form-control" id="nama_peserta" name="nama_peserta" required
                                placeholder="MASUKKAN NAMA PESERTA"
                                style="text-transform: uppercase;"
                                oninput="this.value = this.value.toUpperCase()">
                            <small class="text-muted">Nama peserta harus huruf kapital semua</small>
                        </div>
                        <div class="mb-3">
                            <label for="npsn" class="form-label">NPSN Sekolah</label>
                            <input type="text" class="form-control" id="npsn" name="npsn" required
                                placeholder="MASUKKAN NPSN SEKOLAH"
                                style="text-transform: uppercase;"
                                oninput="this.value = this.value.toUpperCase()">
                            <small class="text-muted">NPSN sekolah harus angka. Jika PKBM/Non Formal, isi dengan PKBM</small>
                        </div>
                        <div class="mb-3">
                            <label for="domisili" class="form-label">Domisili</label>
                            <select class="form-select" id="domisili" name="domisili" required>
                                <option value="">Pilih Domisili</option>
                                <option value="kabupaten semarang">Kabupaten Semarang</option>
                                <option value="kabupaten demak">Kabupaten Demak</option>
                                <option value="kota salatiga">Kota Salatiga</option>
                            </select>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                        <button type="submit" class="btn btn-primary">Simpan</button>
                    </div>
                </form>
            </div>
        </div>

    <!-- Modal Import Data Peserta -->
    <div class="modal fade" id="importPesertaModal" tabindex="-1" aria-labelledby="importPesertaModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="importPesertaModalLabel">Import Data Peserta</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="post" action="" enctype="multipart/form-data">
                    <div class="modal-body">
                        <div class="mb-3">
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <label for="csv_file" class="form-label mb-0">File CSV</label>
                                <a href="pesertaterdaftar.csv" download="pesertaterdaftar.csv" class="btn btn-primary">
                                    <i class="fas fa-download"></i> Download Template
                                </a>
                            </div>
                            <input type="file" class="form-control" id="csv_file" name="csv_file" accept=".csv" required>
                            <small class="text-muted">Upload file dengan format .csv</small>
                        </div>
                        <div class="row mb-3">
                            <div class="col-md-12">
                                <div class="alert alert-info">
                                    <h6 class="mb-2"><i class="fas fa-info-circle me-2"></i>Petunjuk Import Data</h6>
                                    <p class="mb-1">Format data yang dibutuhkan:</p>
                                    <ol>
                                        <li>Kolom <strong>Nama_Peserta</strong> - Nama lengkap peserta (huruf kapital)</li>
                                        <li>Kolom <strong>NPSN</strong> - NPSN sekolah (huruf kapital)</li>
                                        <li>Kolom <strong>Domisili</strong> - Berisi "kabupaten semarang", "kabupaten demak", atau "kota salatiga"</li>
                                    </ol>
                                    <p class="mb-0">Pastikan semua kolom telah diisi dengan benar sebelum melakukan import.</p>
                                    <p class="mb-0">Download template untuk format yang sesuai.</p>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                        <button type="submit" class="btn btn-primary" name="action" value="import">
                            <i class="fas fa-file-import me-1"></i> Import Data
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>


    <!-- Modal Hapus Semua Data -->
    <div class="modal fade" id="deleteAllModal" tabindex="-1" aria-labelledby="deleteAllModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="deleteAllModalLabel">Konfirmasi Hapus Semua Data</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>Apakah Anda yakin ingin menghapus semua data peserta?</p>
                    <p class="text-danger mb-0">Perhatian: Tindakan ini tidak dapat dibatalkan.</p>
                </div>
                <div class="modal-footer">
                    <form method="post" action="">
                        <input type="hidden" name="action" value="delete_all">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                        <button type="submit" class="btn btn-danger">Hapus Semua Data</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
    <script>
        // JavaScript to pass data to modal when "Delete" button is clicked
        document.getElementById('deletePesertaModal').addEventListener('show.bs.modal', function (event) {
            var button = event.relatedTarget; // Button that triggered the modal
            var id = button.getAttribute('data-id');  // Get the ID
            var nama = button.getAttribute('data-nama'); // Get the name

            var modalIdField = document.getElementById('delete-id'); // ID input field in the modal
            var modalNamaField = document.getElementById('delete-nama'); // Name field in the modal

            // Set the modal fields with the data from the button
            modalIdField.value = id;
            modalNamaField.textContent = nama;
        });




        // Script untuk menghapus riwayat error
        function clearImportErrors() {
            // Kirim request AJAX untuk menghapus error dari session
            fetch('?clear_import_errors=1')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // Sembunyikan alert error
                        document.querySelector('#importPesertaModal .alert-warning').style.display = 'none';
                    }
                });
        }

        // Auto-hide alerts setelah 5 detik
        document.addEventListener('DOMContentLoaded', function() {
            // Target semua alert
            const alerts = document.querySelectorAll('.alert-success, .alert-danger');

            // Set timeout untuk masing-masing alert
            alerts.forEach(alert => {
                setTimeout(() => {
                    // Fade out
                    alert.style.transition = 'opacity 1s';
                    alert.style.opacity = '0';

                    // Remove setelah transisi selesai
                    setTimeout(() => {
                        alert.remove();
                    }, 1000);
                }, 5000);
            });
        });
    </script>

    <?php include '../sidebar-footer.php'; ?>

<?php $conn->close(); ?>
