<?php
require_once '../../config.php';
session_start();

// Check if user is admin
if (!isset($_SESSION['username']) || $_SESSION['role'] !== 'admin') {
    header('Location: /fls3n2/admin/');
    exit;
}

$conn = connectDB();
$filter_status = isset($_GET['status']) ? $_GET['status'] : '';
$per_page = 10;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $per_page;

// Pesan untuk aksi
$success_message = '';
$error_message = '';

// Handle Upload/Import Excel
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file_import'])) {
    if ($_FILES['file_import']['error'] === UPLOAD_ERR_OK) {
        $file_tmp = $_FILES['file_import']['tmp_name'];
        $file_name = $_FILES['file_import']['name'];
        $file_ext = pathinfo($file_name, PATHINFO_EXTENSION);
        
        if (in_array($file_ext, ['csv', 'xls', 'xlsx'])) {
            try {
                if ($file_ext === 'csv') {
                    // Handle CSV
                    $row = 0;
                    $imported = 0;
                    if (($handle = fopen($file_tmp, 'r')) !== FALSE) {
                        while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
                            $row++;
                            if ($row == 1) continue; // Skip header
                            
                            $nama_sekolah = $conn->real_escape_string($data[0] ?? '');
                            $nama_peserta = $conn->real_escape_string($data[1] ?? '');
                            $npsn = $conn->real_escape_string($data[2] ?? '');
                            $kategori = $conn->real_escape_string($data[3] ?? '');
                            $kabupaten_kota = $conn->real_escape_string($data[4] ?? '');
                            $email = $conn->real_escape_string($data[5] ?? '');
                            $no_wa = $conn->real_escape_string($data[6] ?? '');
                            $link_bukti = $conn->real_escape_string($data[7] ?? '');
                            
                            if (!empty($nama_sekolah) && !empty($npsn)) {
                                $insert_sql = "INSERT INTO master_sekolah 
                                    (Nama_Sekolah, Nama_Peserta, NPSN, Kategori, Kabupaten_Kota, Email, No_WA, Link_Bukti_BPTI, Status, Tanggal_Daftar)
                                    VALUES ('$nama_sekolah', '$nama_peserta', '$npsn', '$kategori', '$kabupaten_kota', '$email', '$no_wa', '$link_bukti', 'memerlukan_validasi', NOW())
                                    ON DUPLICATE KEY UPDATE 
                                    Nama_Sekolah = '$nama_sekolah', Nama_Peserta = '$nama_peserta', Kategori = '$kategori', Link_Bukti_BPTI = '$link_bukti'";
                                
                                if ($conn->query($insert_sql)) {
                                    $imported++;
                                }
                            }
                        }
                        fclose($handle);
                        $success_message = "Import berhasil! $imported sekolah telah ditambahkan/diperbarui.";
                    }
                }
            } catch (Exception $e) {
                $error_message = "Error import: " . $e->getMessage();
            }
        } else {
            $error_message = "Format file tidak didukung. Gunakan CSV, XLS, atau XLSX.";
        }
    } else {
        $error_message = "Error upload file.";
    }
}

// Handle Export to Excel/CSV
if (isset($_GET['action']) && $_GET['action'] === 'export') {
    $sql_export = "SELECT Nama_Sekolah, Nama_Peserta, NPSN, Kategori, Kabupaten_Kota, Email, No_WA, Status, Tanggal_Daftar FROM master_sekolah ORDER BY Tanggal_Daftar DESC";
    $result_export = $conn->query($sql_export);
    
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="export_sekolah_' . date('Y-m-d_H-i-s') . '.csv"');
    
    $output = fopen('php://output', 'w');
    
    // Header CSV
    fputcsv($output, ['Nama Sekolah', 'Nama Peserta', 'NPSN', 'Kategori', 'Kabupaten/Kota', 'Email', 'No. WA', 'Status', 'Tanggal Daftar']);
    
    // Data
    while ($row = $result_export->fetch_assoc()) {
        fputcsv($output, [
            $row['Nama_Sekolah'],
            $row['Nama_Peserta'],
            $row['NPSN'],
            $row['Kategori'],
            $row['Kabupaten_Kota'],
            $row['Email'],
            $row['No_WA'],
            $row['Status'],
            $row['Tanggal_Daftar']
        ]);
    }
    
    fclose($output);
    exit;
}

