<?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");
    }
}

function nilai_angka($value)
{
    $value = str_replace(',', '.', trim((string)$value));
    if ($value === '') {
        return 0;
    }

    $value = (float)$value;
    if ($value < 0) {
        return 0;
    }
    if ($value > 100) {
        return 100;
    }

    return $value;
}

function hitung_rata_ujian($conn, $siswa_id, $tahun)
{
    $stmt = $conn->prepare("SELECT AVG(nilai) AS rata FROM nilai WHERE siswa_id = ? AND tahun_pelajaran = ?");
    $stmt->bind_param('is', $siswa_id, $tahun);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();

    return $row && $row['rata'] !== null ? round((float)$row['rata'], 2) : 0;
}

function simpan_nilai_akhir($conn, $id, $tahun, $nilai_k5_s1, $nilai_k5_s2, $nilai_k6_s1)
{
    $nilai_rata_ujian = hitung_rata_ujian($conn, $id, $tahun);
    $nilai_rata_raport = round(($nilai_k5_s1 + $nilai_k5_s2 + $nilai_k6_s1) / 3, 2);
    $nilai_akhir = round(($nilai_rata_raport * 0.70) + ($nilai_rata_ujian * 0.30), 2);

    $stmt = $conn->prepare("
        UPDATE siswa SET
            nilai_k5_s1 = ?,
            nilai_k5_s2 = ?,
            nilai_k6_s1 = ?,
            nilai_rata_ujian = ?,
            nilai_rata_raport = ?,
            nilai_akhir = ?
        WHERE id = ?
    ");

    $stmt->bind_param(
        'ddddddi',
        $nilai_k5_s1,
        $nilai_k5_s2,
        $nilai_k6_s1,
        $nilai_rata_ujian,
        $nilai_rata_raport,
        $nilai_akhir,
        $id
    );

    $stmt->execute();
}

pastikan_kolom_siswa($conn, 'nilai_k5_s1', 'DECIMAL(5,2) NULL');
pastikan_kolom_siswa($conn, 'nilai_k5_s2', 'DECIMAL(5,2) NULL');
pastikan_kolom_siswa($conn, 'nilai_k6_s1', 'DECIMAL(5,2) NULL');
pastikan_kolom_siswa($conn, 'nilai_rata_ujian', 'DECIMAL(5,2) NULL');
pastikan_kolom_siswa($conn, 'nilai_rata_raport', 'DECIMAL(5,2) NULL');
pastikan_kolom_siswa($conn, 'nilai_akhir', 'DECIMAL(5,2) NULL');

$kelas = $_GET['kelas'] ?? '';
$tahun = $_GET['tahun'] ?? '';

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

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

    foreach (($_POST['nilai'] ?? []) as $id => $nilai) {
        $id = (int)$id;
        if ($id <= 0) {
            continue;
        }

        simpan_nilai_akhir(
            $conn,
            $id,
            $tahun,
            nilai_angka($nilai['nilai_k5_s1'] ?? 0),
            nilai_angka($nilai['nilai_k5_s2'] ?? 0),
            nilai_angka($nilai['nilai_k6_s1'] ?? 0)
        );
    }

    header(
        'Location: nilai_akhir.php?kelas=' . urlencode($kelas) .
            '&tahun=' . urlencode($tahun) .
            '&status=sukses'
    );
    exit;
}

include 'header.php';

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

$where = '';
$params = [];
$types = '';

if ($kelas !== '') {
    $where = 'WHERE kelas = ?';
    $params[] = $kelas;
    $types .= 's';
}

$sql = "SELECT * FROM siswa $where ORDER BY kelas ASC, nama ASC";
$stmt = $conn->prepare($sql);
if ($params) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$siswa = $stmt->get_result();
?>

<h3 class="fw-bold mb-3">Nilai Akhir Siswa</h3>

<?php if (isset($_GET['status'])): ?>
    <div class="alert alert-success">Nilai akhir berhasil disimpan dan dihitung ulang.</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 name="tahun" class="form-control" value="<?= e($tahun) ?>" required>
        </div>

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

<div class="alert alert-info">
    <b>Rata Ujian</b> dihitung otomatis dari menu <b>Input Nilai Ujian</b> berdasarkan tahun pelajaran yang dipilih.
    Rumus nilai akhir: <b>70% Rata Raport + 30% Rata Ujian</b>.
</div>

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

    <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>Kelas</th>
                    <th>K5 S1</th>
                    <th>K5 S2</th>
                    <th>K6 S1</th>
                    <th>Rata Ujian</th>
                    <th>Rata Raport</th>
                    <th>Nilai Akhir</th>
                </tr>
            </thead>
            <tbody>
                <?php $no = 1; ?>
                <?php while ($row = $siswa->fetch_assoc()): ?>
                    <?php
                    $rata_ujian = hitung_rata_ujian($conn, (int)$row['id'], $tahun);
                    $k5s1 = (float)($row['nilai_k5_s1'] ?? 0);
                    $k5s2 = (float)($row['nilai_k5_s2'] ?? 0);
                    $k6s1 = (float)($row['nilai_k6_s1'] ?? 0);
                    $rata_raport = round(($k5s1 + $k5s2 + $k6s1) / 3, 2);
                    $nilai_akhir = round(($rata_raport * 0.70) + ($rata_ujian * 0.30), 2);
                    ?>
                    <tr>
                        <td><?= $no++ ?></td>
                        <td><?= e($row['nama'] ?? '-') ?></td>
                        <td><?= e($row['nisn'] ?? '-') ?></td>
                        <td><?= e($row['kelas'] ?? '-') ?></td>
                        <td><input type="number" step="0.01" min="0" max="100" name="nilai[<?= e($row['id']) ?>][nilai_k5_s1]" class="form-control form-control-sm" value="<?= e($row['nilai_k5_s1'] ?? '') ?>"></td>
                        <td><input type="number" step="0.01" min="0" max="100" name="nilai[<?= e($row['id']) ?>][nilai_k5_s2]" class="form-control form-control-sm" value="<?= e($row['nilai_k5_s2'] ?? '') ?>"></td>
                        <td><input type="number" step="0.01" min="0" max="100" name="nilai[<?= e($row['id']) ?>][nilai_k6_s1]" class="form-control form-control-sm" value="<?= e($row['nilai_k6_s1'] ?? '') ?>"></td>
                        <td><strong><?= e(number_format($rata_ujian, 2, ',', '.')) ?></strong></td>
                        <td><strong><?= e(number_format($rata_raport, 2, ',', '.')) ?></strong></td>
                        <td><strong class="text-primary"><?= e(number_format($nilai_akhir, 2, ',', '.')) ?></strong></td>
                    </tr>
                <?php endwhile; ?>
            </tbody>
        </table>
    </div>

    <button class="btn btn-success">Simpan & Hitung Semua Nilai Akhir</button>
</form>

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