<?php 
include 'koneksi.php';
cek_akses(['Guru']);

// Ambil daftar kelas di unit guru
$kelas_list = mysqli_query($conn, "SELECT * FROM classes WHERE unit='{$_SESSION['unit']}' ORDER BY name");

// Ambil kelas yang dipilih
$selected_class = isset($_GET['class_id']) ? (int)$_GET['class_id'] : 0;
$selected_mapel = isset($_GET['mata_pelajaran']) ? mysqli_real_escape_string($conn, $_GET['mata_pelajaran']) : '';
$edit_id = isset($_GET['edit']) ? (int)$_GET['edit'] : 0;

// Daftar mata pelajaran berdasarkan unit
$mata_pelajaran_list = [];
if($_SESSION['unit'] == 'Madrasah Ibtidaiyah') {
    $mata_pelajaran_list = ['Matematika', 'Bahasa Indonesia', 'IPA', 'IPS', 'Bahasa Inggris', 'Pendidikan Agama Islam', 'PKN', 'SBdP', 'Penjaskes', 'Bahasa Arab', 'Al-Qur\'an Hadits', 'Fikih', 'SKI', 'Aqidah Akhlak'];
} elseif($_SESSION['unit'] == 'Madrasah Tsanawiyah') {
    $mata_pelajaran_list = ['Matematika', 'Bahasa Indonesia', 'IPA', 'IPS', 'Bahasa Inggris', 'Pendidikan Agama Islam', 'PKN', 'Penjaskes', 'Bahasa Arab', 'Al-Qur\'an Hadits', 'Fikih', 'SKI', 'Aqidah Akhlak', 'TIK', 'Prakarya'];
} elseif($_SESSION['unit'] == 'Madrasah Aliyah') {
    $mata_pelajaran_list = ['Matematika', 'Bahasa Indonesia', 'Bahasa Inggris', 'Pendidikan Agama Islam', 'PKN', 'Penjaskes', 'Bahasa Arab', 'Al-Qur\'an Hadits', 'Fikih', 'SKI', 'Aqidah Akhlak', 'TIK', 'Fisika', 'Kimia', 'Biologi', 'Ekonomi', 'Sosiologi', 'Geografi', 'Sejarah', 'Seni Budaya'];
} elseif($_SESSION['unit'] == 'Istiqlal Boarding School') {
    $mata_pelajaran_list = ['Matematika', 'Bahasa Indonesia', 'Bahasa Inggris', 'Pendidikan Agama Islam', 'PKN', 'Penjaskes', 'Bahasa Arab', 'Al-Qur\'an Hadits', 'Fikih', 'SKI', 'Aqidah Akhlak', 'Tahfidz', 'Kitab Kuning', 'TIK', 'Fisika', 'Kimia', 'Biologi'];
} else {
    $mata_pelajaran_list = ['Matematika', 'Bahasa Indonesia', 'IPA', 'IPS', 'Bahasa Inggris', 'Pendidikan Agama Islam', 'PKN', 'SBdP', 'Penjaskes'];
}

// Buat tabel jika belum ada
mysqli_query($conn, "CREATE TABLE IF NOT EXISTS nilai_siswa (
    id INT PRIMARY KEY AUTO_INCREMENT,
    student_id INT NOT NULL,
    class_id INT NOT NULL,
    mata_pelajaran VARCHAR(100) NOT NULL,
    tugas DECIMAL(5,2) DEFAULT NULL,
    ulangan_harian DECIMAL(5,2) DEFAULT NULL,
    uts DECIMAL(5,2) DEFAULT NULL,
    uas DECIMAL(5,2) DEFAULT NULL,
    praktik DECIMAL(5,2) DEFAULT NULL,
    semester VARCHAR(10) DEFAULT 'Ganjil',
    tahun_ajaran VARCHAR(20) DEFAULT '2026/2027',
    teacher_id INT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)");