// Handle Delete All Data
if (isset($_POST['action']) && $_POST['action'] === 'delete_all') {
    if ($_POST['confirm'] === 'yes') {
        // Verifikasi password admin
        $admin_password = isset($_POST['admin_password']) ? $_POST['admin_password'] : '';
        
        // Query untuk verify password
        $verify_sql = "SELECT password FROM users WHERE username = '" . $conn->real_escape_string($_SESSION['username']) . "' AND role = 'admin'";
        $verify_result = $conn->query($verify_sql);
        
        if ($verify_result && $verify_result->num_rows > 0) {
            $user = $verify_result->fetch_assoc();
            // Jika tersimpan sebagai plaintext atau gunakan password_verify
            if ($admin_password === $user['password'] || (function_exists('password_verify') && password_verify($admin_password, $user['password']))) {
                if ($conn->query("DELETE FROM master_sekolah")) {
                    $success_message = "Semua data sekolah telah dihapus!";
                } else {
                    $error_message = "Error menghapus data: " . $conn->error;
                }
            } else {
                $error_message = "Password admin tidak valid!";
            }
        } else {
            $error_message = "Verifikasi admin gagal!";
        }
    }
}

// Handle Add School Manually
if (isset($_POST['action']) && $_POST['action'] === 'add_school') {
    $nama_sekolah = $conn->real_escape_string($_POST['add_nama_sekolah'] ?? '');
    $nama_peserta = $conn->real_escape_string($_POST['add_nama_peserta'] ?? '');
    $npsn = $conn->real_escape_string($_POST['add_npsn'] ?? '');
    $kategori = $conn->real_escape_string($_POST['add_kategori'] ?? '');
    $kabupaten_kota = $conn->real_escape_string($_POST['add_kabupaten_kota'] ?? '');
    $email = $conn->real_escape_string($_POST['add_email'] ?? '');
    $no_wa = $conn->real_escape_string($_POST['add_no_wa'] ?? '');
    $link_bukti = $conn->real_escape_string($_POST['add_link_bukti'] ?? '');
    
    if (!empty($nama_sekolah) && !empty($npsn)) {
        $insert_sql = "INSERT INTO master_sekolah 
            (Nama_Sekolah, Nama_Peserta, NPSN, Kategori, Kabupaten_Kota, Email, No_WA, Link_Bukti_BPTI, Status, Tanggal_Daftar)
            VALUES ('$nama_sekolah', '$nama_peserta', '$npsn', '$kategori', '$kabupaten_kota', '$email', '$no_wa', '$link_bukti', 'memerlukan_validasi', NOW())";
        
        if ($conn->query($insert_sql)) {
            $success_message = "Sekolah berhasil ditambahkan!";
        } else {
            $error_message = "Error: " . $conn->error;
        }
    } else {
        $error_message = "Nama Sekolah dan NPSN harus diisi!";
    }
    
    header("Location: " . $_SERVER['PHP_SELF'] . (empty($filter_status) ? '' : "?status=$filter_status"));
    exit;
}

// Build query dengan filter status
$where = "WHERE 1=1";
if (!empty($filter_status)) {
    $where .= " AND Status = '" . $conn->real_escape_string($filter_status) . "'";
}

// Get total records
$count_result = $conn->query("SELECT COUNT(*) as total FROM master_sekolah $where");
$count_row = $count_result->fetch_assoc();
$total_records = $count_row['total'];
$total_pages = ceil($total_records / $per_page);

// Get schools
$sql = "SELECT * FROM master_sekolah $where ORDER BY Tanggal_Daftar DESC LIMIT $offset, $per_page";
$result = $conn->query($sql);

$schools = [];
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $schools[] = $row;
    }
}

