<?php
require_once 'config/session.php';
require_once 'config/database.php';
checkLogin();

$database = new Database();
$conn = $database->getConnection();
$currentUser = getCurrentUser();

// Get subjects
$query = "SELECT * FROM mata_pelajaran ORDER BY nama_mapel ASC";
$stmt = $conn->prepare($query);
$stmt->execute();
$subjects = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get assignments for grades
$assignments = [];
if ($currentUser['id_kelas']) {
    $query = "SELECT t.*, m.nama_mapel 
              FROM tugas t 
              JOIN mata_pelajaran m ON t.id_mapel = m.id_mapel 
              WHERE t.id_kelas = :id_kelas 
              ORDER BY t.tanggal_mulai DESC";
    $stmt = $conn->prepare($query);
    $stmt->bindParam(':id_kelas', $currentUser['id_kelas']);
    $stmt->execute();
    $assignments = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Get students
$students = [];
if ($currentUser['id_kelas']) {
    $query = "SELECT * FROM siswa WHERE id_kelas = :id_kelas AND status = 'aktif' ORDER BY nama_siswa ASC";
    $stmt = $conn->prepare($query);
    $stmt->bindParam(':id_kelas', $currentUser['id_kelas']);
    $stmt->execute();
    $students = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Handle grade submission
$message = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['submit_grades'])) {
    $id_tugas = $_POST['id_tugas'];
    
    $conn->beginTransaction();
    try {
        foreach ($_POST['grades'] as $id_siswa => $nilai) {
            if ($nilai !== '') {
                $keterangan = $_POST['keterangan'][$id_siswa] ?? '';
                
                $query = "INSERT INTO nilai_tugas (id_tugas, id_siswa, nilai, keterangan) 
                          VALUES (:id_tugas, :id_siswa, :nilai, :keterangan) 
                          ON DUPLICATE KEY UPDATE nilai = :nilai2, keterangan = :keterangan2";
                
                $stmt = $conn->prepare($query);
                $stmt->bindParam(':id_tugas', $id_tugas);
                $stmt->bindParam(':id_siswa', $id_siswa);
                $stmt->bindParam(':nilai', $nilai);
                $stmt->bindParam(':keterangan', $keterangan);
                $stmt->bindParam(':nilai2', $nilai);
                $stmt->bindParam(':keterangan2', $keterangan);
                $stmt->execute();
            }
        }
        
        $conn->commit();
        $message = "Nilai berhasil disimpan!";
    } catch (Exception $e) {
        $conn->rollback();
        $message = "Gagal menyimpan nilai: " . $e->getMessage();
    }
}

// Get grades for selected assignment
$selected_assignment = $_GET['assignment'] ?? null;
$grades = [];
if ($selected_assignment) {
    $query = "SELECT s.id_siswa, s.nis, s.nama_siswa, nt.nilai, nt.keterangan 
              FROM siswa s 
              LEFT JOIN nilai_tugas nt ON s.id_siswa = nt.id_siswa AND nt.id_tugas = :id_tugas 
              WHERE s.id_kelas = :id_kelas AND s.status = 'aktif' 
              ORDER BY s.nama_siswa ASC";
    $stmt = $conn->prepare($query);
    $stmt->bindParam(':id_tugas', $selected_assignment);
    $stmt->bindParam(':id_kelas', $currentUser['id_kelas']);
    $stmt->execute();
    $grades = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Nilai - Sistem Guru Kelas SD</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
</head>
<body class="bg-gray-50">
    <!-- Navigation -->
    <?php require_once 'includes/navbar.php'; ?>
    
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <!-- Header -->
        <div class="flex justify-between items-center mb-6">
            <h1 class="text-3xl font-bold text-gray-800">Nilai Tugas</h1>
            <div class="flex space-x-4">
                <a href="export_nilai.php" class="bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700 transition">
                    <i class="fas fa-file-excel mr-2"></i>Export Excel
                </a>
                <a href="export_absensi.php" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition">
                    <i class="fas fa-file-excel mr-2"></i>Export Absensi
                </a>
            </div>
        </div>

        <!-- Success Message -->
        <?php if ($message): ?>
        <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-4">
            <i class="fas fa-check-circle mr-2"></i><?= $message ?>
        </div>
        <?php endif; ?>

        <!-- Assignment Selection -->
        <div class="bg-white rounded-lg shadow-md p-6 mb-6">
            <h2 class="text-xl font-bold text-gray-800 mb-4">Pilih Tugas</h2>
            <form method="GET" class="flex space-x-4">
                <select name="assignment" class="flex-1 rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                    <option value="">Pilih Tugas</option>
                    <?php foreach ($assignments as $assignment): ?>
                        <option value="<?= $assignment['id_tugas'] ?>" <?= $selected_assignment == $assignment['id_tugas'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($assignment['nama_mapel']) ?> - <?= htmlspecialchars($assignment['judul_tugas']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <button type="submit" class="bg-indigo-600 text-white px-4 py-2 rounded-lg hover:bg-indigo-700">
                    <i class="fas fa-search mr-2"></i>Lihat Nilai
                </button>
            </form>
        </div>

        <!-- Grades Form -->
        <?php if ($selected_assignment && !empty($students)): ?>
        <div class="bg-white rounded-lg shadow-md p-6">
            <h2 class="text-xl font-bold text-gray-800 mb-4">Input Nilai</h2>
            <form method="POST">
                <input type="hidden" name="submit_grades" value="1">
                <input type="hidden" name="id_tugas" value="<?= $selected_assignment ?>">
                
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">No</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">NIS</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Nama Siswa</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Nilai</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Keterangan</th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200">
                            <?php foreach ($grades as $index => $student): ?>
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900"><?= $index + 1 ?></td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900"><?= htmlspecialchars($student['nis']) ?></td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"><?= htmlspecialchars($student['nama_siswa']) ?></td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <input type="number" name="grades[<?= $student['id_siswa'] ?>]" 
                                           value="<?= $student['nilai'] ?? '' ?>"
                                           min="0" max="100" step="0.5"
                                           class="w-20 rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <input type="text" name="keterangan[<?= $student['id_siswa'] ?>]" 
                                           value="<?= htmlspecialchars($student['keterangan'] ?? '') ?>"
                                           class="rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 w-full"
                                           placeholder="Keterangan">
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                
                <div class="mt-6">
                    <button type="submit" class="bg-indigo-600 text-white px-6 py-2 rounded-lg hover:bg-indigo-700">
                        <i class="fas fa-save mr-2"></i>Simpan Nilai
                    </button>
                </div>
            </form>
        </div>
        <?php endif; ?>
    </div>
</body>
</html>
