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

// Check if user is admin
if (!isset($_SESSION['username']) || $_SESSION['role'] !== 'admin') {
    header('Location: ../../login.php');
    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;

// 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) {
                    // Peserta sudah terdaftar, hanya update status master_sekolah
                    $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>

                <?php if (!empty($action_message)): ?>
                    <div class="alert alert-<?php echo $action_type === 'success' ? 'success' : 'danger'; ?> alert-dismissible fade show" role="alert">
                        <?php echo $action_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"></i> Filter
                                </button>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Table -->
                <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>Nama Peserta</th>
                                        <th>NPSN</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['Nama_Peserta'] ?? '-'); ?></td>
                                            <td><?php echo htmlspecialchars($school['NPSN']); ?></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']); ?>')">
                                                    <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="7" class="text-center">Tidak ada data sekolah</td></tr>
                                    <?php endif; ?>
                                </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 $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>

    <!-- Modal View Detail -->
    <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">
                    <!-- Content akan diisi via JavaScript -->
                </div>
            </div>
        </div>
    </div>

    <!-- Modal Validasi -->
    <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>

    <!-- Modal Tolak -->
    <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>

    <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>Nama Peserta:</strong><br>${school.Nama_Peserta || '-'}
                    </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>Kategori:</strong><br><span class="badge bg-secondary">${school.Kategori}</span>
                    </div>
                </div>
                <div class="row mb-3">
                    <div class="col-md-6">
                        <strong>Email:</strong><br><a href="mailto:${school.Email}">${school.Email}</a>
                    </div>
                    <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>
                <div class="row mb-3">
                    <div class="col-md-12">
                        <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) {
            document.getElementById('validasiSchoolId').value = schoolId;
            document.getElementById('validasiSchoolName').textContent = schoolName;
            document.getElementById('validasiDomisili').value = ''; // Reset dropdown
        }

        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;
            }
        });
    </script>

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