// Handle actions
$action_message = '';
$action_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = isset($_POST['action']) ? $_POST['action'] : '';
    $school_id = isset($_POST['school_id']) ? (int)$_POST['school_id'] : 0;

    if ($action === 'validasi' && $school_id > 0) {
        $domisili = isset($_POST['domisili']) ? $_POST['domisili'] : '';
        
        // Validasi domisili
        $valid_domisili = ['kabupaten semarang', 'kabupaten demak', 'kota salatiga'];
        if (empty($domisili) || !in_array($domisili, $valid_domisili)) {
            $action_message = 'Domisili tidak valid!';
            $action_type = 'error';
        } else {
            // Get school data (Nama_Peserta, NPSN)
            $school_sql = "SELECT Nama_Peserta, NPSN FROM master_sekolah WHERE ID = $school_id";
            $school_result = $conn->query($school_sql);
            
            if ($school_result && $school_result->num_rows > 0) {
                $school_data = $school_result->fetch_assoc();
                $nama_peserta = $conn->real_escape_string($school_data['Nama_Peserta']);
                $npsn = $conn->real_escape_string($school_data['NPSN']);
                
                // Check if peserta already exists in peserta_terdaftar
                $check_sql = "SELECT id FROM peserta_terdaftar 
                             WHERE Nama_Peserta = '$nama_peserta' AND NPSN = '$npsn' AND domisili = '$domisili'";
                $check_result = $conn->query($check_sql);
                
                if ($check_result && $check_result->num_rows > 0) {
                    $action_message = 'Peserta sudah terdaftar di domisili ini!';
                    $action_type = 'warning';
                } else {
                    // Insert ke peserta_terdaftar
                    $insert_sql = "INSERT INTO peserta_terdaftar (Nama_Peserta, NPSN, domisili) 
                                   VALUES ('$nama_peserta', '$npsn', '$domisili')";
                    
                    if ($conn->query($insert_sql)) {
                        // Update master_sekolah status
                        $update_sql = "UPDATE master_sekolah 
                                       SET Status = 'tervalidasi', 
                                           Validasi_Oleh = '" . $conn->real_escape_string($_SESSION['username']) . "',
                                           Tanggal_Validasi = NOW()
                                       WHERE ID = $school_id";
                        
                        if ($conn->query($update_sql)) {
                            $action_message = 'Sekolah berhasil divalidasi dan peserta ditambahkan ke domisili: ' . ucfirst($domisili);
                            $action_type = 'success';
                        } else {
                            $action_message = 'Error updating sekolah status: ' . $conn->error;
                            $action_type = 'error';
                        }
                    } else {
                        $action_message = 'Error inserting peserta: ' . $conn->error;
                        $action_type = 'error';
                    }
                }
            } else {
                $action_message = 'Data sekolah tidak ditemukan!';
                $action_type = 'error';
            }
        }
    } elseif ($action === 'tolak' && $school_id > 0) {
        $alasan = isset($_POST['alasan']) ? $conn->real_escape_string($_POST['alasan']) : '';
        $update_sql = "UPDATE master_sekolah 
                       SET Status = 'ditolak', 
                           Keterangan_Penolakan = '$alasan',
                           Validasi_Oleh = '" . $conn->real_escape_string($_SESSION['username']) . "',
                           Tanggal_Validasi = NOW()
                       WHERE ID = $school_id";
        
        if ($conn->query($update_sql)) {
            $action_message = 'Sekolah berhasil ditolak!';
            $action_type = 'success';
        } else {
            $action_message = 'Error updating record: ' . $conn->error;
            $action_type = 'error';
        }
    }
    
    // Redirect untuk refresh halaman
    header("Location: " . $_SERVER['PHP_SELF'] . (empty($filter_status) ? '' : "?status=$filter_status"));
    exit;
}

