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

// INISIALISASI VARIABEL DI PALING ATAS
$id_guru_aktif = $_SESSION['id_guru'] ?? 0;
$role = $_SESSION['role'] ?? 'guru';
$id_t = isset($_GET['id_tugas']) ? mysqli_real_escape_string($koneksi, $_GET['id_tugas']) : '';

$g = mysqli_fetch_array(mysqli_query($koneksi, "SELECT nama FROM master_guru WHERE id_guru = '$id_guru_aktif'"));
$aktif = mysqli_fetch_array(mysqli_query($koneksi, "SELECT * FROM semester s, tahun_pelajaran t WHERE s.status='Aktif' AND t.status='Aktif' LIMIT 1"));

require 'layout.php';
?>

<div class="container-fluid p-4">
    <h3>Input Nilai Per TP</h3>
    <div class="alert alert-secondary shadow-sm">
        <strong>Guru:</strong> <?= htmlspecialchars($g['nama'] ?? '-') ?> | 
        <strong>Tahun:</strong> <?= htmlspecialchars($aktif['tahun_pelajaran'] ?? '-') ?> | 
        <strong>Semester:</strong> <?= htmlspecialchars($aktif['nama_semester'] ?? '-') ?>
    </div>

    <form method="GET" class="card p-3 mb-4 shadow-sm">
        <div class="row g-2 align-items-center">
            <div class="col-md-6">
                <select name="id_tugas" class="form-select" onchange="this.form.submit()">
                    <option value="">-- Pilih Mapel & Kelas --</option>
                    <?php
                    $where_clause = ($role == 'admin') ? "1=1" : "t.id_guru='$id_guru_aktif'";
                    $sql = "SELECT t.id_tugas, m.nama_mapel, r.kelas FROM tugas_guru t 
                            JOIN master_mapel m ON t.id_mapel=m.id_mapel 
                            JOIN rombel r ON t.id_rombel=r.id_rombel 
                            WHERE $where_clause AND t.id_semester = '{$aktif['id_semester']}' AND t.id_tp_tahun = '{$aktif['id_tp_tahun']}'";
                    $q = mysqli_query($koneksi, $sql);
                    while($d = mysqli_fetch_array($q)) {
                        $sel = ($id_t == $d['id_tugas']) ? 'selected' : '';
                        echo "<option value='".$d['id_tugas']."' $sel>".htmlspecialchars($d['nama_mapel'])." - Kelas: ".htmlspecialchars($d['kelas'])."</option>";
                    }
                    ?>
                </select>
            </div>
            
            <?php if(!empty($id_t)): ?>
            <div class="col-md-6 d-flex gap-2">
                <a href="lingkup_materi.php?id_tugas=<?= urlencode($id_t) ?>" class="btn btn-primary flex-fill">
                    <i class="fa fa-book"></i> Lingkup Materi
                </a>
                <a href="cetak_nilai.php?id_tugas=<?= urlencode($id_t) ?>" class="btn btn-info flex-fill" target="_blank">
                    <i class="fa fa-print"></i> Cetak Nilai
                </a>
                <a href="absensi_mapel.php?id_tugas=<?= urlencode($id_t) ?>" class="btn btn-secondary flex-fill" target="_blank">
                    <i class="fa fa-file-alt"></i> Absensi Mapel
                </a>
            </div>
            <?php endif; ?>
        </div>
    </form>

    <?php
    if(!empty($id_t)) {
        $daftar_tp = mysqli_fetch_all(mysqli_query($koneksi, "SELECT id, tp_kode FROM tujuan_pembelajaran WHERE id_tugas = '$id_t'"), MYSQLI_ASSOC);
        $q_n = mysqli_query($koneksi, "SELECT id_siswa, id_tp, nilai, nilai_rapor FROM nilai_siswa WHERE id_tugas = '$id_t'");
        
        $n_data = []; $r_data = [];
        while($r = mysqli_fetch_assoc($q_n)) { 
            $key = ($r['id_tp'] == null || $r['id_tp'] == 0) ? 'sas' : $r['id_tp'];
            $n_data[$r['id_siswa']][$key] = $r['nilai']; 
            $r_data[$r['id_siswa']] = $r['nilai_rapor'];
        }

        $q_s = mysqli_query($koneksi, "SELECT s.id_siswa, s.nama FROM master_siswa s 
                JOIN anggota_rombel ar ON s.id_siswa=ar.id_siswa 
                WHERE ar.id_rombel=(SELECT id_rombel FROM tugas_guru WHERE id_tugas='$id_t') ORDER BY s.nama ASC");

        echo "<form method='POST' action='proses_simpan_nilai.php'><input type='hidden' name='id_tugas' value='".htmlspecialchars($id_t)."'>
              <div class='table-responsive'><table class='table table-bordered table-hover'><thead class='table-dark'><tr><th>Nama</th>";
        foreach($daftar_tp as $tp) echo "<th>{$tp['tp_kode']}</th>";
        echo "<th>SAS</th><th>Rerata</th><th>Nilai Rapor</th></tr></thead><tbody>";

        while($s = mysqli_fetch_array($q_s)) {
            echo "<tr class='baris-nilai'><td>".htmlspecialchars($s['nama'])."</td>";
            foreach($daftar_tp as $tp) {
                $v = $n_data[$s['id_siswa']][$tp['id']] ?? '';
                echo "<td><input type='number' name='tp[{$s['id_siswa']}][{$tp['id']}]' value='".htmlspecialchars($v)."' class='form-control nilai-tp' oninput='hitung(this)'></td>";
            }
            $v_sas = $n_data[$s['id_siswa']]['sas'] ?? '';
            $v_rapor = $r_data[$s['id_siswa']] ?? '';
            echo "<td><input type='number' name='sas[{$s['id_siswa']}]' value='".htmlspecialchars($v_sas)."' class='form-control nilai-sas' oninput='hitung(this)'></td>
                  <td><input type='text' class='form-control rerata-akhir' readonly></td>
                  <td><input type='number' name='nilai_rapor[{$s['id_siswa']}]' value='".htmlspecialchars($v_rapor)."' class='form-control'></td></tr>";
        }
        echo "</tbody></table></div><button type='submit' class='btn btn-success mt-2'>Simpan Semua Nilai</button></form>";
    }
    ?>
</div>

<script>
function hitung(el) {
    let tr = el.closest('.baris-nilai');
    let tps = tr.querySelectorAll('.nilai-tp');
    let sas = parseFloat(tr.querySelector('.nilai-sas').value) || 0;
    let total = 0, count = 0;
    tps.forEach(i => { if(i.value) { total += parseFloat(i.value); count++; } });
    let rerata = count > 0 ? (total/count + sas) / 2 : sas/2;
    tr.querySelector('.rerata-akhir').value = rerata.toFixed(2);
}
</script>
<?php require 'layout_footer.php'; ?>