<?php
require_once 'config/session.php';
require_once 'config/database.php';
require_once 'config/functions.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 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 form submission
$message = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['submit_nilai'])) {
    $id_mapel = $_POST['id_mapel'];
    $tanggal = $_POST['tanggal'];
    $jenis_penilaian = $_POST['jenis_penilaian'];
    
    $conn->beginTransaction();
    try {
        foreach ($_POST['nilai'] as $id_siswa => $nilai) {
            if ($nilai !== '') {
                $keterangan = $_POST['keterangan'][$id_siswa] ?? '';
                
                $query = "INSERT INTO nilai_harian (id_siswa, id_mapel, tanggal, nilai, jenis_penilaian, keterangan) 
                          VALUES (:id_siswa, :id_mapel, :tanggal, :nilai, :jenis_penilaian, :keterangan) 
                          ON DUPLICATE KEY UPDATE nilai = :nilai2, keterangan = :keterangan2";
                
                $stmt = $conn->prepare($query);
                $stmt->bindParam(':id_siswa', $id_siswa);
                $stmt->bindParam(':id_mapel', $id_mapel);
                $stmt->bindParam(':tanggal', $tanggal);
                $stmt->bindParam(':nilai', $nilai);
                $stmt->bindParam(':jenis_penilaian', $jenis_penilaian);
                $stmt->bindParam(':keterangan', $keterangan);
                $stmt->bindParam(':nilai2', $nilai);
                $stmt->bindParam(':keterangan2', $keterangan);
                $stmt->execute();
            }
        }
        
        $conn->commit();
        $message = "Nilai harian berhasil disimpan!";
    } catch (Exception $e) {
        $conn->rollback();
        $message = "Gagal menyimpan nilai: " . $e->getMessage();
    }
}

// Get existing daily grades
$existing_grades = [];
if (isset($_GET['tanggal']) && isset($_GET['id_mapel']) && isset($_GET['jenis'])) {
    $tanggal = $_GET['tanggal'];
    $id_mapel = $_GET['id_mapel'];
    $jenis_penilaian = $_GET['jenis'];
    
    $query = "SELECT nh.*, s.nis, s.nama_siswa 
              FROM nilai_harian nh
              JOIN siswa s ON nh.id_siswa = s.id_siswa
              WHERE nh.id_mapel = :id_mapel AND nh.tanggal = :tanggal AND nh.jenis_penilaian = :jenis_penilaian
              AND s.id_kelas = :id_kelas
              ORDER BY s.nama_siswa ASC";
    
    $stmt = $conn->prepare($query);
    $stmt->bindParam(':id_mapel', $id_mapel);
    $stmt->bindParam(':tanggal', $tanggal);
    $stmt->bindParam(':jenis_penilaian', $jenis_penilaian);
    $stmt->bindParam(':id_kelas', $currentUser['id_kelas']);
    $stmt->execute();
    $existing_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 Harian - 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 Harian Siswa</h1>
            <a href="rekap_nilai_harian.php" class="bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700 transition">
                <i class="fas fa-file-alt mr-2"></i>Rekap Nilai
            </a>
        </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; ?>

        <!-- Filter Form -->
        <div class="bg-white rounded-lg shadow-md p-6 mb-6">
            <h2 class="text-xl font-bold text-gray-800 mb-4">Filter Nilai Harian</h2>
            <form method="GET" class="grid grid-cols-1 md:grid-cols-4 gap-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700">Tanggal</label>
                    <input type="date" name="tanggal" value="<?= $_GET['tanggal'] ?? date('Y-m-d') ?>" 
                           class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700">Mata Pelajaran</label>
                    <select name="id_mapel" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                        <option value="">Pilih Mata Pelajaran</option>
                        <?php foreach ($subjects as $subject): ?>
                            <option value="<?= $subject['id_mapel'] ?>" <?= isset($_GET['id_mapel']) && $_GET['id_mapel'] == $subject['id_mapel'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($subject['nama_mapel']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700">Jenis Penilaian</label>
                    <select name="jenis" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                        <option value="">Pilih Jenis</option>
                        <option value="tugas" <?= isset($_GET['jenis']) && $_GET['jenis'] == 'tugas' ? 'selected' : '' ?>>Tugas</option>
                        <option value="ulangan" <?= isset($_GET['jenis']) && $_GET['jenis'] == 'ulangan' ? 'selected' : '' ?>>Ulangan</option>
                        <option value="praktik" <?= isset($_GET['jenis']) && $_GET['jenis'] == 'praktik' ? 'selected' : '' ?>>Praktik</option>
                        <option value="sikap" <?= isset($_GET['jenis']) && $_GET['jenis'] == 'sikap' ? 'selected' : '' ?>>Sikap</option>
                    </select>
                </div>
                <div class="flex items-end">
                    <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>Tampilkan
                    </button>
                </div>
            </form>
        </div>

        <!-- Input Form -->
        <div class="bg-white rounded-lg shadow-md p-6">
            <h2 class="text-xl font-bold text-gray-800 mb-4">Input Nilai Harian</h2>
            <form method="POST">
                <input type="hidden" name="submit_nilai" value="1">
                
                <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700">Tanggal</label>
                        <input type="date" name="tanggal" value="<?= $_GET['tanggal'] ?? date('Y-m-d') ?>" required
                               class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700">Mata Pelajaran</label>
                        <select name="id_mapel" required class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                            <option value="">Pilih Mata Pelajaran</option>
                            <?php foreach ($subjects as $subject): ?>
                                <option value="<?= $subject['id_mapel'] ?>"><?= htmlspecialchars($subject['nama_mapel']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700">Jenis Penilaian</label>
                        <select name="jenis_penilaian" required class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                            <option value="">Pilih Jenis</option>
                            <option value="tugas">Tugas</option>
                            <option value="ulangan">Ulangan</option>
                            <option value="praktik">Praktik</option>
                            <option value="sikap">Sikap</option>
                        </select>
                    </div>
                </div>

                <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 ($students as $index => $student): ?>
                            <?php 
                                $existing_grade = null;
                                foreach ($existing_grades as $grade) {
                                    if ($grade['id_siswa'] == $student['id_siswa']) {
                                        $existing_grade = $grade;
                                        break;
                                    }
                                }
                            ?>
                            <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="nilai[<?= $student['id_siswa'] ?>]" 
                                           value="<?= $existing_grade['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($existing_grade['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>
    </div>
</body>
</html>