$conn->close();
?>
<!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 Sekolah - Admin 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>
        .status-badge {
            padding: 5px 10px;
            border-radius: 4px;
            font-size: 0.85rem;
            font-weight: 600;
        }
        
        .status-memerlukan_validasi {
            background-color: #fff3cd;
            color: #856404;
        }
        
        .status-tervalidasi {
            background-color: #d4edda;
            color: #155724;
        }
        
        .status-ditolak {
            background-color: #f8d7da;
            color: #721c24;
        }

        .pagination {
            margin-top: 20px;
        }
    </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 Sekolah</h1>
                    <div>
                        <span class="badge bg-info">Total: <?php echo $total_records; ?> sekolah</span>
                    </div>
                </div>

                <!-- Action Buttons -->
                <div class="d-flex justify-content-end gap-2 flex-wrap mb-4">   
                    <a href="?action=export" class="btn btn-success" title="Export data sekolah ke CSV">
                        <i class="fas fa-file-excel me-1"></i> Ekspor Excel
                    </a>
                    <button type="button" class="btn btn-warning" data-bs-toggle="modal" data-bs-target="#addSchoolModal" title="Tambah sekolah secara manual">
                        <i class="fas fa-plus me-1"></i> Tambah Sekolah
                    </button>
                    <button type="button" class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#deleteAllModal" title="Hapus semua data sekolah">
                        <i class="fas fa-trash-alt me-1"></i> Hapus Semua Data
                    </button>
                </div>

                <!-- Alert Messages -->
                <?php if (!empty($success_message)): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <i class="fas fa-check-circle me-2"></i><?php echo $success_message; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>

                <?php if (!empty($error_message)): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <i class="fas fa-exclamation-circle me-2"></i><?php echo $error_message; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>

                <!-- Filter Status -->
                <div class="card mb-4">
                    <div class="card-body">
                        <form action="" method="get" class="row g-3">
                            <div class="col-md-6">
                                <label for="filter_status" class="form-label">Filter Status</label>
                                <select class="form-select" id="filter_status" name="status">
                                    <option value="">Semua Status</option>
                                    <option value="memerlukan_validasi" <?php echo $filter_status === 'memerlukan_validasi' ? 'selected' : ''; ?>>Memerlukan Validasi</option>
                                    <option value="tervalidasi" <?php echo $filter_status === 'tervalidasi' ? 'selected' : ''; ?>>Tervalidasi</option>
                                    <option value="ditolak" <?php echo $filter_status === 'ditolak' ? 'selected' : ''; ?>>Ditolak</option>
                                </select>
                            </div>
                            <div class="col-md-6 d-flex align-items-end">
                                <button type="submit" class="btn btn-primary w-100">
                                    <i class="fas fa-filter me-1"></i> Filter
                                </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 Sekolah</th>
                                        <th>Kabupaten/Kota</th> 
                                        <th>NPSN</th>
                                        <th>Nama Peserta</th>
                                        <th>Kategori</th>
                                        <th>Email / WA</th>
                                        <th>Status</th>
                                        <th>Aksi</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (!empty($schools)): ?>
                                        <?php foreach ($schools as $school): ?>
                                        <tr>
                                            <td><strong><?php echo htmlspecialchars($school['Nama_Sekolah']); ?></strong></td>
                                            <td><?php echo htmlspecialchars($school['Kabupaten_Kota'] ?? '-'); ?></td>
                                            <td><?php echo htmlspecialchars($school['NPSN']); ?></td>
                                            <td><?php echo htmlspecialchars($school['Nama_Peserta'] ?? '-'); ?></td>
                                            <td><span class="badge bg-secondary"><?php echo htmlspecialchars($school['Kategori']); ?></span></td>
                                            <td>
                                                <small><a href="mailto:<?php echo htmlspecialchars($school['Email']); ?>"><?php echo htmlspecialchars($school['Email']); ?></a><br>
                                                <a href="https://wa.me/<?php echo preg_replace('/[^0-9]/', '', $school['No_WA']); ?>"><?php echo htmlspecialchars($school['No_WA']); ?></a></small>
                                            </td>
                                            <td>
                                                <span class="status-badge status-<?php echo $school['Status']; ?>">
                                                    <?php 
                                                    $status_text = [
                                                        'memerlukan_validasi' => 'Menunggu',
                                                        'tervalidasi' => 'Tervalidasi',
                                                        'ditolak' => 'Ditolak'
                                                    ];
                                                    echo $status_text[$school['Status']] ?? $school['Status'];
                                                    ?>
                                                </span>
                                            </td>
                                            <td>
                                                <button type="button" class="btn btn-sm btn-info" data-bs-toggle="modal" data-bs-target="#viewModal" 
                                                    onclick="loadSchoolData(<?php echo htmlspecialchars(json_encode($school)); ?>)">
                                                    <i class="fas fa-eye"></i> Lihat
                                                </button>
                                                
                                                <?php if ($school['Status'] === 'memerlukan_validasi'): ?>
                                                <button type="button" class="btn btn-sm btn-success" data-bs-toggle="modal" data-bs-target="#validasiModal" 
                                                    onclick="setSchoolForValidasi(<?php echo $school['ID']; ?>, '<?php echo htmlspecialchars($school['Nama_Sekolah']); ?>', '<?php echo htmlspecialchars(strtolower($school['Kabupaten_Kota'])); ?>')">
                                                    <i class="fas fa-check"></i> Validasi
                                                </button>
                                                <button type="button" class="btn btn-sm btn-danger" data-bs-toggle="modal" data-bs-target="#tolakModal" 
                                                    onclick="setSchoolForTolak(<?php echo $school['ID']; ?>, '<?php echo htmlspecialchars($school['Nama_Sekolah']); ?>')">
                                                    <i class="fas fa-times"></i> Tolak
                                                </button>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <tr><td colspan="8" class="text-center">Tidak ada data sekolah</td></tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>

                        <?php if ($total_pages > 1): ?>
                        <nav aria-label="Page navigation">
                            <ul class="pagination justify-content-center">
                                <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                                    <a class="page-link" href="?page=<?php echo max(1, $page-1) . (empty($filter_status) ? '' : '&status='.$filter_status); ?>">Previous</a>
                                </li>

                                <?php for ($i = max(1, $page-2); $i <= min($total_pages, $page+2); $i++): ?>
                                <li class="page-item <?php echo $i === $page ? 'active' : ''; ?>">
                                    <a class="page-link" href="?page=<?php echo $i . (empty($filter_status) ? '' : '&status='.$filter_status); ?>"><?php echo $i; ?></a>
                                </li>
                                <?php endfor; ?>

                                <li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
                                    <a class="page-link" href="?page=<?php echo min($total_pages, $page+1) . (empty($filter_status) ? '' : '&status='.$filter_status); ?>">Next</a>
                                </li>
                            </ul>
                        </nav>
                        <?php endif; ?>
                    </div>
                </div>

    <div class="modal fade" id="viewModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Detail Sekolah</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="viewModalContent">
                    </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="validasiModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Validasi Sekolah</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="validasiForm" method="POST">
                    <div class="modal-body">
                        <h6>Pilih Domisili Peserta</h6>
                        <p class="text-muted">Sekolah: <strong id="validasiSchoolName"></strong></p>
                        
                        <div class="mb-3">
                            <label for="validasiDomisili" class="form-label">Domisili <span class="text-danger">*</span></label>
                            <select class="form-select" id="validasiDomisili" 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>
                            <small class="form-text text-muted">Domisili akan ditambahkan ke tabel peserta terdaftar</small>
                        </div>

                        <input type="hidden" id="validasiSchoolId" name="school_id">
                        <input type="hidden" name="action" value="validasi">
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                        <button type="submit" class="btn btn-success">
                            <i class="fas fa-check"></i> Ya, Validasi
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="modal fade" id="tolakModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Tolak Sekolah</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="tolakForm" method="POST">
                    <div class="modal-body">
                        <p>Alasan penolakan untuk <strong id="tolakSchoolName"></strong>:</p>
                        <textarea class="form-control" name="alasan" rows="4" placeholder="Masukkan alasan penolakan..." required></textarea>
                        <input type="hidden" id="tolakSchoolId" name="school_id">
                        <input type="hidden" name="action" value="tolak">
                    </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">
                            <i class="fas fa-times"></i> Ya, Tolak
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Modal Import Excel -->
    <div class="modal fade" id="importModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-upload"></i> Import Data Sekolah</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="importForm" method="POST" enctype="multipart/form-data">
                    <div class="modal-body">
                        <p class="text-muted">Upload file CSV atau Excel untuk import data sekolah secara massal.</p>
                        
                        <div class="mb-3">
                            <label for="file_import" class="form-label">Pilih File <span class="text-danger">*</span></label>
                            <input type="file" class="form-control" id="file_import" name="file_import" accept=".csv,.xls,.xlsx" required>
                            <small class="form-text text-muted">Format: CSV, XLS, atau XLSX. Maksimal 5MB</small>
                        </div>

                        <div class="alert alert-info" role="alert">
                            <strong>Format File CSV:</strong>
                            <pre class="mb-0" style="font-size: 16px;">Nama Sekolah,Nama Peserta,NPSN,Kategori,Kabupaten/Kota,Email,No. WA,Link Bukti BPTI
