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

// 1. Ambil Periode Aktif dari database agar akurat
$q_aktif = mysqli_query($koneksi, "SELECT s.id_semester, t.id_tp_tahun 
                                   FROM semester s, tahun_pelajaran t 
                                   WHERE s.status = 'Aktif' AND t.status = 'Aktif' LIMIT 1");
$aktif = mysqli_fetch_array($q_aktif);

$id_sem = $aktif['id_semester'] ?? 0;
$id_tp  = $aktif['id_tp_tahun'] ?? 0;

if (isset($_POST['id_tugas'])) {
    $id_tugas = mysqli_real_escape_string($koneksi, $_POST['id_tugas']);
    
    // 2. Simpan Nilai TP dengan menyertakan id_semester dan id_tp_tahun
    if (isset($_POST['tp'])) {
        foreach ($_POST['tp'] as $id_siswa => $tps) {
            foreach ($tps as $id_tp_pembelajaran => $nilai) {
                $nilai = ($nilai === '') ? 'NULL' : "'$nilai'";
                
                $sql = "INSERT INTO nilai_siswa (id_tugas, id_siswa, id_tp, nilai, id_semester, id_tp_tahun) 
                        VALUES ('$id_tugas', '$id_siswa', '$id_tp_pembelajaran', $nilai, '$id_sem', '$id_tp')
                        ON DUPLICATE KEY UPDATE nilai = $nilai";
                mysqli_query($koneksi, $sql);
            }
        }
    }

    // 3. Simpan Nilai SAS (id_tp = NULL) dengan penanda periode
    if (isset($_POST['sas'])) {
        foreach ($_POST['sas'] as $id_siswa => $nilai) {
            $nilai = ($nilai === '') ? 'NULL' : "'$nilai'";
            
            $sql = "INSERT INTO nilai_siswa (id_tugas, id_siswa, id_tp, nilai, id_semester, id_tp_tahun) 
                    VALUES ('$id_tugas', '$id_siswa', NULL, $nilai, '$id_sem', '$id_tp')
                    ON DUPLICATE KEY UPDATE nilai = $nilai";
            mysqli_query($koneksi, $sql);
        }
    }

    // 4. Simpan Nilai Rapor
    if (isset($_POST['nilai_rapor'])) {
        foreach ($_POST['nilai_rapor'] as $id_siswa => $nilai) {
            $nilai = ($nilai === '') ? 'NULL' : "'$nilai'";
            
            $sql = "UPDATE nilai_siswa SET nilai_rapor = $nilai WHERE id_tugas = '$id_tugas' AND id_siswa = '$id_siswa'";
            mysqli_query($koneksi, $sql);
        }
    }
    
    echo "<script>alert('Data berhasil disimpan!'); window.location='input_nilai.php?id_tugas=$id_tugas';</script>";
}
?>