<?php
require_once '../auth/cek_login.php';
require_role(['admin','guru']);
require_once '../config/koneksi.php';

if (!function_exists('e')) {
    function e($value) { return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); }
}

function pastikan_kolom_siswa($conn, $kolom, $definisi)
{
    $kolom = preg_replace('/[^a-zA-Z0-9_]/', '', $kolom);
    $cek = $conn->query("SHOW COLUMNS FROM siswa LIKE '" . $conn->real_escape_string($kolom) . "'");
    if ($cek && $cek->num_rows == 0) {
        $conn->query("ALTER TABLE siswa ADD `$kolom` $definisi");
    }
}

pastikan_kolom_siswa($conn, 'nomor_skl', 'VARCHAR(100) NULL');
pastikan_kolom_siswa($conn, 'tanggal_skl', 'DATE NULL');
pastikan_kolom_siswa($conn, 'status_lulus', "VARCHAR(30) NULL DEFAULT 'LULUS'");
pastikan_kolom_siswa($conn, 'keterangan_lulus', 'TEXT NULL');

$profil = $conn->query('SELECT * FROM profil_sekolah LIMIT 1')->fetch_assoc();
$tahun = $_GET['tahun'] ?? ($profil['tahun_pelajaran'] ?? '2025/2026');
$kelas = $_GET['kelas'] ?? '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $tahun = trim($_POST['tahun'] ?? $tahun);
    $kelas = trim($_POST['kelas'] ?? $kelas);
    foreach (($_POST['skl'] ?? []) as $id => $data) {
        $id = (int)$id;
        if ($id <= 0) { continue; }
        $nomor = trim($data['nomor_skl'] ?? '');
        $tanggal = trim($data['tanggal_skl'] ?? '');
        $status = trim($data['status_lulus'] ?? 'LULUS');
        $ket = trim($data['keterangan_lulus'] ?? '');
        $tanggal = $tanggal === '' ? null : $tanggal;
        $stmt = $conn->prepare('UPDATE siswa SET nomor_skl=?, tanggal_skl=?, status_lulus=?, keterangan_lulus=? WHERE id=?');
        $stmt->bind_param('ssssi', $nomor, $tanggal, $status, $ket, $id);
        $stmt->execute();
    }
    header('Location: cetak_skl.php?kelas=' . urlencode($kelas) . '&tahun=' . urlencode($tahun) . '&status=sukses');
    exit;
}

$kelasQ = $conn->query('SELECT DISTINCT kelas FROM siswa ORDER BY kelas ASC');
$where = '';
$params = [];
$types = '';
if ($kelas !== '') {
    $where = 'WHERE kelas = ?';
    $params[] = $kelas;
    $types .= 's';
}
$stmt = $conn->prepare("SELECT * FROM siswa $where ORDER BY kelas ASC, nama ASC");
if ($params) { $stmt->bind_param($types, ...$params); }
$stmt->execute();
$siswa = $stmt->get_result();

include 'header.php';
?>
<h3 class="fw-bold mb-3">Cetak Surat Keterangan Lulus (SKL)</h3>

<?php if (isset($_GET['status'])): ?>
    <div class="alert alert-success">Data SKL berhasil disimpan.</div>
<?php endif; ?>

<form method="get" class="card p-3 mb-3">
    <div class="row g-2 align-items-end">
        <div class="col-md-4">
            <label>Kelas</label>
            <select name="kelas" class="form-select">
                <option value="">Semua Kelas</option>
                <?php while ($k = $kelasQ->fetch_assoc()): ?>
                    <option value="<?= e($k['kelas']) ?>" <?= $kelas == $k['kelas'] ? 'selected' : '' ?>><?= e($k['kelas']) ?></option>
                <?php endwhile; ?>
            </select>
        </div>
        <div class="col-md-4">
            <label>Tahun Pelajaran</label>
            <input type="text" name="tahun" class="form-control" value="<?= e($tahun) ?>" required>
        </div>
        <div class="col-md-4">
            <button class="btn btn-primary w-100"><i class="fa-solid fa-search"></i> Tampilkan</button>
        </div>
    </div>
</form>

<form method="post" class="card p-3">
    <input type="hidden" name="kelas" value="<?= e($kelas) ?>">
    <input type="hidden" name="tahun" value="<?= e($tahun) ?>">

    <div class="d-flex flex-wrap gap-2 justify-content-between align-items-center mb-3">
        <div>
            <b>Data SKL</b><br>
            <small class="text-muted">Isi nomor/tanggal SKL, simpan, lalu cetak per siswa atau semua siswa.</small>
        </div>
        <div class="d-flex gap-2">
            <button class="btn btn-success"><i class="fa-solid fa-save"></i> Simpan Data SKL</button>
            <a target="_blank" class="btn btn-primary" href="../cetak/skl.php?kelas=<?= urlencode($kelas) ?>&tahun=<?= urlencode($tahun) ?>">
                <i class="fa-solid fa-print"></i> Cetak Semua
            </a>
        </div>
    </div>

    <div class="table-responsive">
        <table class="table table-bordered table-striped align-middle">
            <thead class="table-dark">
                <tr>
                    <th>No</th>
                    <th>Nama</th>
                    <th>NISN</th>
                    <th>No SKL</th>
                    <th>Tanggal SKL</th>
                    <th>Status</th>
                    <th>Keterangan</th>
                    <th>Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php $no = 1; while ($row = $siswa->fetch_assoc()): ?>
                    <tr>
                        <td><?= $no++ ?></td>
                        <td><?= e($row['nama'] ?? '-') ?></td>
                        <td><?= e($row['nisn'] ?? '-') ?></td>
                        <td><input class="form-control form-control-sm" name="skl[<?= (int)$row['id'] ?>][nomor_skl]" value="<?= e($row['nomor_skl'] ?? '') ?>" placeholder="421.2/.../SD/..."></td>
                        <td><input type="date" class="form-control form-control-sm" name="skl[<?= (int)$row['id'] ?>][tanggal_skl]" value="<?= e($row['tanggal_skl'] ?? date('Y-m-d')) ?>"></td>
                        <td>
                            <select class="form-select form-select-sm" name="skl[<?= (int)$row['id'] ?>][status_lulus]">
                                <?php $st = $row['status_lulus'] ?? 'LULUS'; ?>
                                <option value="LULUS" <?= $st == 'LULUS' ? 'selected' : '' ?>>LULUS</option>
                                <option value="TIDAK LULUS" <?= $st == 'TIDAK LULUS' ? 'selected' : '' ?>>TIDAK LULUS</option>
                            </select>
                        </td>
                        <td><input class="form-control form-control-sm" name="skl[<?= (int)$row['id'] ?>][keterangan_lulus]" value="<?= e($row['keterangan_lulus'] ?? '') ?>" placeholder="Opsional"></td>
                        <td>
                            <a target="_blank" class="btn btn-sm btn-primary" href="../cetak/skl.php?id=<?= (int)$row['id'] ?>&tahun=<?= urlencode($tahun) ?>">
                                <i class="fa-solid fa-print"></i> Cetak
                            </a>
                        </td>
                    </tr>
                <?php endwhile; ?>
            </tbody>
        </table>
    </div>
</form>
<?php include 'footer.php'; ?>
