<?php
// admin_peserta_kabupaten_2.php - Peserta Kabupaten Demak
require_once '../../config.php';
requireRole('admin');

$conn = connectDB();
$error = '';
$success = '';


// Proses hapus semua data
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action']) && $_POST['action'] == 'deleteAll') {
    // Konfirmasi dengan password admin sebagai verifikasi
    $admin_password = sanitizeInput($_POST['admin_password']);
    
    // Verifikasi password admin (sesuaikan dengan metode autentikasi yang digunakan)
    $stmt = $conn->prepare("SELECT password FROM users WHERE username = ? AND role = 'admin'");
    $stmt->bind_param("s", $_SESSION['username']);
    $stmt->execute();
    $result = $stmt->get_result();
    $user = $result->fetch_assoc();
    
    if ($user && password_verify($admin_password, $user['password'])) {
        // Hapus semua penilaian terkait terlebih dahulu
        $stmt = $conn->prepare("DELETE FROM penilaian WHERE domisili = ?");
        $stmt->bind_param("s", $domisili);
        $stmt->execute();
        
        // Hapus semua peserta
        $stmt = $conn->prepare("TRUNCATE TABLE domisilikabupaten2");
        if ($stmt->execute()) {
            $success = "Semua data peserta Kabupaten Demak berhasil dihapus!";
        } else {
            $error = "Gagal menghapus semua data: " . $conn->error;
        }
    } else {
        $error = "Password admin tidak valid!";
    }
}

// Proses ekspor data ke Excel
if (isset($_GET['export']) && $_GET['export'] == 'excel') {
    $domisili = 'kabupaten demak';
    
    // Query untuk mengambil semua data peserta
    $sql = "SELECT p.NISN, p.Nama_Peserta, p.TTL, p.Email, p.Nama_Sekolah, p.NPSN, p.Jenis_Kelamin, c.Bidang_Lomba, 
            p.Foto_Peserta, p.Karya, p.Tanggal_Daftar 
            FROM domisilikabupaten2 p 
            LEFT JOIN cabang_lomba c ON p.ID_Cabang_Lomba = c.ID 
            ORDER BY p.Nama_Peserta";
            
    $result = $conn->query($sql);
    
    if ($result) {
        // Set header untuk download file Excel
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="Data_Peserta_Kab_Demak_' . date('Y-m-d') . '.xls"');
        header('Cache-Control: max-age=0');
        
        // Mulai output Excel
        echo '<!DOCTYPE html>';
        echo '<html>';
        echo '<head>';
        echo '<meta charset="UTF-8">';
        echo '<title>Data Peserta Kabupaten Demak</title>';
        echo '</head>';
        echo '<body>';
        echo '<table border="1">';
        
        // Header tabel
        echo '<tr>';
        echo '<th>No</th>';
        echo '<th>NISN</th>';
        echo '<th>Nama Peserta</th>';
        echo '<th>TTL</th>';
        echo '<th>Email</th>';
        echo '<th>Sekolah</th>';
        echo '<th>NPSN</th>';
        echo '<th>Jenis Kelamin</th>';
        echo '<th>Cabang Lomba</th>';
        echo '<th>URL Foto</th>';
        echo '<th>URL Karya</th>';
        echo '<th>Tanggal Daftar</th>';
        echo '</tr>';
        
        // Data peserta
        $no = 1;
        while ($row = $result->fetch_assoc()) {
            echo '<tr>';
            echo '<td>' . $no++ . '</td>';
            echo '<td>' . $row['NISN'] . '</td>';
            echo '<td>' . $row['Nama_Peserta'] . '</td>';
            echo '<td>' . (isset($row['TTL']) ? $row['TTL'] : '-') . '</td>';
            echo '<td>' . (isset($row['Email']) ? $row['Email'] : '-') . '</td>';
            echo '<td>' . $row['Nama_Sekolah'] . '</td>';
            echo '<td>' . (isset($row['NPSN']) ? $row['NPSN'] : '-') . '</td>';
            echo '<td>' . $row['Jenis_Kelamin'] . '</td>';
            echo '<td>' . $row['Bidang_Lomba'] . '</td>';
            echo '<td>' . $row['Foto_Peserta'] . '</td>';
            echo '<td>' . $row['Karya'] . '</td>';
            echo '<td>' . $row['Tanggal_Daftar'] . '</td>';
            echo '</tr>';
        }
        
        echo '</table>';
        echo '</body>';
        echo '</html>';
        
        exit;
    } else {
        $error = "Gagal mengekspor data: " . $conn->error;
    }
}

