<?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 filter parameters
$bulan = $_GET['bulan'] ?? date('m');
$tahun = $_GET['tahun'] ?? date('Y');
$id_mapel = $_GET['id_mapel'] ?? '';

// Build query
$query = "SELECT s.nis, s.nama_siswa, m.nama_mapel, nh.tanggal, nh.nilai, nh.jenis_penilaian, nh.keterangan
          FROM nilai_harian nh
          JOIN siswa s ON nh.id_siswa = s.id_siswa
          JOIN mata_pelajaran m ON nh.id_mapel = m.id_mapel
          WHERE s.id_kelas = :id_kelas AND MONTH(nh.tanggal) = :bulan AND YEAR(nh.tanggal) = :tahun";

$params = [':id_kelas' => $currentUser['id_kelas'], ':bulan' => $bulan, ':tahun' => $tahun];

if ($id_mapel) {
    $query .= " AND nh.id_mapel = :id_mapel";
    $params[':id_mapel'] = $id_mapel;
}

$query .= " ORDER BY nh.tanggal DESC, s.nama_siswa ASC";

$stmt = $conn->prepare($query);
foreach ($params as $key => $value) {
    $stmt->bindValue($key, $value);
}
$stmt->execute();
$grades = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get summary by student
$summary = [];
if ($currentUser['id_kelas']) {
    $query = "SELECT s.nis, s.nama_siswa, m.nama_mapel, AVG(nh.nilai) as rata_rata, COUNT(*) as total_nilai
              FROM nilai_harian nh
              JOIN siswa s ON nh.id_siswa = s.id_siswa
              JOIN mata_pelajaran m ON nh.id_mapel = m.id_mapel
              WHERE s.id_kelas = :id_kelas AND MONTH(nh.tanggal) = :bulan AND YEAR(nh.tanggal) = :tahun";
    
    if ($id_mapel) {
        $query .= " AND nh.id_mapel = :id_mapel";
    }
    
    $query .= " GROUP BY s.id_siswa, s.nis, s.nama_siswa, m.id_mapel, m.nama_mapel
                ORDER BY s.nama_siswa ASC";
    
    $stmt = $conn->prepare($query);
    foreach ($params as $key => $value) {
        $stmt->bindValue($key, $value);
    }
    $stmt->execute();
    $summary = $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>Rekap 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">Rekap Nilai Harian</h1>
            <a href="nilai_harian.php" class="bg-indigo-600 text-white px-4 py-2 rounded-lg hover:bg-indigo-700 transition">
                <i class="fas fa-plus mr-2"></i>Tambah Nilai
            </a>
        </div>

        <!-- Filter Form -->
        <div class="bg-white rounded-lg shadow-md p-6 mb-6">
            <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">Bulan</label>
                    <select name="bulan" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                        <?php for ($i = 1; $i <= 12; $i++): ?>
                            <option value="<?= $i ?>" <?= $bulan == $i ? 'selected' : '' ?>>
                                <?= getMonthName($i) ?>
                            </option>
                        <?php endfor; ?>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700">Tahun</label>
                    <select name="tahun" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                        <?php for ($i = date('Y') - 2; $i <= date('Y') + 1; $i++): ?>
                            <option value="<?= $i ?>" <?= $tahun == $i ? 'selected' : '' ?>>
                                <?= $i ?>
                            </option>
                        <?php endfor; ?>
                    </select>
                </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="">Semua Mata Pelajaran</option>
                        <?php foreach ($subjects as $subject): ?>
                            <option value="<?= $subject['id_mapel'] ?>" <?= $id_mapel == $subject['id_mapel'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($subject['nama_mapel']) ?>
                            </option>
                        <?php endforeach; ?>
                    </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>

        <!-- Summary Cards -->
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-6">
            <div class="bg-white rounded-lg shadow-md p-6 text-center">
                <div class="text-2xl font-bold text-blue-600"><?= count($grades) ?></div>
                <div class="text-sm text-gray-600">Total Nilai</div>
            </div>
            <div class="bg-white rounded-lg shadow-md p-6 text-center">
                <div class="text-2xl font-bold text-green-600">
                    <?= count($summary) > 0 ? number_format(array_sum(array_column($summary, 'rata_rata')) / count($summary), 1) : 0 ?>
                </div>
                <div class="text-sm text-gray-600">Rata-rata Keseluruhan</div>
            </div>
            <div class="bg-white rounded-lg shadow-md p-6 text-center">
                <div class="text-2xl font-bold text-purple-600"><?= count($summary) ?></div>
                <div class="text-sm text-gray-600">Siswa Dinilai</div>
            </div>
        </div>

        <!-- Summary Table -->
        <div class="bg-white rounded-lg shadow-md p-6 mb-6">
            <h2 class="text-xl font-bold text-gray-800 mb-4">Ringkasan Nilai - <?= getMonthName($bulan) ?> <?= $tahun ?></h2>
            <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">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">Mata Pelajaran</th>
                            <th class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">Rata-rata</th>
                            <th class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">Total Nilai</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        <?php foreach ($summary as $item): ?>
                        <tr>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900"><?= htmlspecialchars($item['nis']) ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"><?= htmlspecialchars($item['nama_siswa']) ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900"><?= htmlspecialchars($item['nama_mapel']) ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-center font-medium"><?= number_format($item['rata_rata'], 1) ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-center"><?= $item['total_nilai'] ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Detailed Grades Table -->
        <div class="bg-white rounded-lg shadow-md p-6">
            <h2 class="text-xl font-bold text-gray-800 mb-4">Detail Nilai Harian</h2>
            <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">Tanggal</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">Mata Pelajaran</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Jenis</th>
                            <th class="px-6 py-3 text-center 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 $grade): ?>
                        <tr>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900"><?= formatDate($grade['tanggal']) ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900"><?= htmlspecialchars($grade['nis']) ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"><?= htmlspecialchars($grade['nama_siswa']) ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900"><?= htmlspecialchars($grade['nama_mapel']) ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900"><?= ucfirst($grade['jenis_penilaian']) ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-center font-medium"><?= number_format($grade['nilai'], 1) ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900"><?= htmlspecialchars($grade['keterangan'] ?? '-') ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</body>
</html>