// Ambil data untuk edit
$edit_data = null;
if($edit_id > 0) {
    $query_edit = mysqli_query($conn, "SELECT * FROM nilai_siswa WHERE id = $edit_id");
    if($query_edit && mysqli_num_rows($query_edit) > 0) {
        $edit_data = mysqli_fetch_assoc($query_edit);
        // Set kelas dan mapel dari data edit
        $selected_class = $edit_data['class_id'];
        $selected_mapel = $edit_data['mata_pelajaran'];
    }
}

// Proses update nilai
if(isset($_POST['update_nilai'])) {
    $id = $_POST['id'];
    $tugas = $_POST['tugas'];
    $ulangan_harian = $_POST['ulangan_harian'];
    $uts = $_POST['uts'];
    $uas = $_POST['uas'];
    $praktik = $_POST['praktik'];
    
    $query = "UPDATE nilai_siswa SET 
        tugas = " . ($tugas !== '' ? $tugas : 'NULL') . ",
        ulangan_harian = " . ($ulangan_harian !== '' ? $ulangan_harian : 'NULL') . ",
        uts = " . ($uts !== '' ? $uts : 'NULL') . ",
        uas = " . ($uas !== '' ? $uas : 'NULL') . ",
        praktik = " . ($praktik !== '' ? $praktik : 'NULL') . "
        WHERE id = $id";
    
    if(mysqli_query($conn, $query)) {
        echo "<script>alert('Nilai berhasil diupdate!'); window.location='input_nilai.php';</script>";
    } else {
        echo "<script>alert('Gagal update: " . mysqli_error($conn) . "');</script>";
    }
}