// Proses tambah peserta baru
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action']) && $_POST['action'] == 'add') {
    $nisn = sanitizeInput($_POST['nisn']);
    $nama = sanitizeInput($_POST['nama']);
    $sekolah = sanitizeInput($_POST['sekolah']);
    $npsn = sanitizeInput($_POST['npsn']);
    $ttl = sanitizeInput($_POST['ttl']);
    $email = sanitizeInput($_POST['email']);
    $jenis_kelamin = sanitizeInput($_POST['jenis_kelamin']);
    $id_cabang_lomba = $_POST['id_cabang_lomba'];
    $foto_peserta = sanitizeInput($_POST['foto_peserta']); // Diubah menjadi link Google Drive
    $karya = sanitizeInput($_POST['karya']); // Link Google Drive
    
    if(empty($error)) {
        // Cek NISN sudah ada atau belum
        $stmt = $conn->prepare("SELECT NISN FROM domisilikabupaten2 WHERE NISN = ?");
        $stmt->bind_param("s", $nisn);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows > 0) {
            $error = "NISN sudah terdaftar!";
        } else {
            // Insert peserta baru
            $stmt = $conn->prepare("INSERT INTO domisilikabupaten2 (NISN, Nama_Peserta, Nama_Sekolah, NPSN, TTL, Email, Jenis_Kelamin, Foto_Peserta, Karya, ID_Cabang_Lomba) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("sssssssssi", $nisn, $nama, $sekolah, $npsn, $ttl, $email, $jenis_kelamin, $foto_peserta, $karya, $id_cabang_lomba);
            
            if ($stmt->execute()) {
                $success = "Peserta berhasil ditambahkan!";
            } else {
                $error = "Gagal menambahkan peserta: " . $conn->error;
            }
        }
    }
}

// Proses edit peserta
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action']) && $_POST['action'] == 'edit') {
    $nisn = sanitizeInput($_POST['nisn']);
    $nama = sanitizeInput($_POST['nama']);
    $sekolah = sanitizeInput($_POST['sekolah']);
    $npsn = sanitizeInput($_POST['npsn']);
    $ttl = sanitizeInput($_POST['ttl']);
    $email = sanitizeInput($_POST['email']);
    $jenis_kelamin = sanitizeInput($_POST['jenis_kelamin']);
    $id_cabang_lomba = $_POST['id_cabang_lomba'];
    $foto_peserta = sanitizeInput($_POST['foto_peserta']); // Link Google Drive
    $karya = sanitizeInput($_POST['karya']); // Link Google Drive
    
    if(empty($error)) {
        // Update peserta
        $stmt = $conn->prepare("UPDATE domisilikabupaten2 SET Nama_Peserta = ?, Nama_Sekolah = ?, NPSN = ?, TTL = ?, Email = ?, Jenis_Kelamin = ?, Foto_Peserta = ?, Karya = ?, ID_Cabang_Lomba = ? WHERE NISN = ?");
        $stmt->bind_param("ssssssssss", $nama, $sekolah, $npsn, $ttl, $email, $jenis_kelamin, $foto_peserta, $karya, $id_cabang_lomba, $nisn);
        
        if ($stmt->execute()) {
            $success = "Peserta berhasil diperbarui!";
        } else {
            $error = "Gagal memperbarui peserta: " . $conn->error;
        }
    }
}

