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

// Get students with attendance summary
$students = [];
if ($currentUser['id_kelas']) {
    $query = "SELECT s.id_siswa, s.nis, s.nama_siswa,
              COUNT(CASE WHEN a.status = 'hadir' THEN 1 END) as hadir,
              COUNT(CASE WHEN a.status = 'sakit' THEN 1 END) as sakit,
              COUNT(CASE WHEN a.status = 'izin' THEN 1 END) as izin,
              COUNT(CASE WHEN a.status = 'alpa' THEN 1 END) as alpa,
              COUNT(*) as total_hari
              FROM siswa s
              LEFT JOIN absensi a ON s.id_siswa = a.id_siswa 
                  AND MONTH(a.tanggal) = :bulan AND YEAR(a.tanggal) = :tahun
              WHERE s.id_kelas = :id_kelas AND s.status = 'aktif'
              GROUP BY s.id_siswa, s.nis, s.nama_siswa
              ORDER BY s.nama_siswa ASC";
    
    $stmt = $conn->prepare($query);
    $stmt->bindParam(':bulan', $bulan);
    $stmt->bindParam(':tahun', $tahun);
    $stmt->bindParam(':id_kelas', $currentUser['id_kelas']);
    $stmt->execute();
    $students = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Get detailed attendance records
$attendance_details = [];
if ($currentUser['id_kelas']) {
    $query = "SELECT a.*, s.nis, s.nama_siswa 
              FROM absensi a
              JOIN siswa s ON a.id_siswa = s.id_siswa
              WHERE s.id_kelas = :id_kelas AND MONTH(a.tanggal) = :bulan AND YEAR(a.tanggal) = :tahun
              ORDER BY a.tanggal DESC, s.nama_siswa ASC";
    
    $stmt = $conn->prepare($query);
    $stmt->bindParam(':bulan', $bulan);
    $stmt->bindParam(':tahun', $tahun);
    $stmt->bindParam(':id_kelas', $currentUser['id_kelas']);
    $stmt->execute();
    $attendance_details = $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 Absensi - 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 -->
    <nav class="bg-white shadow-lg">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between h-16">
                <div class="flex items-center">
                    <a href="dashboard.php" class="flex items-center">
                        <i class="fas fa-chalkboard-teacher text-indigo-600 text-2xl mr-3"></i>
                        <span class="text-xl font-bold text-gray-800">Sistem Guru Kelas SD</span>
                    </a>
                </div>
                <div class="flex items-center space-x-4">
                    <span class="text-gray-700">Kelas: <?= htmlspecialchars($currentUser['nama_kelas'] ?? 'Belum ditentukan') ?></span>
                    <a href="dashboard.php" class="text-gray-600 hover:text-indigo-600">
                        <i class="fas fa-home"></i>
                    </a>
                    <a href="logout.php" class="text-red-600 hover:text-red-800">
                        <i class="fas fa-sign-out-alt"></i>
                    </a>
                </div>
            </div>
        </div>
    </nav>

    <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 Absensi</h1>
            <a href="export_absensi.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>
        </div>

        <!-- Filter Form -->
        <div class="bg-white rounded-lg shadow-md p-6 mb-6">
            <form method="GET" class="flex space-x-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700">Bulan</label>
                    <select name="bulan" class="mt-1 block 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 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 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-4 gap-6 mb-6">
            <div class="bg-white rounded-lg shadow-md p-6 text-center">
                <div class="text-2xl font-bold text-green-600">
                    <?= array_sum(array_column($students, 'hadir')) ?>
                </div>
                <div class="text-sm text-gray-600">Total Hadir</div>
            </div>
            <div class="bg-white rounded-lg shadow-md p-6 text-center">
                <div class="text-2xl font-bold text-yellow-600">
                    <?= array_sum(array_column($students, 'sakit')) ?>
                </div>
                <div class="text-sm text-gray-600">Total Sakit</div>
            </div>
            <div class="bg-white rounded-lg shadow-md p-6 text-center">
                <div class="text-2xl font-bold text-blue-600">
                    <?= array_sum(array_column($students, 'izin')) ?>
                </div>
                <div class="text-sm text-gray-600">Total Izin</div>
            </div>
            <div class="bg-white rounded-lg shadow-md p-6 text-center">
                <div class="text-2xl font-bold text-red-600">
                    <?= array_sum(array_column($students, 'alpa')) ?>
                </div>
                <div class="text-sm text-gray-600">Total Alpa</div>
            </div>
        </div>

        <!-- Attendance 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 Absensi - <?= 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">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-center text-xs font-medium text-gray-500 uppercase tracking-wider">Hadir</th>
                            <th class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">Sakit</th>
                            <th class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">Izin</th>
                            <th class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">Alpa</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 ($students 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 text-sm text-center text-green-600"><?= $student['hadir'] ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-center text-yellow-600"><?= $student['sakit'] ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-center text-blue-600"><?= $student['izin'] ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-center text-red-600"><?= $student['alpa'] ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-center font-medium"><?= $student['total_hari'] ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Detailed Attendance Records -->
        <div class="bg-white rounded-lg shadow-md p-6">
            <h2 class="text-xl font-bold text-gray-800 mb-4">Detail Absensi</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-center text-xs font-medium text-gray-500 uppercase tracking-wider">Status</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 ($attendance_details as $record): ?>
                        <tr>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900"><?= formatDate($record['tanggal']) ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900"><?= htmlspecialchars($record['nis']) ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"><?= htmlspecialchars($record['nama_siswa']) ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-center">
                                <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full 
                                    <?= $record['status'] == 'hadir' ? 'bg-green-100 text-green-800' : 
                                       ($record['status'] == 'sakit' ? 'bg-yellow-100 text-yellow-800' : 
                                       ($record['status'] == 'izin' ? 'bg-blue-100 text-blue-800' : 'bg-red-100 text-red-800')) ?>">
                                    <?= ucfirst($record['status']) ?>
                                </span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900"><?= htmlspecialchars($record['keterangan'] ?? '-') ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</body>
</html>
