<?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_pg, nh.nilai_uraian, nh.nilai_praktik, nh.nilai_pengetahuan, nh.nilai_adab, nh.nilai_akhir, 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_pg) as rata_pg, 
              AVG(nh.nilai_uraian) as rata_uraian, 
              AVG(nh.nilai_praktik) as rata_praktik, 
              AVG(nh.nilai_pengetahuan) as rata_pengetahuan, 
              AVG(nh.nilai_adab) as rata_adab, 
              AVG(nh.nilai_akhir) as rata_akhir, 
              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 Komponen - 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 Komponen</h1>
            <a href="nilai_komponen.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" id="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" id="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" id="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>
        
        <!-- Export Section -->
        <div class="mt-4 pt-4 border-t border-gray-200">
            <h3 class="text-sm font-medium text-gray-700 mb-2">Export ke Excel:</h3>
            <div class="flex flex-wrap gap-2">
                <button onclick="exportMonthly()" class="bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700 text-sm">
                    <i class="fas fa-file-excel mr-2"></i>Export Bulanan
                </button>
                <button onclick="showWeeklyModal()" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 text-sm">
                    <i class="fas fa-calendar-week mr-2"></i>Export Mingguan
                </button>
            </div>
        </div>
    </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_akhir')) / 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 Komponen - <?= 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">PG</th>
                            <th class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">Uraian</th>
                            <th class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">Praktik</th>
                            <th class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">Pengetahuan</th>
                            <th class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">Adab</th>
                            <th class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">Akhir</th>
                            <th class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">Total</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"><?= number_format($item['rata_pg'], 1) ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-center"><?= number_format($item['rata_uraian'], 1) ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-center"><?= number_format($item['rata_praktik'], 1) ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-center"><?= number_format($item['rata_pengetahuan'], 1) ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-center"><?= number_format($item['rata_adab'], 1) ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-center font-medium"><?= number_format($item['rata_akhir'], 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 Komponen</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">PG</th>
                            <th class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">Uraian</th>
                            <th class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">Praktik</th>
                            <th class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">Pengetahuan</th>
                            <th class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">Adab</th>
                            <th class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">Akhir</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"><?= number_format($grade['nilai_pg'], 1) ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-center"><?= number_format($grade['nilai_uraian'], 1) ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-center"><?= number_format($grade['nilai_praktik'], 1) ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-center"><?= number_format($grade['nilai_pengetahuan'], 1) ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-center"><?= number_format($grade['nilai_adab'], 1) ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-center font-medium"><?= number_format($grade['nilai_akhir'], 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>
    <!-- Weekly Export Modal -->
    <div id="weeklyModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden z-50">
        <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
            <div class="mt-3">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="text-lg font-medium text-gray-900">Export Mingguan</h3>
                    <button onclick="closeWeeklyModal()" class="text-gray-400 hover:text-gray-600">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <form id="weeklyForm" onsubmit="exportWeekly(event)">
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-2">Tanggal Mulai</label>
                        <input type="date" id="start_date" name="start_date" class="w-full px-3 py-2 border border-gray-300 rounded-md" required>
                    </div>
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-2">Tanggal Selesai</label>
                        <input type="date" id="end_date" name="end_date" class="w-full px-3 py-2 border border-gray-300 rounded-md" required>
                    </div>
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-2">Mata Pelajaran</label>
                        <select id="modal_id_mapel" name="id_mapel" class="w-full px-3 py-2 border border-gray-300 rounded-md">
                            <option value="">Semua Mata Pelajaran</option>
                            <?php foreach ($subjects as $subject): ?>
                                <option value="<?= $subject['id_mapel'] ?>"><?= htmlspecialchars($subject['nama_mapel']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="flex justify-end space-x-2">
                        <button type="button" onclick="closeWeeklyModal()" class="px-4 py-2 bg-gray-300 text-gray-700 rounded-md hover:bg-gray-400">
                            Batal
                        </button>
                        <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">
                            <i class="fas fa-download mr-2"></i>Export
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        // Export monthly data
        function exportMonthly() {
            const bulan = document.getElementById('bulan').value;
            const tahun = document.getElementById('tahun').value;
            const id_mapel = document.getElementById('id_mapel').value;
            
            const url = `export_nilai_komponen.php?export_type=monthly&bulan=${bulan}&tahun=${tahun}&id_mapel=${id_mapel}`;
            window.open(url, '_blank');
        }

        // Show weekly export modal
        function showWeeklyModal() {
            document.getElementById('weeklyModal').classList.remove('hidden');
            
            // Set default dates (current week)
            const today = new Date();
            const startOfWeek = new Date(today);
            startOfWeek.setDate(today.getDate() - today.getDay());
            const endOfWeek = new Date(startOfWeek);
            endOfWeek.setDate(startOfWeek.getDate() + 6);
            
            document.getElementById('start_date').value = startOfWeek.toISOString().split('T')[0];
            document.getElementById('end_date').value = endOfWeek.toISOString().split('T')[0];
            
            // Sync subject selection
            const mainMapel = document.getElementById('id_mapel').value;
            document.getElementById('modal_id_mapel').value = mainMapel;
        }

        // Close weekly export modal
        function closeWeeklyModal() {
            document.getElementById('weeklyModal').classList.add('hidden');
        }

        // Export weekly data
        function exportWeekly(event) {
            event.preventDefault();
            
            const start_date = document.getElementById('start_date').value;
            const end_date = document.getElementById('end_date').value;
            const id_mapel = document.getElementById('modal_id_mapel').value;
            
            const url = `export_nilai_komponen.php?export_type=weekly&start_date=${start_date}&end_date=${end_date}&id_mapel=${id_mapel}`;
            window.open(url, '_blank');
            closeWeeklyModal();
        }

        // Close modal when clicking outside
        window.onclick = function(event) {
            const modal = document.getElementById('weeklyModal');
            if (event.target == modal) {
                closeWeeklyModal();
            }
        }
    </script>
</body>
</html>