// Proses hapus peserta
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action']) && $_POST['action'] == 'delete') {
    $nisn = sanitizeInput($_POST['nisn']);
    
    // Hapus penilaian terkait terlebih dahulu
    $stmt = $conn->prepare("DELETE FROM penilaian WHERE nisn_peserta = ? AND domisili = 'kabupaten'");
    $stmt->bind_param("s", $nisn);
    $stmt->execute();
    
    // Hapus peserta
    $stmt = $conn->prepare("DELETE FROM domisilikabupaten2 WHERE NISN = ?");
    $stmt->bind_param("s", $nisn);
    
    if ($stmt->execute() && $stmt->affected_rows > 0) {
        $success = "Peserta berhasil dihapus!";
    } else {
        $error = "Gagal menghapus peserta: " . $conn->error;
    }
}
?>

<!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 Kabupaten Demak - Sistem Penilaian Karya Siswa</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>
        .content {
            padding: 20px;
        }
        .table-responsive {
            overflow-x: auto;
        }
        .table th, .table td {
            white-space: nowrap;
        }
        .email-cell {
            max-width: 200px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
    </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">
            <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 Kabupaten Demak</h1>
    <div>
        <a href="?export=excel" class="btn btn-success me-2">
            <i class="fas fa-file-excel me-1"></i> Ekspor Excel
        </a>
        <button type="button" class="btn btn-danger me-2" data-bs-toggle="modal" data-bs-target="#deleteAllModal">
            <i class="fas fa-trash-alt me-1"></i> Hapus Semua Data
        </button>
        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addPesertaModal">
            <i class="fas fa-plus"></i> Tambah Peserta
        </button>
    </div>
</div>

<!-- Modal Konfirmasi 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 bg-danger text-white">
                <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>
            <form method="post" action="">
                <div class="modal-body">
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        <strong>PERHATIAN!</strong> Tindakan ini akan menghapus SEMUA data peserta Kabupaten Demak dan tidak dapat dibatalkan!
                    </div>
                    <p>Masukkan password admin Anda untuk konfirmasi:</p>
                    <input type="hidden" name="action" value="deleteAll">
                    <div class="mb-3">
                        <input type="password" class="form-control" name="admin_password" required placeholder="Password admin">
                    </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-danger">Hapus Semua Data</button>
                </div>
            </form>
        </div>
    </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; ?>
                
                <div class="card">
                    <div class="card-body">
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <div class="input-group">
                                    <input type="text" class="form-control" id="searchInput" placeholder="Cari peserta...">
                                    <button class="btn btn-outline-secondary" type="button">
                                        <i class="fas fa-search"></i>
                                    </button>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <select class="form-select" id="filterCabang">
                                    <option value="">Semua Cabang Lomba</option>
                                    <?php
                                    $sql = "SELECT ID, Bidang_Lomba FROM cabang_lomba ORDER BY Bidang_Lomba";
                                    $result = $conn->query($sql);
                                    
                                    if ($result->num_rows > 0) {
                                        while($row = $result->fetch_assoc()) {
                                            echo "<option value='" . $row["ID"] . "'>" . $row["Bidang_Lomba"] . "</option>";
                                        }
                                    }
                                    ?>
                                </select>
                            </div>
                        </div>
                        
                        <div class="table-responsive">
                            <table class="table table-striped table-hover" id="pesertaTable">
                                <thead>
                                    <tr>
                                        <th>NISN</th>
                                        <th>Foto Profil</th>
                                        <th>Nama Peserta</th>
                                        <th>Tempat, Tanggal Lahir</th>
                                        <th>Email</th>
                                        <th>Sekolah</th>
                                        <th>NPSN</th>
                                        <th>Jenis Kelamin</th>
                                        <th>Cabang Lomba</th>
                                        <th>Karya</th>
                                        <th>Aksi</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    $sql = "SELECT dk.*, cl.Bidang_Lomba 
                                           FROM domisilikabupaten2 dk
                                           LEFT JOIN cabang_lomba cl ON dk.ID_Cabang_Lomba = cl.ID
                                           ORDER BY dk.Nama_Peserta";
                                    $result = $conn->query($sql);
                                    
                                    if ($result->num_rows > 0) {
                                        while($row = $result->fetch_assoc()) {
                                            echo "<tr data-cabang='" . $row["ID_Cabang_Lomba"] . "'>";
                                            echo "<td>" . $row["NISN"] . "</td>";
                                            echo "<td><a href='" . $row["Foto_Peserta"] . "' target='_blank' class='btn btn-sm btn-outline-primary'><i class='fas fa-image me-1'></i> Lihat Foto</a></td>";
                                            echo "<td>" . $row["Nama_Peserta"] . "</td>";
                                            echo "<td>" . (isset($row["TTL"]) ? $row["TTL"] : "-") . "</td>";
                                            echo "<td class='email-cell'>" . (isset($row["Email"]) ? $row["Email"] : "-") . "</td>";
                                            echo "<td>" . $row["Nama_Sekolah"] . "</td>";
                                            echo "<td>" . (isset($row["NPSN"]) ? $row["NPSN"] : "-") . "</td>";
                                            echo "<td>" . $row["Jenis_Kelamin"] . "</td>";
                                            echo "<td>" . $row["Bidang_Lomba"] . "</td>";
                                            echo "<td><a href='" . $row["Karya"] . "' target='_blank' class='btn btn-sm btn-outline-primary'><i class='fas fa-eye me-1'></i> Lihat</a></td>";
                                            echo "<td>";
                                            echo "<button type='button' class='btn btn-sm btn-info me-1' data-bs-toggle='modal' data-bs-target='#editPesertaModal' 
                                                  data-nisn='" . $row["NISN"] . "'
                                                  data-nama='" . $row["Nama_Peserta"] . "'
                                                  data-sekolah='" . $row["Nama_Sekolah"] . "'
                                                  data-npsn='" . (isset($row["NPSN"]) ? $row["NPSN"] : "") . "'
                                                  data-ttl='" . (isset($row["TTL"]) ? $row["TTL"] : "") . "'
                                                  data-email='" . (isset($row["Email"]) ? $row["Email"] : "") . "'
                                                  data-jk='" . $row["Jenis_Kelamin"] . "'
                                                  data-cabang='" . $row["ID_Cabang_Lomba"] . "'
                                                  data-foto='" . $row["Foto_Peserta"] . "'
                                                  data-karya='" . $row["Karya"] . "'>
                                                  <i class='fas fa-edit'></i></button>";
                                            echo "<button type='button' class='btn btn-sm btn-danger' data-bs-toggle='modal' data-bs-target='#deletePesertaModal' 
                                                  data-nisn='" . $row["NISN"] . "' 
                                                  data-nama='" . $row["Nama_Peserta"] . "'>
                                                  <i class='fas fa-trash'></i></button>";
                                            echo "</td>";
                                            echo "</tr>";
                                        }
                                    } else {
                                        echo "<tr><td colspan='11' class='text-center'>Tidak ada data peserta</td></tr>";
                                    }
                                    ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </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 modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addPesertaModalLabel">Tambah Peserta Kabupaten Demak</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="row mb-3">
                            <div class="col-md-6">
                                <label for="nisn" class="form-label">NISN</label>
                                <input type="text" class="form-control" id="nisn" name="nisn" required>
                            </div>
                            <div class="col-md-6">
                                <label for="nama" class="form-label">Nama Peserta</label>
                                <input type="text" class="form-control" id="nama" name="nama" required>
                            </div>
                        </div>
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="ttl" class="form-label">Tempat, Tanggal Lahir</label>
                                <input type="text" class="form-control" id="ttl" name="ttl" placeholder="Contoh: Jakarta, 31 Desember 2000" required>
                            </div>
                            <div class="col-md-6">
                                <label for="email" class="form-label">Email</label>
                                <input type="email" class="form-control" id="email" name="email" required>
                            </div>
                        </div>
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="sekolah" class="form-label">Asal Sekolah</label>
                                <input type="text" class="form-control" id="sekolah" name="sekolah" required>
                            </div>
                            <div class="col-md-6">
                                <label for="npsn" class="form-label">NPSN Sekolah</label>
                                <input type="text" class="form-control" id="npsn" name="npsn" required>
                            </div>
                        </div>
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="jenis_kelamin" class="form-label">Jenis Kelamin</label>
                                <select class="form-select" id="jenis_kelamin" name="jenis_kelamin" required>
                                    <option value="">Pilih Jenis Kelamin</option>
                                    <option value="Laki-laki">Laki-laki</option>
                                    <option value="Perempuan">Perempuan</option>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label for="id_cabang_lomba" class="form-label">Cabang Lomba</label>
                                <select class="form-select" id="id_cabang_lomba" name="id_cabang_lomba" required>
                                    <option value="">Pilih Cabang Lomba</option>
                                    <?php
                                    $sql = "SELECT ID, Bidang_Lomba FROM cabang_lomba ORDER BY Bidang_Lomba";
                                    $result = $conn->query($sql);
                                    
                                    if ($result->num_rows > 0) {
                                        while($row = $result->fetch_assoc()) {
                                            echo "<option value='" . $row["ID"] . "'>" . $row["Bidang_Lomba"] . "</option>";
                                        }
                                    }
                                    ?>
                                </select>
                            </div>
                        </div>
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="foto_peserta" class="form-label">Link Foto Peserta (Google Drive)</label>
                                <input type="url" class="form-control" id="foto_peserta" name="foto_peserta" required placeholder="https://drive.google.com/file/d/...">
                                <small class="text-muted">Pastikan link memiliki akses publik</small>
                            </div>
                            <div class="col-md-6">
                                <label for="karya" class="form-label">Link File Karya (Google Drive)</label>
                                <input type="url" class="form-control" id="karya" name="karya" required placeholder="https://drive.google.com/file/d/...">
                                <small class="text-muted">Pastikan link memiliki akses publik</small>
                            </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">Simpan</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <!-- Modal Edit Peserta -->
    <div class="modal fade" id="editPesertaModal" tabindex="-1" aria-labelledby="editPesertaModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editPesertaModalLabel">Edit Peserta Kabupaten Demak</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="edit">
                        <input type="hidden" name="nisn" id="edit-nisn">
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="edit-nama" class="form-label">Nama Peserta</label>
                                <input type="text" class="form-control" id="edit-nama" name="nama" required>
                            </div>
                            <div class="col-md-6">
                                <label for="edit-ttl" class="form-label">Tempat, Tanggal Lahir</label>
                                <input type="text" class="form-control" id="edit-ttl" name="ttl" required>
                            </div>
                        </div>
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="edit-email" class="form-label">Email</label>
                                <input type="email" class="form-control" id="edit-email" name="email" required>
                            </div>
                            <div class="col-md-6">
                                <label for="edit-jenis_kelamin" class="form-label">Jenis Kelamin</label>
                                <select class="form-select" id="edit-jenis_kelamin" name="jenis_kelamin" required>
                                    <option value="Laki-laki">Laki-laki</option>
                                    <option value="Perempuan">Perempuan</option>
                                </select>
                            </div>
                        </div>
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="edit-sekolah" class="form-label">Asal Sekolah</label>
                                <input type="text" class="form-control" id="edit-sekolah" name="sekolah" required>
                            </div>
                            <div class="col-md-6">
                                <label for="edit-npsn" class="form-label">NPSN Sekolah</label>
                                <input type="text" class="form-control" id="edit-npsn" name="npsn" required>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label for="edit-id_cabang_lomba" class="form-label">Cabang Lomba</label>
                            <select class="form-select" id="edit-id_cabang_lomba" name="id_cabang_lomba" required>
                                <option value="">Pilih Cabang Lomba</option>
                                <?php
                                $sql = "SELECT ID, Bidang_Lomba FROM cabang_lomba ORDER BY Bidang_Lomba";
                                $result = $conn->query($sql);
                                
                                if ($result->num_rows > 0) {
                                    while($row = $result->fetch_assoc()) {
                                        echo "<option value='" . $row["ID"] . "'>" . $row["Bidang_Lomba"] . "</option>";
                                    }
                                }
                                ?>
                            </select>
                        </div>
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="edit-foto_peserta" class="form-label">Link Foto Peserta (Google Drive)</label>
                                <input type="url" class="form-control" id="edit-foto_peserta" name="foto_peserta" required>
                                <small class="text-muted">Pastikan link memiliki akses publik</small>
                                <div class="mt-2">
                                    <a id="preview-foto-link" href="#" target="_blank" class="btn btn-sm btn-outline-primary">
                                        <i class="fas fa-image me-1"></i> Lihat Foto Saat Ini
                                    </a>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <label for="edit-karya" class="form-label">Link File Karya (Google Drive)</label>
                                <input type="url" class="form-control" id="edit-karya" name="karya" required>
                                <small class="text-muted">Pastikan link memiliki akses publik</small>
                                <div class="mt-2">
                                    <a id="preview-karya-link" href="#" target="_blank" class="btn btn-sm btn-outline-primary">
                                        <i class="fas fa-eye me-1"></i> Lihat Karya Saat Ini
                                    </a>
                                </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">Simpan Perubahan</button>
                    </div>
                </form>
            </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 peserta <span id="delete-peserta-nama"></span>?</p>
                    <p class="text-danger"><small>Perhatian: Semua data peserta termasuk penilaian juga akan dihapus.</small></p>
                </div>
                <div class="modal-footer">
                    <form method="post" action="">
                        <input type="hidden" name="action" value="delete">
                        <input type="hidden" name="nisn" id="delete-nisn">
                        <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>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Script untuk mengisi modal edit
        document.getElementById('editPesertaModal').addEventListener('show.bs.modal', function (event) {
            var button = event.relatedTarget;
            var nisn = button.getAttribute('data-nisn');
            var nama = button.getAttribute('data-nama');
            var sekolah = button.getAttribute('data-sekolah');
            var npsn = button.getAttribute('data-npsn');
            var ttl = button.getAttribute('data-ttl');
            var email = button.getAttribute('data-email');
            var jk = button.getAttribute('data-jk');
            var cabang = button.getAttribute('data-cabang');
            var foto = button.getAttribute('data-foto');
            var karya = button.getAttribute('data-karya');
            
            document.getElementById('edit-nisn').value = nisn;
            document.getElementById('edit-nama').value = nama;
            document.getElementById('edit-sekolah').value = sekolah;
            document.getElementById('edit-npsn').value = npsn;
            document.getElementById('edit-ttl').value = ttl;
            document.getElementById('edit-email').value = email;
            document.getElementById('edit-jenis_kelamin').value = jk;
            document.getElementById('edit-id_cabang_lomba').value = cabang;
            document.getElementById('edit-foto_peserta').value = foto;
            document.getElementById('edit-karya').value = karya;
            
            // Set preview links
            document.getElementById('preview-foto-link').href = foto;
            document.getElementById('preview-karya-link').href = karya;
        });
        
        // Script untuk mengisi modal hapus
        document.getElementById('deletePesertaModal').addEventListener('show.bs.modal', function (event) {
            var button = event.relatedTarget;
            var nisn = button.getAttribute('data-nisn');
            var nama = button.getAttribute('data-nama');
            
            document.getElementById('delete-nisn').value = nisn;
            document.getElementById('delete-peserta-nama').textContent = nama;
        });
        
        // Filter peserta berdasarkan cabang lomba
        document.getElementById('filterCabang').addEventListener('change', function() {
            var filter = this.value;
            var rows = document.querySelectorAll('#pesertaTable tbody tr');
            
            rows.forEach(function(row) {
                if (filter === '' || row.getAttribute('data-cabang') === filter) {
                    row.style.display = '';
                } else {
                    row.style.display = 'none';
                }
            });
        });
        
        // Pencarian peserta
        document.getElementById('searchInput').addEventListener('keyup', function() {
            var filter = this.value.toLowerCase();
            var rows = document.querySelectorAll('#pesertaTable tbody tr');
            
            rows.forEach(function(row) {
                var text = row.textContent.toLowerCase();
                if (text.indexOf(filter) > -1) {
                    row.style.display = '';
                } else {
                    row.style.display = 'none';
                }
            });
        });
    </script>
</body>
</html>

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