SMA NEGERI 1 SEMARANG,Budi Santoso,201020,SMA,Kabupaten Semarang,sekolah@email.com,081234567890,https://example.com/bukti</pre>
                        </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">
                            <i class="fas fa-upload"></i> Import
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Modal Tambah Sekolah Manual -->
    <div class="modal fade" id="addSchoolModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-plus"></i> Tambah Sekolah Baru</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="addSchoolForm" method="POST">
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="add_nama_sekolah" class="form-label">Nama Sekolah <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="add_nama_sekolah" name="add_nama_sekolah" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="add_npsn" class="form-label">NPSN <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="add_npsn" name="add_npsn" required placeholder="Contoh: 2312345" pattern="[0-9]+" title="NPSN hanya boleh angka">
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="add_nama_peserta" class="form-label">Nama Peserta</label>
                                <input type="text" class="form-control" id="add_nama_peserta" name="add_nama_peserta">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="add_kategori" class="form-label">Kategori</label>
                                <select class="form-select" id="add_kategori" name="add_kategori">
                                    <option value="">-- Pilih Kategori --</option>
                                    <option value="SMA">SMA</option>
                                    <option value="MA">MA (Madrasah Aliyah)</option>
                                    <option value="SMK">SMK</option>
                                    <option value="MAK">MAK (Madrasah Aliyah Kejuruan)</option>
                                    <option value="PKBM">PKBM</option>
                                </select>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="add_kabupaten_kota" class="form-label">Kabupaten/Kota</label>
                                <select class="form-select" id="add_kabupaten_kota" name="add_kabupaten_kota">
                                    <option value="">-- Pilih Kabupaten/Kota --</option>
                                    <option value="Kota Salatiga">Kota Salatiga</option>
                                    <option value="Kabupaten Demak">Kabupaten Demak</option>
                                    <option value="Kabupaten Semarang">Kabupaten Semarang</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="add_email" class="form-label">Email</label>
                                <input type="email" class="form-control" id="add_email" name="add_email">
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="add_no_wa" class="form-label">No. WhatsApp</label>
                                <input type="tel" class="form-control" id="add_no_wa" name="add_no_wa" pattern="[0-9]{10,15}">
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-12 mb-3">
                                <label for="add_link_bukti" class="form-label">Link Bukti BPTI</label>
                                <input type="url" class="form-control" id="add_link_bukti" name="add_link_bukti" placeholder="https://example.com/bukti">
                                <small class="form-text text-muted">Link bukti pendaftaran dari BPTI (opsional)</small>
                            </div>
                        </div>

                        <input type="hidden" name="action" value="add_school">
                    </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">
                            <i class="fas fa-save"></i> Simpan Sekolah
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Modal Hapus Semua Data -->
    <div class="modal fade" id="deleteAllModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header bg-danger text-white">
                    <h5 class="modal-title"><i class="fas fa-exclamation-triangle"></i> Konfirmasi Hapus Semua Data</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="deleteAllForm" method="POST">
                    <div class="modal-body">
                        <div class="alert alert-danger" role="alert">
                            <i class="fas fa-exclamation-triangle me-2"></i>
                            <strong>PERHATIAN!</strong> Tindakan ini akan menghapus SEMUA data sekolah dan tidak dapat dibatalkan!
                        </div>
                        
                        <p class="mb-3">Masukkan <strong>password admin Anda</strong> untuk konfirmasi:</p>
                        
                        <div class="mb-3">
                            <label for="adminPassword" class="form-label">Password Admin <span class="text-danger">*</span></label>
                            <input type="password" class="form-control" id="adminPassword" name="admin_password" required placeholder="Masukkan password admin">
                        </div>

                        <input type="hidden" name="action" value="delete_all">
                        <input type="hidden" name="confirm" value="yes">
                    </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">
                            <i class="fas fa-trash-alt me-2"></i> Hapus Semua Data
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function loadSchoolData(school) {
            let buktiLink = `<a href="${school.Link_Bukti_BPTI}" target="_blank" class="btn btn-sm btn-primary">${school.Link_Bukti_BPTI}</a>`;
            
            let html = `
                <div class="row mb-3">
                    <div class="col-md-6">
                        <strong>Nama Sekolah:</strong><br>${school.Nama_Sekolah}
                    </div>
                    <div class="col-md-6">
                        <strong>Kabupaten/Kota:</strong><br>${school.Kabupaten_Kota || '-'}
                    </div>
                </div>
                <div class="row mb-3">
                    <div class="col-md-6">
                        <strong>NPSN:</strong><br>${school.NPSN}
                    </div>
                    <div class="col-md-6">
                        <strong>Nama Peserta:</strong><br>${school.Nama_Peserta || '-'}
                    </div>
                </div>
                <div class="row mb-3">
                    <div class="col-md-6">
                        <strong>Kategori:</strong><br><span class="badge bg-secondary">${school.Kategori}</span>
                    </div>
                    <div class="col-md-6">
                        <strong>Email:</strong><br><a href="mailto:${school.Email}">${school.Email}</a>
                    </div>
                </div>
                <div class="row mb-3">
                    <div class="col-md-6">
                        <strong>No. WhatsApp:</strong><br><a href="https://wa.me/${school.No_WA.replace(/[^0-9]/g, '')}">${school.No_WA}</a>
                    </div>
                    <div class="col-md-6">
                        <strong>Link Bukti BPTI:</strong><br>${buktiLink}
                    </div>
                </div>
                <div class="row mb-3">
                    <div class="col-md-6">
                        <strong>Status:</strong><br>
                        <span class="status-badge status-${school.Status}">
                            ${{'memerlukan_validasi': 'Menunggu Validasi', 'tervalidasi': 'Tervalidasi', 'ditolak': 'Ditolak'}[school.Status]}
                        </span>
                    </div>
                    <div class="col-md-6">
                        <strong>Tanggal Daftar:</strong><br>${new Date(school.Tanggal_Daftar).toLocaleDateString('id-ID')}
                    </div>
                </div>
            `;
            
            if (school.Validasi_Oleh) {
                html += `<div class="row mb-3">
                    <div class="col-md-12">
                        <strong>Divalidasi oleh:</strong> ${school.Validasi_Oleh} pada ${new Date(school.Tanggal_Validasi).toLocaleDateString('id-ID')}
                    </div>
                </div>`;
            }
            
            if (school.Keterangan_Penolakan) {
                html += `<div class="row mb-3">
                    <div class="col-md-12">
                        <strong>Alasan Penolakan:</strong><br><textarea class="form-control" readonly>${school.Keterangan_Penolakan}</textarea>
                    </div>
                </div>`;
            }
            
            document.getElementById('viewModalContent').innerHTML = html;
        }

        function setSchoolForValidasi(schoolId, schoolName, domisili) {
            document.getElementById('validasiSchoolId').value = schoolId;
            document.getElementById('validasiSchoolName').textContent = schoolName;
            // Auto-fill domisili dari tabel sekolah
            if (domisili) {
                document.getElementById('validasiDomisili').value = domisili;
            } else {
                document.getElementById('validasiDomisili').value = '';
            }
        }

        function setSchoolForTolak(schoolId, schoolName) {
            document.getElementById('tolakSchoolId').value = schoolId;
            document.getElementById('tolakSchoolName').textContent = schoolName;
            document.querySelector('textarea[name="alasan"]').value = '';
        }

        // Validasi form sebelum submit
        document.getElementById('validasiForm').addEventListener('submit', function(e) {
            const domisili = document.getElementById('validasiDomisili').value;
            if (!domisili) {
                e.preventDefault();
                alert('Silakan pilih domisili peserta terlebih dahulu!');
                return false;
            }
        });

        // Validasi password pada delete all form
        document.getElementById('deleteAllForm').addEventListener('submit', function(e) {
            const password = document.getElementById('adminPassword').value;
            if (!password) {
                e.preventDefault();
                alert('Silakan masukkan password admin!');
            }
        });

        // Validasi file import
        document.getElementById('importForm').addEventListener('submit', function(e) {
            const fileInput = document.getElementById('file_import');
            if (!fileInput.value) {
                e.preventDefault();
                alert('Silakan pilih file untuk di-import!');
            }
        });

        // Validasi input NPSN - hanya angka
        document.getElementById('add_npsn').addEventListener('input', function(e) {
            this.value = this.value.replace(/[^0-9]/g, '');
        });
    </script>

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