// Proses simpan nilai baru
if(isset($_POST['simpan_nilai'])) {
    $class_id = $_POST['class_id'];
    $mata_pelajaran = mysqli_real_escape_string($conn, $_POST['mata_pelajaran']);
    $semester = $_POST['semester'];
    $tahun_ajaran = $_POST['tahun_ajaran'];
    
    $success = 0;
    $error = 0;
    
    foreach($_POST['tugas'] as $student_id => $tugas) {
        $tugas_value = ($tugas !== '') ? $tugas : 'NULL';
        $ulangan_value = (isset($_POST['ulangan_harian'][$student_id]) && $_POST['ulangan_harian'][$student_id] !== '') ? $_POST['ulangan_harian'][$student_id] : 'NULL';
        $uts_value = (isset($_POST['uts'][$student_id]) && $_POST['uts'][$student_id] !== '') ? $_POST['uts'][$student_id] : 'NULL';
        $uas_value = (isset($_POST['uas'][$student_id]) && $_POST['uas'][$student_id] !== '') ? $_POST['uas'][$student_id] : 'NULL';
        $praktik_value = (isset($_POST['praktik'][$student_id]) && $_POST['praktik'][$student_id] !== '') ? $_POST['praktik'][$student_id] : 'NULL';
        
        // Cek apakah sudah ada data
        $cek = mysqli_query($conn, "SELECT id FROM nilai_siswa 
            WHERE student_id = '$student_id' AND class_id = '$class_id' 
            AND mata_pelajaran = '$mata_pelajaran' AND semester = '$semester' AND tahun_ajaran = '$tahun_ajaran'");
        
        if($cek && mysqli_num_rows($cek) > 0) {
            $query = "UPDATE nilai_siswa SET 
                tugas = $tugas_value,
                ulangan_harian = $ulangan_value,
                uts = $uts_value,
                uas = $uas_value,
                praktik = $praktik_value
                WHERE student_id = '$student_id' AND class_id = '$class_id' 
                AND mata_pelajaran = '$mata_pelajaran' AND semester = '$semester' AND tahun_ajaran = '$tahun_ajaran'";
        } else {
            $query = "INSERT INTO nilai_siswa (student_id, class_id, mata_pelajaran, tugas, ulangan_harian, uts, uas, praktik, semester, tahun_ajaran, teacher_id) 
                      VALUES ('$student_id', '$class_id', '$mata_pelajaran', $tugas_value, $ulangan_value, $uts_value, $uas_value, $praktik_value, '$semester', '$tahun_ajaran', '{$_SESSION['user_id']}')";
        }
        
        if(mysqli_query($conn, $query)) {
            $success++;
        } else {
            $error++;
        }
    }
    
    if($error == 0) {
        echo "<script>alert('Nilai berhasil disimpan! $success siswa'); window.location='input_nilai.php?class_id=$class_id&mata_pelajaran=$mata_pelajaran';</script>";
    } else {
        echo "<script>alert('Tersimpan $success siswa, gagal $error');</script>";
    }
}

// Proses hapus nilai
if(isset($_GET['hapus'])) {
    $id = $_GET['hapus'];
    mysqli_query($conn, "DELETE FROM nilai_siswa WHERE id = $id");
    echo "<script>alert('Nilai berhasil dihapus!'); window.location='input_nilai.php';</script>";
}

// Ambil siswa berdasarkan kelas yang dipilih
$siswa_list = [];
$existing_nilai = [];
if($selected_class > 0 && $selected_mapel && !$edit_id) {
    $query_siswa = mysqli_query($conn, "SELECT s.*, c.name as class_name 
        FROM students s 
        JOIN classes c ON s.class_id = c.id 
        WHERE s.class_id = '$selected_class' 
        ORDER BY s.name");
    if($query_siswa) {
        while($row = mysqli_fetch_assoc($query_siswa)) {
            $siswa_list[] = $row;
        }
    }
    
    // Ambil nilai yang sudah ada
    $query_nilai = mysqli_query($conn, "SELECT * FROM nilai_siswa 
        WHERE class_id = '$selected_class' AND mata_pelajaran = '$selected_mapel'");
    if($query_nilai) {
        while($row = mysqli_fetch_assoc($query_nilai)) {
            $existing_nilai[$row['student_id']] = $row;
        }
    }
}

// ========== PERBAIKAN: AMBIL SEMUA DATA NILAI UNTUK REKAP ==========
$nilai_list = mysqli_query($conn, "SELECT n.*, s.name as student_name, c.name as class_name 
    FROM nilai_siswa n 
    JOIN students s ON n.student_id = s.id 
    JOIN classes c ON n.class_id = c.id 
    WHERE n.teacher_id = '{$_SESSION['user_id']}' 
    ORDER BY n.updated_at DESC LIMIT 100");

// ========== REKAP PER SISWA (UNTUK TABEL REKAP) ==========
$rekap_query = "SELECT 
    s.id as siswa_id,
    s.name as student_name,
    c.name as class_name,
    c.unit as unit,
    n.mata_pelajaran,
    n.tugas,
    n.ulangan_harian,
    n.uts,
    n.uas,
    n.praktik,
    ((IFNULL(n.tugas, 0) + IFNULL(n.ulangan_harian, 0) + IFNULL(n.uts, 0) + IFNULL(n.uas, 0) + IFNULL(n.praktik, 0)) / 
     (CASE WHEN n.tugas IS NOT NULL THEN 1 ELSE 0 END + 
      CASE WHEN n.ulangan_harian IS NOT NULL THEN 1 ELSE 0 END + 
      CASE WHEN n.uts IS NOT NULL THEN 1 ELSE 0 END + 
      CASE WHEN n.uas IS NOT NULL THEN 1 ELSE 0 END + 
      CASE WHEN n.praktik IS NOT NULL THEN 1 ELSE 0 END)) as rata_rata
FROM students s
JOIN classes c ON s.class_id = c.id
LEFT JOIN nilai_siswa n ON n.student_id = s.id AND n.teacher_id = '{$_SESSION['user_id']}'
WHERE n.id IS NOT NULL
ORDER BY c.unit, c.name, s.name";

$rekap_data = mysqli_query($conn, $rekap_query);
?>

<!DOCTYPE html>
<html>
<head>
    <title>Input Nilai Siswa - SIM ISTIQLAL</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/admin-lte@3.2/dist/css/adminlte.min.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="assets/css/theme-istiqlal-green.css">
    <style>
        .content-wrapper { background: #f1f5f9; }
        .card { border-radius: 20px; box-shadow: 0 5px 20px rgba(0,0,0,0.08); margin-bottom: 25px; border: none; }
        .card-header { border-radius: 20px 20px 0 0; padding: 12px 20px; background: linear-gradient(135deg, #0b5e4e 0%, #10b981 100%); color: white; }
        .card-header h4 { margin: 0; font-size: 16px; font-weight: 600; }
        .table thead th { background: linear-gradient(135deg, #0b5e4e 0%, #10b981 100%); color: white; font-weight: 600; padding: 10px; font-size: 12px; white-space: nowrap; }
        .table tbody td { padding: 8px 10px; vertical-align: middle; font-size: 12px; }
        .btn-save { background: linear-gradient(135deg, #0b5e4e 0%, #10b981 100%); border: none; color: white; padding: 10px 20px; border-radius: 8px; }
        .btn-save:hover { transform: translateY(-2px); }
        .btn-edit { background: #f59e0b; border: none; color: white; padding: 5px 10px; border-radius: 5px; }
        .btn-edit:hover { background: #d97706; }
        .nilai-input { width: 80px; text-align: center; }
        .jumlah-siswa { font-size: 14px; color: #64748b; margin-left: 10px; }
        .nilai-cell { background: #f8fafc; }
        .table-responsive { overflow-x: auto; }
        .badge-unit { font-size: 10px; padding: 3px 8px; border-radius: 12px; }
    </style>
</head>
<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">
    <?php include 'sidebar.php'; ?>
    
    <div class="content-wrapper">
        <div class="content-header">
            <div class="container-fluid">
                <div class="row mb-2">
                    <div class="col-sm-6">
                        <h1 class="m-0" style="font-size: 20px;">
                            <i class="fas fa-star text-warning"></i> Input Nilai Siswa
                        </h1>
                        <small class="text-muted">Unit: <?= $_SESSION['unit'] ?></small>
                    </div>
                    <div class="col-sm-6">
                        <ol class="breadcrumb float-sm-right">
                            <li class="breadcrumb-item"><a href="dashboard.php">Home</a></li>
                            <li class="breadcrumb-item active">Input Nilai</li>
                        </ol>
                    </div>
                </div>
            </div>
        </div>

        <div class="content">
            <div class="container-fluid">
                <!-- Form Edit Nilai -->
                <?php if($edit_data): ?>
                <div class="card">
                    <div class="card-header bg-warning text-white">
                        <h4><i class="fas fa-edit"></i> Edit Nilai Siswa</h4>
                    </div>
                    <div class="card-body">
                        <form method="POST">
                            <input type="hidden" name="id" value="<?= $edit_data['id'] ?>">
                            <div class="row">
                                <div class="col-md-3 mb-3">
                                    <label class="form-label">Siswa</label>
                                    <input type="text" class="form-control" value="<?= htmlspecialchars($edit_data['student_name'] ?? '') ?>" readonly disabled>
                                </div>
                                <div class="col-md-3 mb-3">
                                    <label class="form-label">Kelas</label>
                                    <input type="text" class="form-control" value="<?= htmlspecialchars($edit_data['class_name'] ?? '') ?>" readonly disabled>
                                </div>
                                <div class="col-md-3 mb-3">
                                    <label class="form-label">Mata Pelajaran</label>
                                    <input type="text" class="form-control" value="<?= htmlspecialchars($edit_data['mata_pelajaran']) ?>" readonly disabled>
                                </div>
                                <div class="col-md-3 mb-3">
                                    <label class="form-label">Semester / Tahun</label>
                                    <input type="text" class="form-control" value="<?= $edit_data['semester'] . ' / ' . $edit_data['tahun_ajaran'] ?>" readonly disabled>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-2 mb-3">
                                    <label class="form-label">Nilai Tugas</label>
                                    <input type="number" step="0.01" name="tugas" class="form-control" value="<?= $edit_data['tugas'] ?>" placeholder="0-100">
                                </div>
                                <div class="col-md-2 mb-3">
                                    <label class="form-label">Nilai Ulangan</label>
                                    <input type="number" step="0.01" name="ulangan_harian" class="form-control" value="<?= $edit_data['ulangan_harian'] ?>" placeholder="0-100">
                                </div>
                                <div class="col-md-2 mb-3">
                                    <label class="form-label">Nilai UTS</label>
                                    <input type="number" step="0.01" name="uts" class="form-control" value="<?= $edit_data['uts'] ?>" placeholder="0-100">
                                </div>
                                <div class="col-md-2 mb-3">
                                    <label class="form-label">Nilai UAS</label>
                                    <input type="number" step="0.01" name="uas" class="form-control" value="<?= $edit_data['uas'] ?>" placeholder="0-100">
                                </div>
                                <div class="col-md-2 mb-3">
                                    <label class="form-label">Nilai Praktik</label>
                                    <input type="number" step="0.01" name="praktik" class="form-control" value="<?= $edit_data['praktik'] ?>" placeholder="0-100">
                                </div>
                                <div class="col-md-2 mb-3">
                                    <label class="form-label">&nbsp;</label>
                                    <div class="d-flex gap-2">
                                        <button type="submit" name="update_nilai" class="btn btn-success">Simpan Perubahan</button>
                                        <a href="input_nilai.php" class="btn btn-secondary">Batal</a>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                <?php endif; ?>

                <!-- Filter Kelas -->
                <?php if(!$edit_data): ?>
                <div class="card">
                    <div class="card-header">
                        <h4><i class="fas fa-filter"></i> Pilih Kelas & Mata Pelajaran</h4>
                    </div>
                    <div class="card-body">
                        <form method="GET" action="">
                            <div class="row">
                                <div class="col-md-5 mb-3">
                                    <label class="form-label">Pilih Kelas</label>
                                    <select name="class_id" class="form-control" onchange="this.form.submit()">
                                        <option value="">-- Pilih Kelas --</option>
                                        <?php 
                                        if($kelas_list && mysqli_num_rows($kelas_list) > 0) {
                                            mysqli_data_seek($kelas_list, 0);
                                            while($kelas = mysqli_fetch_assoc($kelas_list)): ?>
                                            <option value="<?= $kelas['id'] ?>" <?= ($selected_class == $kelas['id']) ? 'selected' : '' ?>>
                                                <?= htmlspecialchars($kelas['name']) ?>
                                            </option>
                                            <?php endwhile;
                                        } ?>
                                    </select>
                                </div>
                                <div class="col-md-5 mb-3">
                                    <label class="form-label">Mata Pelajaran</label>
                                    <select name="mata_pelajaran" class="form-control" onchange="this.form.submit()">
                                        <option value="">-- Pilih Mata Pelajaran --</option>
                                        <?php foreach($mata_pelajaran_list as $mapel): ?>
                                        <option value="<?= $mapel ?>" <?= ($selected_mapel == $mapel) ? 'selected' : '' ?>>
                                            <?= $mapel ?>
                                        </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-2 mb-3">
                                    <label class="form-label">&nbsp;</label>
                                    <a href="input_nilai.php" class="btn btn-secondary form-control">Reset</a>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                <?php endif; ?>

                <!-- Form Input Nilai per Kelas -->
                <?php if($selected_class > 0 && $selected_mapel && count($siswa_list) > 0 && !$edit_id): ?>
                <div class="card">
                    <div class="card-header">
                        <h4>
                            <i class="fas fa-edit"></i> Input Nilai <?= htmlspecialchars($selected_mapel) ?>
                            <span class="jumlah-siswa">Jumlah Siswa: <?= count($siswa_list) ?></span>
                        </h4>
                    </div>
                    <div class="card-body">
                        <form method="POST" action="">
                            <input type="hidden" name="class_id" value="<?= $selected_class ?>">
                            <input type="hidden" name="mata_pelajaran" value="<?= htmlspecialchars($selected_mapel) ?>">
                            
                            <div class="row mb-3">
                                <div class="col-md-3">
                                    <label class="form-label">Semester</label>
                                    <select name="semester" class="form-control">
                                        <option value="Ganjil">Ganjil</option>
                                        <option value="Genap">Genap</option>
                                    </select>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">Tahun Ajaran</label>
                                    <select name="tahun_ajaran" class="form-control">
                                        <option value="2026/2027">2026/2027</option>
                                        <option value="2027/2028">2027/2028</option>
                                    </select>
                                </div>
                            </div>
                            
                            <div class="table-responsive">
                                <table class="table table-bordered table-striped">
                                    <thead>
                                        <tr>
                                            <th width="5%">No</th>
                                            <th width="18%">Nama Siswa</th>
                                            <th width="10%">NIS</th>
                                            <th width="10%">Tugas</th>
                                            <th width="10%">Ulangan Harian</th>
                                            <th width="10%">UTS</th>
                                            <th width="10%">UAS</th>
                                            <th width="10%">Praktik</th>
                                            <th width="8%">Rata-rata</th>
                                            <th width="7%">Grade</th>
                                         </div>
                                    </thead>
                                    <tbody>
                                        <?php $no=1; foreach($siswa_list as $siswa): 
                                            $nilai = isset($existing_nilai[$siswa['id']]) ? $existing_nilai[$siswa['id']] : null;
                                            $tugas = $nilai['tugas'] ?? '';
                                            $ulangan = $nilai['ulangan_harian'] ?? '';
                                            $uts = $nilai['uts'] ?? '';
                                            $uas = $nilai['uas'] ?? '';
                                            $praktik = $nilai['praktik'] ?? '';
                                            
                                            // Hitung rata-rata
                                            $rata = 0;
                                            $count = 0;
                                            if($tugas !== '') { $rata += $tugas; $count++; }
                                            if($ulangan !== '') { $rata += $ulangan; $count++; }
                                            if($uts !== '') { $rata += $uts; $count++; }
                                            if($uas !== '') { $rata += $uas; $count++; }
                                            if($praktik !== '') { $rata += $praktik; $count++; }
                                            $rata = $count > 0 ? round($rata / $count, 2) : 0;
                                            
                                            $grade = '';
                                            $grade_class = '';
                                            if($rata >= 85) { $grade = 'A'; $grade_class = 'success'; }
                                            elseif($rata >= 75) { $grade = 'B'; $grade_class = 'info'; }
                                            elseif($rata >= 65) { $grade = 'C'; $grade_class = 'warning'; }
                                            elseif($rata > 0) { $grade = 'D'; $grade_class = 'danger'; }
                                            else { $grade = '-'; $grade_class = 'secondary'; }
                                        ?>
                                        <tr>
                                            <td class="text-center"><?= $no++ ?> </div>
                                            <td><strong><?= htmlspecialchars($siswa['name']) ?></strong> </div>
                                            <td><?= htmlspecialchars($siswa['nis']) ?> </div>
                                            <td class="nilai-cell">
                                                <input type="number" step="0.01" name="tugas[<?= $siswa['id'] ?>]" class="form-control nilai-input" value="<?= $tugas ?>" placeholder="0-100" style="width:80px">
                                            </div>
                                            <td class="nilai-cell">
                                                <input type="number" step="0.01" name="ulangan_harian[<?= $siswa['id'] ?>]" class="form-control nilai-input" value="<?= $ulangan ?>" placeholder="0-100" style="width:80px">
                                            </div>
                                            <td class="nilai-cell">
                                                <input type="number" step="0.01" name="uts[<?= $siswa['id'] ?>]" class="form-control nilai-input" value="<?= $uts ?>" placeholder="0-100" style="width:80px">
                                            </div>
                                            <td class="nilai-cell">
                                                <input type="number" step="0.01" name="uas[<?= $siswa['id'] ?>]" class="form-control nilai-input" value="<?= $uas ?>" placeholder="0-100" style="width:80px">
                                            </div>
                                            <td class="nilai-cell">
                                                <input type="number" step="0.01" name="praktik[<?= $siswa['id'] ?>]" class="form-control nilai-input" value="<?= $praktik ?>" placeholder="0-100" style="width:80px">
                                            </div>
                                            <td class="text-center"><strong><?= $rata ?></strong> </div>
                                            <td class="text-center"><span class="badge bg-<?= $grade_class ?>"><?= $grade ?></span> </div>
                                         </div>
                                        <?php endforeach; ?>
                                    </tbody>
                                    <tfoot class="table-secondary">
                                        <tr>
                                            <td colspan="10" class="text-right">
                                                <button type="submit" name="simpan_nilai" class="btn btn-save">
                                                    <i class="fas fa-save"></i> Simpan Semua Nilai
                                                </button>
                                            </div>
                                         </div>
                                    </tfoot>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                <?php elseif($selected_class > 0 && $selected_mapel && count($siswa_list) == 0 && !$edit_id): ?>
                <div class="alert alert-warning">
                    <i class="fas fa-exclamation-triangle"></i> Belum ada siswa di kelas ini.
                </div>
                <?php elseif($selected_class > 0 && !$selected_mapel && !$edit_id): ?>
                <div class="alert alert-info">
                    <i class="fas fa-info-circle"></i> Silakan pilih mata pelajaran terlebih dahulu.
                </div>
                <?php endif; ?>

                <!-- Daftar Nilai yang Sudah Diinput (Semua Unit) -->
                <div class="card">
                    <div class="card-header">
                        <h4><i class="fas fa-history"></i> Riwayat Nilai Siswa</h4>
                    </div>
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-bordered mb-0">
                                <thead>
                                    <tr>
                                        <th>No</th>
                                        <th>Siswa</th>
                                        <th>Kelas</th>
                                        <th>Unit</th>
                                        <th>Mapel</th>
                                        <th>Tugas</th>
                                        <th>Ulangan</th>
                                        <th>UTS</th>
                                        <th>UAS</th>
                                        <th>Praktik</th>
                                        <th>Rata-rata</th>
                                        <th>Aksi</th>
                                     </div>
                                </thead>
                                <tbody>
                                    <?php if($nilai_list && mysqli_num_rows($nilai_list) > 0): ?>
                                        <?php $no=1; while($row = mysqli_fetch_assoc($nilai_list)): 
                                            $rata = 0;
                                            $count = 0;
                                            if($row['tugas']) { $rata += $row['tugas']; $count++; }
                                            if($row['ulangan_harian']) { $rata += $row['ulangan_harian']; $count++; }
                                            if($row['uts']) { $rata += $row['uts']; $count++; }
                                            if($row['uas']) { $rata += $row['uas']; $count++; }
                                            if($row['praktik']) { $rata += $row['praktik']; $count++; }
                                            $rata = $count > 0 ? round($rata / $count, 2) : 0;
                                        ?>
                                        <tr>
                                            <td class="text-center"><?= $no++ ?> </div>
                                            <td><?= htmlspecialchars($row['student_name']) ?> </div>
                                            <td><?= htmlspecialchars($row['class_name']) ?> </div>
                                            <td><span class="badge badge-unit bg-secondary"><?= htmlspecialchars($row['unit'] ?? '-') ?></span> </div>
                                            <td><?= htmlspecialchars($row['mata_pelajaran']) ?> </div>
                                            <td class="text-center"><?= $row['tugas'] ?? '-' ?> </div>
                                            <td class="text-center"><?= $row['ulangan_harian'] ?? '-' ?> </div>
                                            <td class="text-center"><?= $row['uts'] ?? '-' ?> </div>
                                            <td class="text-center"><?= $row['uas'] ?? '-' ?> </div>
                                            <td class="text-center"><?= $row['praktik'] ?? '-' ?> </div>
                                            <td class="text-center"><strong><?= $rata ?></strong> </div>
                                            <td class="text-center">
                                                <div class="btn-group" role="group">
                                                    <a href="?edit=<?= $row['id'] ?>" class="btn btn-sm btn-edit">
                                                        <i class="fas fa-edit"></i> Edit
                                                    </a>
                                                    <a href="?hapus=<?= $row['id'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('Yakin hapus?')">
                                                        <i class="fas fa-trash"></i> Hapus
                                                    </a>
                                                </div>
                                            </div>
                                         </div>
                                        <?php endwhile; ?>
                                    <?php else: ?>
                                        <td><td colspan="12" class="text-center">Belum ada data nilai</div>
                                    <?php endif; ?>
                                </tbody>
                             </div>
                        </div>
                    </div>
                </div>

                <!-- Tabel Rekap Nilai (Semua Unit) -->
                <div class="card">
                    <div class="card-header bg-secondary text-white">
                        <h4><i class="fas fa-chart-bar"></i> Rekap Nilai Siswa (Semua Unit)</h4>
                    </div>
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-bordered mb-0">
                                <thead>
                                    <tr>
                                        <th>No</th>
                                        <th>Siswa</th>
                                        <th>Kelas</th>
                                        <th>Unit</th>
                                        <th>Mapel</th>
                                        <th>Tugas</th>
                                        <th>Ulangan</th>
                                        <th>UTS</th>
                                        <th>UAS</th>
                                        <th>Praktik</th>
                                        <th>Rata-rata</th>
                                     </div>
                                </thead>
                                <tbody>
                                    <?php if($rekap_data && mysqli_num_rows($rekap_data) > 0): ?>
                                        <?php $no=1; while($row = mysqli_fetch_assoc($rekap_data)): ?>
                                        <tr>
                                            <td class="text-center"><?= $no++ ?> </div>
                                            <td><?= htmlspecialchars($row['student_name']) ?> </div>
                                            <td><?= htmlspecialchars($row['class_name']) ?> </div>
                                            <td><span class="badge badge-unit bg-secondary"><?= htmlspecialchars($row['unit']) ?></span> </div>
                                            <td><?= htmlspecialchars($row['mata_pelajaran']) ?> </div>
                                            <td class="text-center"><?= $row['tugas'] ?? '-' ?> </div>
                                            <td class="text-center"><?= $row['ulangan_harian'] ?? '-' ?> </div>
                                            <td class="text-center"><?= $row['uts'] ?? '-' ?> </div>
                                            <td class="text-center"><?= $row['uas'] ?? '-' ?> </div>
                                            <td class="text-center"><?= $row['praktik'] ?? '-' ?> </div>
                                            <td class="text-center"><strong><?= round($row['rata_rata'] ?? 0, 2) ?></strong> </div>
                                         </div>
                                        <?php endwhile; ?>
                                    <?php else: ?>
                                        <td><td colspan="11" class="text-center">Belum ada data rekap nilai</div>
                                    <?php endif; ?>
                                </tbody>
                             </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <footer class="main-footer">
        <strong>&copy; <?= date('Y') ?> SIM ISTIQLAL - Sistem Administrasi Guru</strong>
    </footer>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/admin-lte@3.2/dist/js/adminlte.min.js"></script>
<script>
$(document).ready(function() {
    $('.nilai-input').on('input', function() {
        var row = $(this).closest('tr');
        var tugas = parseFloat(row.find('input[name^="tugas"]').val()) || 0;
        var ulangan = parseFloat(row.find('input[name^="ulangan_harian"]').val()) || 0;
        var uts = parseFloat(row.find('input[name^="uts"]').val()) || 0;
        var uas = parseFloat(row.find('input[name^="uas"]').val()) || 0;
        var praktik = parseFloat(row.find('input[name^="praktik"]').val()) || 0;
        
        var count = 0;
        var total = 0;
        if(tugas > 0) { total += tugas; count++; }
        if(ulangan > 0) { total += ulangan; count++; }
        if(uts > 0) { total += uts; count++; }
        if(uas > 0) { total += uas; count++; }
        if(praktik > 0) { total += praktik; count++; }
        
        var rata = count > 0 ? (total / count).toFixed(2) : 0;
        row.find('td:eq(8)').html('<strong>' + rata + '</strong>');
        
        var grade = '';
        var gradeClass = '';
        if(rata >= 85) { grade = 'A'; gradeClass = 'success'; }
        else if(rata >= 75) { grade = 'B'; gradeClass = 'info'; }
        else if(rata >= 65) { grade = 'C'; gradeClass = 'warning'; }
        else if(rata > 0) { grade = 'D'; gradeClass = 'danger'; }
        else { grade = '-'; gradeClass = 'secondary'; }
        
        row.find('td:eq(9)').html('<span class="badge bg-' + gradeClass + '">' + grade + '</span>');
    });
});
</script>
</body>
</html>