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

// Helper function to format date in Indonesian
function formatDate($date) {
    $months = [
        1 => 'Januari', 2 => 'Februari', 3 => 'Maret', 4 => 'April',
        5 => 'Mei', 6 => 'Juni', 7 => 'Juli', 8 => 'Agustus',
        9 => 'September', 10 => 'Oktober', 11 => 'November', 12 => 'Desember'
    ];
    
    $days = [
        'Sunday' => 'Minggu', 'Monday' => 'Senin', 'Tuesday' => 'Selasa',
        'Wednesday' => 'Rabu', 'Thursday' => 'Kamis', 'Friday' => 'Jumat',
        'Saturday' => 'Sabtu'
    ];
    
    $timestamp = strtotime($date);
    $dayName = $days[date('l', $timestamp)];
    $day = date('d', $timestamp);
    $month = $months[date('n', $timestamp)];
    $year = date('Y', $timestamp);
    
    return $dayName . ', ' . $day . ' ' . $month . ' ' . $year;
}

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

$today = date('Y-m-d');
$message = '';

// Handle attendance submission
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['submit_attendance'])) {
    $conn->beginTransaction();
    try {
        foreach ($_POST['attendance'] as $id_siswa => $status) {
            $keterangan = $_POST['keterangan'][$id_siswa] ?? '';
            
            // Check if attendance already exists
            $query = "SELECT id_absensi FROM absensi WHERE id_siswa = :id_siswa AND tanggal = :tanggal";
            $stmt = $conn->prepare($query);
            $stmt->bindParam(':id_siswa', $id_siswa);
            $stmt->bindParam(':tanggal', $today);
            $stmt->execute();
            
            if ($stmt->rowCount() > 0) {
                // Update existing
                $query = "UPDATE absensi SET status = :status, keterangan = :keterangan 
                          WHERE id_siswa = :id_siswa AND tanggal = :tanggal";
            } else {
                // Insert new
                $query = "INSERT INTO absensi (id_siswa, id_kelas, tanggal, status, keterangan) 
                          VALUES (:id_siswa, :id_kelas, :tanggal, :status, :keterangan)";
            }
            
            $stmt = $conn->prepare($query);
            $stmt->bindParam(':id_siswa', $id_siswa);
            if (!isset($stmt->id_kelas)) {
                $stmt->bindParam(':id_kelas', $currentUser['id_kelas']);
            }
            $stmt->bindParam(':tanggal', $today);
            $stmt->bindParam(':status', $status);
            $stmt->bindParam(':keterangan', $keterangan);
            $stmt->execute();
        }
        
        $conn->commit();
        $message = "Absensi berhasil disimpan!";
    } catch (Exception $e) {
        $conn->rollback();
        $message = "Gagal menyimpan absensi: " . $e->getMessage();
    }
}

// Get students with today's attendance
$students = [];
if ($currentUser['id_kelas']) {
    $query = "SELECT s.*, a.status as attendance_status, a.keterangan 
              FROM siswa s 
              LEFT JOIN absensi a ON s.id_siswa = a.id_siswa AND a.tanggal = :tanggal
              WHERE s.id_kelas = :id_kelas AND s.status = 'aktif' 
              ORDER BY s.nama_siswa ASC";
    $stmt = $conn->prepare($query);
    $stmt->bindParam(':id_kelas', $currentUser['id_kelas']);
    $stmt->bindParam(':tanggal', $today);
    $stmt->execute();
    $students = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Get attendance history
$history = [];
if ($currentUser['id_kelas']) {
    $query = "SELECT a.*, s.nama_siswa, s.nis 
              FROM absensi a 
              JOIN siswa s ON a.id_siswa = s.id_siswa 
              WHERE a.id_kelas = :id_kelas 
              ORDER BY a.tanggal DESC, s.nama_siswa ASC 
              LIMIT 50";
    $stmt = $conn->prepare($query);
    $stmt->bindParam(':id_kelas', $currentUser['id_kelas']);
    $stmt->execute();
    $history = $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>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 -->
    <?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">Absensi Siswa</h1>
            <div class="text-lg font-semibold text-gray-700">
                <i class="fas fa-calendar-alt mr-2"></i>
                <?= formatDate($today) ?>
            </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; ?>

        <!-- Attendance Form -->
        <div class="bg-white rounded-lg shadow-md p-6 mb-8">
            <h2 class="text-xl font-bold text-gray-800 mb-4">Absensi Hari Ini</h2>
            <form method="POST">
                <input type="hidden" name="submit_attendance" value="1">
                
                <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">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 ($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">
                                    <select name="attendance[<?= $student['id_siswa'] ?>]" 
                                            class="rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                                        <option value="hadir" <?= $student['attendance_status'] == 'hadir' ? 'selected' : '' ?>>Hadir</option>
                                        <option value="sakit" <?= $student['attendance_status'] == 'sakit' ? 'selected' : '' ?>>Sakit</option>
                                        <option value="izin" <?= $student['attendance_status'] == 'izin' ? 'selected' : '' ?>>Izin</option>
                                        <option value="alpa" <?= $student['attendance_status'] == 'alpa' ? 'selected' : '' ?>>Alpa</option>
                                    </select>
                                </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 (opsional)">
                                </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 transition">
                        <i class="fas fa-save mr-2"></i>Simpan Absensi
                    </button>
                </div>
            </form>
        </div>

        <!-- Attendance History -->
        <div class="bg-white rounded-lg shadow-md p-6">
            <h2 class="text-xl font-bold text-gray-800 mb-4">Riwayat 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-left 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 ($history 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">
                                <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>
