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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $mapel_id = (int)($_POST['mapel_id'] ?? 0);
    $kelas = $_POST['kelas'] ?? '';
    $tahun = trim($_POST['tahun_pelajaran'] ?? '');

    foreach (($_POST['nilai'] ?? []) as $siswa_id => $nilai) {
        $siswa_id = (int)$siswa_id;
        $nilai = str_replace(',', '.', trim((string)$nilai));
        $nilai = ($nilai === '') ? 0 : (float)$nilai;

        if ($nilai < 0) {
            $nilai = 0;
        }

        if ($nilai > 100) {
            $nilai = 100;
        }

        $stmt = $conn->prepare("
            INSERT INTO nilai 
                (siswa_id, mapel_id, nilai, tahun_pelajaran) 
            VALUES 
                (?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE 
                nilai = VALUES(nilai)
        ");

        $stmt->bind_param(
            'iids',
            $siswa_id,
            $mapel_id,
            $nilai,
            $tahun
        );

        $stmt->execute();
    }

    header(
        'Location: nilai.php?kelas=' . urlencode($kelas) .
            '&mapel_id=' . $mapel_id .
            '&tahun=' . urlencode($tahun) .
            '&ok=1'
    );
    exit;
}

include 'header.php';

$kelas = $_GET['kelas'] ?? '';
$mapel_id = (int)($_GET['mapel_id'] ?? 0);
$tahun = $_GET['tahun'] ?? ($profil_header['tahun_pelajaran'] ?? '2025/2026');

$kelasQ = $conn->query("
    SELECT DISTINCT kelas 
    FROM siswa 
    ORDER BY kelas ASC
");

$mapelQ = $conn->query("
    SELECT * 
    FROM mapel 
    ORDER BY urutan ASC, nama_mapel ASC
");

$siswaQ = null;

if ($kelas !== '' && $mapel_id > 0) {
    $stmt = $conn->prepare("
        SELECT 
            s.*, 
            n.nilai 
        FROM siswa s 
        LEFT JOIN nilai n 
            ON n.siswa_id = s.id 
            AND n.mapel_id = ? 
            AND n.tahun_pelajaran = ? 
        WHERE s.kelas = ? 
        ORDER BY s.nama ASC
    ");

    $stmt->bind_param(
        'iss',
        $mapel_id,
        $tahun,
        $kelas
    );

    $stmt->execute();

    $siswaQ = $stmt->get_result();
}
?>

<h3 class="fw-bold mb-3">Input Nilai Ujian</h3>

<?php if (isset($_GET['ok'])): ?>
    <div class="alert alert-success">
        Nilai 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-3">
            <label>Kelas</label>
            <select name="kelas" class="form-select" required>
                <option value="">Pilih 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>Mata Pelajaran</label>
            <select name="mapel_id" class="form-select" required>
                <option value="">Pilih Mapel</option>

                <?php while ($m = $mapelQ->fetch_assoc()): ?>
                    <option value="<?= e($m['id']) ?>" <?= $mapel_id == $m['id'] ? 'selected' : '' ?>>
                        <?= e($m['nama_mapel']) ?>
                    </option>
                <?php endwhile; ?>
            </select>
        </div>

        <div class="col-md-3">
            <label>Tahun Pelajaran</label>
            <input name="tahun" class="form-control" value="<?= e($tahun) ?>">
        </div>

        <div class="col-md-2">
            <button class="btn btn-primary w-100">
                Tampilkan
            </button>
        </div>

    </div>
</form>

<?php if ($siswaQ): ?>

    <form method="post" class="card p-3 table-responsive">

        <input type="hidden" name="kelas" value="<?= e($kelas) ?>">
        <input type="hidden" name="mapel_id" value="<?= e($mapel_id) ?>">
        <input type="hidden" name="tahun_pelajaran" value="<?= e($tahun) ?>">

        <table class="table table-bordered table-striped align-middle">
            <thead>
                <tr>
                    <th width="50">No</th>
                    <th>No Ujian</th>
                    <th>Nama Siswa</th>
                    <th width="160">Nilai</th>
                </tr>
            </thead>

            <tbody>
                <?php $no = 1; ?>
                <?php while ($s = $siswaQ->fetch_assoc()): ?>
                    <tr>
                        <td><?= $no++ ?></td>
                        <td><?= e($s['no_ujian'] ?? '') ?></td>
                        <td><?= e($s['nama'] ?? '') ?></td>
                        <td>
                            <input
                                type="number"
                                step="0.01"
                                min="0"
                                max="100"
                                name="nilai[<?= e($s['id']) ?>]"
                                class="form-control"
                                value="<?= e($s['nilai'] ?? '') ?>">
                        </td>
                    </tr>
                <?php endwhile; ?>
            </tbody>
        </table>

        <button class="btn btn-success">
            Simpan Nilai
        </button>

    </form>

<?php endif; ?>

<?php include 'footer.php'; ?>