<?php
// =======================================================
// SISTEM ABSENSI SISWA - VERSI FINAL DENGAN UPLOAD FOTO
// =======================================================

session_start();
require_once 'db.php';

// --- KONFIGURASI ---
define('ADMIN_PASSWORD', 'Mifwan.id01');
define('UPLOAD_DIR', 'uploads/foto_siswa/');
define('MAX_FILE_SIZE', 2 * 1024 * 1024); // 2MB

// Buat folder uploads jika belum ada
if (!file_exists(UPLOAD_DIR)) {
    mkdir(UPLOAD_DIR, 0777, true);
}

// --- HELPER FUNCTIONS ---
function getStatusColors() {
    return [
        'H' => 'bg-green-500 text-white',
        'I' => 'bg-yellow-500 text-white',
        'S' => 'bg-blue-500 text-white',
        'A' => 'bg-red-500 text-white'
    ];
}

function getStatusDisplayClass($status) {
    $colors = getStatusColors();
    if (isset($colors[$status])) {
        return $colors[$status];
    }
    return 'bg-gray-100 text-gray-400';
}

function uploadFoto($file) {
    if ($file['error'] !== UPLOAD_ERR_OK) {
        return null;
    }

    // Validasi tipe file
    $allowed_types = ['image/jpeg', 'image/png', 'image/gif'];
    $file_type = mime_content_type($file['tmp_name']);
    if (!in_array($file_type, $allowed_types)) {
        return null;
    }

    // Validasi ukuran file
    if ($file['size'] > MAX_FILE_SIZE) {
        return null;
    }

    // Generate nama file unik
    $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
    $filename = uniqid() . '_' . time() . '.' . $extension;
    $filepath = UPLOAD_DIR . $filename;

    if (move_uploaded_file($file['tmp_name'], $filepath)) {
        return $filepath;
    }

    return null;
}

// --- CEK STATUS LOGIN ---
$is_admin = isset($_SESSION['is_admin_logged_in']) && $_SESSION['is_admin_logged_in'] === true;
$is_public = isset($_GET['view']) && $_GET['view'] === 'public';

// --- PROSES LOGOUT & LOGIN ---
if (isset($_GET['action']) && $_GET['action'] === 'logout') {
    session_destroy();
    header("Location: index.php");
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['login'])) {
    if ($_POST['password'] === ADMIN_PASSWORD) {
        $_SESSION['is_admin_logged_in'] = true;
        header("Location: index.php");
        exit;
    } else {
        $login_error = "Password salah!";
    }
}

// --- PROSES UPDATE KEHADIRAN (AJAX) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    header('Content-Type: application/json');
    if (!$is_admin) {
        echo json_encode(['success' => false, 'message' => 'Akses ditolak.']);
        exit;
    }

    if ($_POST['action'] === 'update_attendance') {
        $siswa_id = $_POST['siswa_id'] ?? null;
        $tanggal = $_POST['tanggal'] ?? null;
        $status = $_POST['status'] ?? null;

        if (!$siswa_id || !$tanggal || !$status) {
            echo json_encode(['success' => false, 'message' => 'Data tidak lengkap.']);
            exit;
        }

        if ($status === 'UNMARK') {
            $query = "DELETE FROM kehadiran WHERE siswa_id = ? AND tanggal = ?";
            $stmt = $pdo->prepare($query);
            if ($stmt->execute([$siswa_id, $tanggal])) {
                echo json_encode(['success' => true, 'unmarked' => true]);
            } else {
                echo json_encode(['success' => false, 'message' => 'Gagal menghapus data.']);
            }
            exit;
        }

        if (in_array($status, ['H', 'I', 'S', 'A'])) {
            $query = "REPLACE INTO kehadiran (siswa_id, tanggal, status, bulan) VALUES (?, ?, ?, ?)";
            $bulan = date('Y-m', strtotime($tanggal));
            $stmt = $pdo->prepare($query);
            if ($stmt->execute([$siswa_id, $tanggal, $status, $bulan])) {
                echo json_encode(['success' => true]);
            } else {
                echo json_encode(['success' => false, 'message' => 'Gagal menyimpan ke database.']);
            }
            exit;
        }

        echo json_encode(['success' => false, 'message' => 'Status tidak valid.']);
        exit;
    }

    if ($_POST['action'] === 'get_fresh_data') {
        $class_id = $_POST['class_id'] ?? null;
        $month = $_POST['month'] ?? null;

        if (!$class_id || !$month) {
            echo json_encode(['success' => false, 'message' => 'Parameter kelas/bulan tidak ada.']);
            exit;
        }

        $stmt_siswa = $pdo->prepare("SELECT * FROM siswa WHERE kelas_id = ? ORDER BY nama ASC");
        $stmt_siswa->execute([$class_id]);
        $siswa_list = $stmt_siswa->fetchAll(PDO::FETCH_ASSOC);

        $attendance_data = [];
        if (!empty($siswa_list)) {
            $siswa_ids = array_column($siswa_list, 'siswa_id');
            if (!empty($siswa_ids)) {
                $placeholders = implode(',', array_fill(0, count($siswa_ids), '?'));
                $stmt_attendance = $pdo->prepare("SELECT siswa_id, tanggal, status FROM kehadiran WHERE siswa_id IN ($placeholders) AND bulan = ?");
                $stmt_attendance->execute([...$siswa_ids, $month]);
                $results = $stmt_attendance->fetchAll(PDO::FETCH_ASSOC);
                foreach ($results as $row) {
                    $attendance_data[$row['siswa_id']][$row['tanggal']] = $row['status'];
                }
            }
        }

        echo json_encode(['success' => true, 'attendance_data' => $attendance_data]);
        exit;
    }
}

// =======================================================
// PROSES ADMIN CRUD (Kelas & Siswa) DENGAN UPLOAD FOTO
// =======================================================
if ($is_admin) {
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['crud_action'])) {
        $crud_action = $_POST['crud_action'];

        if ($crud_action === 'add_class' && isset($_POST['nama_kelas'])) {
            $nama_kelas = trim($_POST['nama_kelas']);
            if (!empty($nama_kelas)) {
                try {
                    $stmt = $pdo->prepare("INSERT INTO kelas (nama_kelas) VALUES (?)");
                    $stmt->execute([$nama_kelas]);
                    $_SESSION['crud_message'] = ['success' => true, 'text' => "Kelas '{$nama_kelas}' berhasil ditambahkan."];
                } catch (PDOException $e) {
                    $_SESSION['crud_message'] = ['success' => false, 'text' => "Gagal menambahkan kelas: " . htmlspecialchars($e->getMessage())];
                }
            }
            header("Location: index.php?page=classes");
            exit;
        }

        if ($crud_action === 'delete_class' && isset($_POST['class_id'])) {
            $class_id = $_POST['class_id'];
            try {
                $pdo->exec("DELETE FROM kehadiran WHERE siswa_id IN (SELECT siswa_id FROM siswa WHERE kelas_id = {$class_id})");
                $pdo->prepare("DELETE FROM siswa WHERE kelas_id = ?")->execute([$class_id]);
                $stmt = $pdo->prepare("DELETE FROM kelas WHERE id = ?");
                $stmt->execute([$class_id]);
                $_SESSION['crud_message'] = ['success' => true, 'text' => "Kelas dan semua data terkait berhasil dihapus."];
            } catch (PDOException $e) {
                $_SESSION['crud_message'] = ['success' => false, 'text' => "Gagal menghapus kelas: " . htmlspecialchars($e->getMessage())];
            }
            header("Location: index.php?page=classes");
            exit;
        }

        if ($crud_action === 'add_student' && isset($_POST['nama'], $_POST['kelas_id'])) {
            $nama = trim($_POST['nama']);
            $kelas_id = $_POST['kelas_id'];
            $jenis_kelamin = $_POST['jenis_kelamin'] ?? null;
            $tempat_lahir = $_POST['tempat_lahir'] ?? null;
            $tanggal_lahir = $_POST['tanggal_lahir'] ?? null;
            $nisn = $_POST['nisn'] ?? null;
            $id_card = $_POST['id_card'] ?? null;
            $foto_path = null;

            // Proses upload foto
            if (isset($_FILES['foto_siswa']) && $_FILES['foto_siswa']['error'] === UPLOAD_ERR_OK) {
                $foto_path = uploadFoto($_FILES['foto_siswa']);
                if (!$foto_path) {
                    $_SESSION['crud_message'] = ['success' => false, 'text' => "Gagal mengupload foto. Pastikan file berupa gambar (JPG/PNG) dan maksimal 2MB."];
                    header("Location: index.php?page=students&class_id={$kelas_id}");
                    exit;
                }
            }

            // Jika NISN kosong, set menjadi NULL
            if (empty($nisn)) {
                $nisn = null;
            }

            // Jika ID Card kosong, set menjadi NULL
            if (empty($id_card)) {
                $id_card = null;
            }

            if (!empty($nama) && is_numeric($kelas_id)) {
                try {
                    // Cek duplikat NISN hanya jika NISN diisi
                    if (!empty($nisn)) {
                        $stmt_check = $pdo->prepare("SELECT COUNT(*) FROM siswa WHERE nisn = ?");
                        $stmt_check->execute([$nisn]);
                        if ($stmt_check->fetchColumn() > 0) {
                            $_SESSION['crud_message'] = ['success' => false, 'text' => "NISN {$nisn} sudah terdaftar."];
                            header("Location: index.php?page=students&class_id={$kelas_id}");
                            exit;
                        }
                    }

                    // Cek duplikat ID Card hanya jika ID Card diisi
                    if (!empty($id_card)) {
                        $stmt_check = $pdo->prepare("SELECT COUNT(*) FROM siswa WHERE id_card = ?");
                        $stmt_check->execute([$id_card]);
                        if ($stmt_check->fetchColumn() > 0) {
                            $_SESSION['crud_message'] = ['success' => false, 'text' => "ID Card {$id_card} sudah terdaftar."];
                            header("Location: index.php?page=students&class_id={$kelas_id}");
                            exit;
                        }
                    }

                    // Insert data lengkap dengan foto dan id_card
                    $stmt = $pdo->prepare("INSERT INTO siswa (nama, jenis_kelamin, tempat_lahir, tanggal_lahir, nisn, id_card, kelas_id, foto_path) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                    $stmt->execute([$nama, $jenis_kelamin, $tempat_lahir, $tanggal_lahir, $nisn, $id_card, $kelas_id, $foto_path]);
                    $new_id = $pdo->lastInsertId();

                    $message = "Siswa '{$nama}' berhasil ditambahkan. ID Siswa: #{$new_id}.";
                    if ($foto_path) {
                        $message .= " Foto berhasil diupload.";
                    }
                    if ($id_card) {
                        $message .= " ID Card: {$id_card}.";
                    }
                    $_SESSION['crud_message'] = ['success' => true, 'text' => $message];

                } catch (PDOException $e) {
                    $_SESSION['crud_message'] = ['success' => false, 'text' => "Gagal menambahkan siswa: " . htmlspecialchars($e->getMessage())];
                }
            }
            header("Location: index.php?page=students&class_id={$kelas_id}");
            exit;
        }

        if ($crud_action === 'edit_student' && isset($_POST['siswa_id'], $_POST['nama'], $_POST['kelas_id'])) {
            $siswa_id = $_POST['siswa_id'];
            $nama = trim($_POST['nama']);
            $kelas_id = $_POST['kelas_id'];
            $jenis_kelamin = $_POST['jenis_kelamin'] ?? null;
            $tempat_lahir = $_POST['tempat_lahir'] ?? null;
            $tanggal_lahir = $_POST['tanggal_lahir'] ?? null;
            $nisn = $_POST['nisn'] ?? null;
            $id_card = $_POST['id_card'] ?? null;
            $existing_foto_path = $_POST['existing_foto_path'] ?? null;

            $new_foto_path = $existing_foto_path;
            $uploaded_path = null;

            // Jika NISN kosong, set menjadi NULL
            if (empty($nisn)) {
                $nisn = null;
            }

            // Jika ID Card kosong, set menjadi NULL
            if (empty($id_card)) {
                $id_card = null;
            }

            // 1. Proses upload foto baru
            if (isset($_FILES['foto_siswa']) && $_FILES['foto_siswa']['error'] === UPLOAD_ERR_OK) {
                $uploaded_path = uploadFoto($_FILES['foto_siswa']);
                if (!$uploaded_path) {
                    $_SESSION['crud_message'] = ['success' => false, 'text' => "Gagal mengupload foto. Pastikan file berupa gambar (JPG/PNG) dan maksimal 2MB."];
                    header("Location: index.php?page=students&class_id={$kelas_id}");
                    exit;
                }

                // Hapus foto lama jika ada
                if (!empty($existing_foto_path) && file_exists($existing_foto_path)) {
                    unlink($existing_foto_path);
                }
                $new_foto_path = $uploaded_path;
            } else if (isset($_POST['remove_foto']) && $_POST['remove_foto'] == '1') {
                // Hapus foto jika checkbox 'Hapus Foto' dicentang
                 if (!empty($existing_foto_path) && file_exists($existing_foto_path)) {
                    unlink($existing_foto_path);
                }
                $new_foto_path = null;
            }

            if (!empty($nama) && is_numeric($kelas_id) && is_numeric($siswa_id)) {
                try {
                    // 2. Cek duplikat NISN (kecuali NISN siswa saat ini)
                    if (!empty($nisn)) {
                        $stmt_check = $pdo->prepare("SELECT COUNT(*) FROM siswa WHERE nisn = ? AND siswa_id != ?");
                        $stmt_check->execute([$nisn, $siswa_id]);
                        if ($stmt_check->fetchColumn() > 0) {
                            $_SESSION['crud_message'] = ['success' => false, 'text' => "NISN {$nisn} sudah terdaftar pada siswa lain."];
                            header("Location: index.php?page=students&class_id={$kelas_id}");
                            exit;
                        }
                    }

                    // 2b. Cek duplikat ID Card (kecuali ID Card siswa saat ini)
                    if (!empty($id_card)) {
                        $stmt_check = $pdo->prepare("SELECT COUNT(*) FROM siswa WHERE id_card = ? AND siswa_id != ?");
                        $stmt_check->execute([$id_card, $siswa_id]);
                        if ($stmt_check->fetchColumn() > 0) {
                            $_SESSION['crud_message'] = ['success' => false, 'text' => "ID Card {$id_card} sudah terdaftar pada siswa lain."];
                            header("Location: index.php?page=students&class_id={$kelas_id}");
                            exit;
                        }
                    }

                    // 3. Update data
                    $stmt = $pdo->prepare("UPDATE siswa SET nama = ?, jenis_kelamin = ?, tempat_lahir = ?, tanggal_lahir = ?, nisn = ?, id_card = ?, kelas_id = ?, foto_path = ? WHERE siswa_id = ?");
                    $stmt->execute([$nama, $jenis_kelamin, $tempat_lahir, $tanggal_lahir, $nisn, $id_card, $kelas_id, $new_foto_path, $siswa_id]);

                    $message = "Data siswa '{$nama}' (ID: #{$siswa_id}) berhasil diperbarui.";
                    if ($uploaded_path) {
                         $message .= " Foto baru berhasil diupload.";
                    } elseif (isset($_POST['remove_foto']) && $_POST['remove_foto'] == '1') {
                        $message .= " Foto berhasil dihapus.";
                    }

                    $_SESSION['crud_message'] = ['success' => true, 'text' => $message];

                } catch (PDOException $e) {
                    $_SESSION['crud_message'] = ['success' => false, 'text' => "Gagal mengedit siswa: " . htmlspecialchars($e->getMessage())];
                }
            }
            header("Location: index.php?page=students&class_id={$kelas_id}");
            exit;
        }

        if ($crud_action === 'delete_student' && isset($_POST['siswa_id'], $_POST['kelas_id'])) {
            $siswa_id = $_POST['siswa_id'];
            $kelas_id = $_POST['kelas_id'];
            try {
                // Hapus foto jika ada
                $stmt_foto = $pdo->prepare("SELECT foto_path FROM siswa WHERE siswa_id = ?");
                $stmt_foto->execute([$siswa_id]);
                $foto_path = $stmt_foto->fetchColumn();

                if ($foto_path && file_exists($foto_path)) {
                    unlink($foto_path);
                }

                $pdo->prepare("DELETE FROM kehadiran WHERE siswa_id = ?")->execute([$siswa_id]);
                $stmt = $pdo->prepare("DELETE FROM siswa WHERE siswa_id = ?");
                $stmt->execute([$siswa_id]);
                $_SESSION['crud_message'] = ['success' => true, 'text' => "Siswa (ID: #{$siswa_id}) berhasil dihapus."];
            } catch (PDOException $e) {
                $_SESSION['crud_message'] = ['success' => false, 'text' => "Gagal menghapus siswa: " . htmlspecialchars($e->getMessage())];
            }
            header("Location: index.php?page=students&class_id={$kelas_id}");
            exit;
        }
    }
}

$crud_message = $_SESSION['crud_message'] ?? null;
unset($_SESSION['crud_message']);

// --- AMBIL DATA DARI DATABASE (DASHBOARD) ---
$kelas_list = $pdo->query("SELECT * FROM kelas ORDER BY nama_kelas ASC")->fetchAll(PDO::FETCH_ASSOC);

// Tentukan kelas aktif untuk dashboard
$current_class_id = $_GET['class_id'] ?? ($kelas_list[0]['id'] ?? null);

$kelas_data = null;
if ($current_class_id) {
    $stmt_kelas = $pdo->prepare("SELECT * FROM kelas WHERE id = ?");
    $stmt_kelas->execute([$current_class_id]);
    $kelas_data = $stmt_kelas->fetch(PDO::FETCH_ASSOC);
}

// Tentukan bulan aktif untuk dashboard
$current_month = $_GET['month'] ?? date('Y-m');

$siswa_list = [];
if ($current_class_id) {
    $stmt_siswa = $pdo->prepare("SELECT * FROM siswa WHERE kelas_id = ? ORDER BY nama ASC");
    $stmt_siswa->execute([$current_class_id]);
    $siswa_list = $stmt_siswa->fetchAll(PDO::FETCH_ASSOC);
}

// Ambil data kehadiran untuk dashboard
$attendance_data = [];
if (!empty($siswa_list) && !empty($current_month)) {
    $siswa_ids = array_column($siswa_list, 'siswa_id');
    if (!empty($siswa_ids)) {
        $placeholders = implode(',', array_fill(0, count($siswa_ids), '?'));
        $stmt_attendance = $pdo->prepare("SELECT siswa_id, tanggal, status FROM kehadiran WHERE siswa_id IN ($placeholders) AND bulan = ?");
        $stmt_attendance->execute([...$siswa_ids, $current_month]);
        $results = $stmt_attendance->fetchAll(PDO::FETCH_ASSOC);
        foreach ($results as $row) {
            $attendance_data[$row['siswa_id']][$row['tanggal']] = $row['status'];
        }
    }
}

$days_in_month = [];
if (!empty($current_month)) {
    $date = new DateTime("$current_month-01");
    $end_date = new DateTime($date->format('Y-m-t'));
    while ($date <= $end_date) {
        $days_in_month[] = [
            'date' => $date->format('Y-m-d'),
            'day' => $date->format('j'),
            'dow' => $date->format('D'),
            'is_weekend' => in_array($date->format('D'), ['Sat', 'Sun'])
        ];
        $date->modify('+1 day');
    }
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sistem Absensi Siswa</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
        body { font-family: 'Inter', sans-serif; }
        .table-container { overflow: auto; max-height: 70vh; border-radius: 0.5rem; }
        .table-container thead th { position: sticky; top: 0; z-index: 10; background: #4f46e5; color: white; }
        .table-container thead th:first-child { z-index: 11; }
        .table-container tbody td:first-child { position: sticky; left: 0; z-index: 5; background: white; box-shadow: 1px 0 3px rgba(0,0,0,0.05); }
        .table-container tbody tr:hover td:first-child { background: #f3f4f6; }
        .status-btn { width: 32px; height: 32px; border-radius: 0.375rem; display: inline-flex; align-items: center; justify-content: center; font-weight: 600; font-size: 0.875rem; cursor: pointer; transition: all 0.15s ease-in-out; border: 2px solid transparent; margin: 0 1px; }
        .status-btn.active { transform: scale(1.1); border-color: #1f2937; }
        .status-btn:not(.active):hover { transform: scale(1.05); background-color: #e5e7eb; }
        .table-container::-webkit-scrollbar { height: 8px; width: 8px; }
        .table-container::-webkit-scrollbar-thumb { background-color: #cbd5e1; border-radius: 4px; }
    </style>
</head>
<body class="bg-gray-50">

<?php if (!$is_admin && !$is_public): ?>
<div class="min-h-screen flex items-center justify-center bg-gradient-to-br from-indigo-500 to-purple-600 w-full">
        <div class="bg-white p-8 rounded-2xl shadow-2xl w-full max-w-md">

            <div class="text-center mb-6">
                <div class="inline-flex items-center justify-center w-16 h-16 bg-indigo-100 rounded-full mb-4">
                    <i class="fas fa-user-shield text-indigo-600 text-2xl"></i>
                </div>
                <h2 class="text-3xl font-bold text-gray-900">Login Admin</h2>
                <p class="text-gray-600">Masuk untuk mengakses dashboard</p>
            </div>

            <?php if (isset($login_error) && $login_error): ?>
                <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded-lg mb-4 text-sm"><?= htmlspecialchars($login_error) ?></div>
            <?php endif; ?>

            <form method="POST" class="space-y-6">
                <input type="hidden" name="login" value="1">
                <div>
                    <label for="password" class="block text-sm font-medium text-gray-700">Password</label>
                    <input type="password" id="password" name="password" required
                           class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500">
                </div>
                <button type="submit" class="w-full bg-indigo-600 text-white py-2 px-4 rounded-lg hover:bg-indigo-700 transition font-semibold">Masuk</button>
            </form>

            <div class="mt-6 text-center pt-6 border-t border-gray-200">
                <p class="text-gray-600">Bukan Admin?
                    <a href="login_siswa.php" class="text-blue-600 hover:underline font-semibold">Login Siswa</a>
                    </p>
            </div>

        </div>
    </div>

<?php else: ?>
<div class="flex min-h-screen bg-gray-100">
    <aside class="w-64 bg-gray-800 text-white flex-shrink-0 hidden md:block">
        <div class="p-6">
            <h1 class="text-2xl font-bold flex items-center text-indigo-400">
                <i class="fas fa-clipboard-check mr-2"></i> SDM03KREATIF
            </h1>
        </div>
        <nav class="mt-6">
            <?php $current_page = $_GET['page'] ?? 'dashboard'; ?>

            <a href="index.php" class="block py-3 px-6 <?= ($current_page === 'dashboard' && !isset($_GET['page'])) ? 'bg-indigo-600 text-white font-semibold border-l-4 border-white' : 'text-gray-300 hover:bg-gray-700 hover:text-white transition' ?>">Dashboard</a>

            <a href="scan.php" class="block py-3 px-6 text-gray-300 hover:bg-gray-700 hover:text-white transition">
                <i class="fas fa-qrcode mr-2"></i> Scan Absen
            </a>
            <a href="cetak_barcode.php" class="block py-3 px-6 text-gray-300 hover:bg-gray-700 hover:text-white transition">
                <i class="fas fa-barcode mr-2"></i> Cetak Barcode
            </a>

            <?php if ($is_admin): ?>
                <div class="p-6 pt-4 text-xs font-semibold text-gray-400 uppercase">Administrasi</div>
                <a href="index.php?page=classes" class="block py-3 px-6 <?= $current_page === 'classes' ? 'bg-indigo-600 text-white font-semibold border-l-4 border-white' : 'text-gray-300 hover:bg-gray-700 hover:text-white transition' ?>">
                    <i class="fas fa-chalkboard-teacher mr-2"></i> Kelola Kelas
                </a>
                <a href="index.php?page=students&class_id=<?= $current_class_id ?>" class="block py-3 px-6 <?= $current_page === 'students' ? 'bg-indigo-600 text-white font-semibold border-l-4 border-white' : 'text-gray-300 hover:bg-gray-700 hover:text-white transition' ?>">
                    <i class="fas fa-users mr-2"></i> Kelola Siswa
                </a>
            <?php endif; ?>

            <div class="absolute bottom-0 w-64 p-6 border-t border-gray-700">
                <?php if ($is_admin): ?>
                    <p class="text-xs text-gray-400 mb-2">MODE: ADMINISTRATOR</p>
                    <a href="?view=public" class="block py-2 px-4 text-sm hover:bg-gray-700 rounded transition">Mode Publik</a>
                    <a href="?action=logout" class="block py-2 px-4 text-sm hover:bg-gray-700 rounded transition text-red-300">Logout</a>
                <?php else: ?>
                    <p class="text-xs text-gray-400 mb-2">MODE: PUBLIK</p>
                    <a href="index.php" class="block py-2 px-4 text-sm hover:bg-gray-700 rounded transition text-indigo-300">Login Admin</a>
                <?php endif; ?>
            </div>
        </nav>
    </aside>

    <main class="flex-1 overflow-y-auto">
        <header class="bg-white shadow p-4 md:p-6 sticky top-0 z-40">
            <h2 class="text-2xl font-bold text-gray-800">
                <?php
                    if ($current_page === 'classes') echo 'Administrasi Kelas';
                    elseif ($current_page === 'students') echo 'Administrasi Siswa';
                    else echo 'Rekap Absensi Siswa';
                ?>
            </h2>
        </header>

        <div class="p-4 md:p-6">
            <?php if (isset($crud_message)): ?>
                <div class="bg-<?= $crud_message['success'] ? 'green' : 'red' ?>-100 border border-<?= $crud_message['success'] ? 'green' : 'red' ?>-400 text-<?= $crud_message['success'] ? 'green' : 'red' ?>-700 px-4 py-3 rounded-lg mb-4 text-sm">
                    <?= htmlspecialchars($crud_message['text']) ?>
                </div>
            <?php endif; ?>

            <?php
            $page = $_GET['page'] ?? 'dashboard';

            if ($is_admin && $page === 'classes'):
                // ===================================
                // HALAMAN: KELOLA KELAS
                // ===================================
            ?>

                <h2 class="text-3xl font-bold text-gray-800 mb-6">Kelola Kelas</h2>
                <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                    <div class="bg-white p-6 rounded-lg shadow col-span-1">
                        <h3 class="text-xl font-semibold mb-4">Tambah Kelas Baru</h3>
                        <form method="POST" class="space-y-4">
                            <input type="hidden" name="crud_action" value="add_class">
                            <div>
                                <label for="nama_kelas" class="block text-sm font-medium text-gray-700">Nama Kelas (Contoh: X RPL)</label>
                                <input type="text" id="nama_kelas" name="nama_kelas" required class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500">
                            </div>
                            <button type="submit" class="w-full bg-indigo-600 text-white py-2 px-4 rounded-md hover:bg-indigo-700 transition font-semibold">
                                <i class="fas fa-plus mr-1"></i> Tambah Kelas
                            </button>
                        </form>
                    </div>

                    <div class="bg-white p-6 rounded-lg shadow col-span-2">
                        <h3 class="text-xl font-semibold mb-4">Daftar Kelas Aktif (<?= count($kelas_list) ?>)</h3>
                        <div class="overflow-y-auto" style="max-height: 400px;">
                            <table class="min-w-full divide-y divide-gray-200">
                                <thead class="bg-gray-50 sticky top-0">
                                    <tr>
                                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID Kelas</th>
                                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Nama Kelas</th>
                                        <th class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">Aksi</th>
                                    </tr>
                                </thead>
                                <tbody class="bg-white divide-y divide-gray-200">
                                    <?php if (isset($kelas_list) && is_array($kelas_list) && !empty($kelas_list)): ?>
                                        <?php foreach ($kelas_list as $k): ?>
                                            <tr>
                                                <td class="px-6 py-4 whitespace-nowrap text-sm font-bold text-gray-500">#<?= $k['id'] ?></td>
                                                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                                                    <?= htmlspecialchars($k['nama_kelas']) ?>
                                                </td>
                                                <td class="px-6 py-4 whitespace-nowrap text-center text-sm font-medium">
                                                    <a href="index.php?page=students&class_id=<?= $k['id'] ?>" class="text-blue-600 hover:text-blue-900 text-lg mr-2" title="Kelola Siswa">
                                                        <i class="fas fa-users"></i>
                                                    </a>
                                                    <form method="POST" onsubmit="return confirm('Apakah Anda yakin menghapus kelas <?= htmlspecialchars($k['nama_kelas']) ?>? SEMUA SISWA & DATA KEHADIRANNYA akan ikut terhapus!');" class="inline">
                                                        <input type="hidden" name="crud_action" value="delete_class">
                                                        <input type="hidden" name="class_id" value="<?= $k['id'] ?>">
                                                        <button type="submit" class="text-red-600 hover:text-red-900 text-lg" title="Hapus Kelas">
                                                            <i class="fas fa-trash"></i>
                                                        </button>
                                                    </form>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <tr>
                                            <td colspan="3" class="px-6 py-4 text-center text-sm text-gray-500">
                                                Tidak ada data kelas.
                                            </td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

            <?php elseif ($is_admin && $page === 'students'):
                // ===================================
                // HALAMAN: KELOLA SISWA
                // ===================================
                $current_class_for_students = $_GET['class_id'] ?? ($kelas_list[0]['id'] ?? null);

                $selected_class_data = null;
                if ($current_class_for_students) {
                    $stmt_kelas_select = $pdo->prepare("SELECT * FROM kelas WHERE id = ?");
                    $stmt_kelas_select->execute([$current_class_for_students]);
                    $selected_class_data = $stmt_kelas_select->fetch(PDO::FETCH_ASSOC);
                }

                $siswa_list_crud = [];
                if ($current_class_for_students) {
                    $stmt_siswa_crud = $pdo->prepare("SELECT * FROM siswa WHERE kelas_id = ? ORDER BY nama ASC");
                    $stmt_siswa_crud->execute([$current_class_for_students]);
                    $siswa_list_crud = $stmt_siswa_crud->fetchAll(PDO::FETCH_ASSOC);
                }
            ?>
                <div class="flex justify-between items-center mb-6">
                    <h2 class="text-3xl font-bold text-gray-800">
                        Kelola Siswa Kelas:
                        <span class="text-indigo-600"><?= htmlspecialchars($selected_class_data['nama_kelas'] ?? 'Pilih Kelas') ?></span>
                    </h2>
                    <form method="GET" class="inline-flex">
                        <input type="hidden" name="page" value="students">
                        <select name="class_id" onchange="this.form.submit()" class="px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500">
                            <?php if (empty($kelas_list)): ?>
                                <option disabled selected>Tidak Ada Kelas</option>
                            <?php endif; ?>
                            <?php foreach ($kelas_list as $k): ?>
                                <option value="<?= $k['id'] ?>" <?= $k['id'] == $current_class_for_students ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($k['nama_kelas']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </form>
                </div>

                <?php if (!$selected_class_data): ?>
                    <div class="bg-yellow-50 border-l-4 border-yellow-400 p-4 text-center text-yellow-700">
                        <p>Silakan <a href="index.php?page=classes" class="font-bold hover:underline">Kelola Kelas</a> terlebih dahulu.</p>
                    </div>
                <?php else: ?>
                    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                        <div class="bg-white p-6 rounded-lg shadow lg:col-span-1">
                            <h3 class="text-xl font-semibold mb-4">Tambah Siswa Baru</h3>
                            <form method="POST" enctype="multipart/form-data" class="space-y-4">
                                <input type="hidden" name="crud_action" value="add_student">
                                <input type="hidden" name="kelas_id" value="<?= $selected_class_data['id'] ?>">

                                <div>
                                    <label for="nama_siswa" class="block text-sm font-medium text-gray-700">Nama Lengkap *</label>
                                    <input type="text" id="nama_siswa" name="nama" required class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500">
                                </div>

                                <div>
                                    <label for="foto_siswa" class="block text-sm font-medium text-gray-700">Foto Siswa (Opsional)</label>
                                    <input type="file" id="foto_siswa" name="foto_siswa" accept="image/*" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500">
                                    <p class="text-xs text-gray-500 mt-1">Format: JPG, PNG, JPEG. Maksimal 2MB.</p>
                                </div>

                                <div class="grid grid-cols-2 gap-4">
                                    <div>
                                        <label for="jenis_kelamin" class="block text-sm font-medium text-gray-700">Jenis Kelamin</label>
                                        <select id="jenis_kelamin" name="jenis_kelamin" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500">
                                            <option value="">Pilih Jenis Kelamin</option>
                                            <option value="L">Laki-laki</option>
                                            <option value="P">Perempuan</option>
                                        </select>
                                    </div>
                                    <div>
                                        <label for="nisn" class="block text-sm font-medium text-gray-700">NISN (Opsional)</label>
                                        <input type="text" id="nisn" name="nisn" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500" placeholder="Nomor NISN">
                                    </div>
                                </div>

                                <div>
                                    <label for="id_card" class="block text-sm font-medium text-gray-700">ID Card / Nomor Kartu Pelajar (Opsional)</label>
                                    <input type="text" id="id_card" name="id_card" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500" placeholder="Nomor ID Card / Kartu Pelajar">
                                    <p class="text-xs text-gray-500 mt-1">Nomor ID card untuk kartu pelajar.</p>
                                </div>

                                <div class="grid grid-cols-2 gap-4">
                                    <div>
                                        <label for="tempat_lahir" class="block text-sm font-medium text-gray-700">Tempat Lahir</label>
                                        <input type="text" id="tempat_lahir" name="tempat_lahir" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500">
                                    </div>
                                    <div>
                                        <label for="tanggal_lahir" class="block text-sm font-medium text-gray-700">Tanggal Lahir</label>
                                        <input type="date" id="tanggal_lahir" name="tanggal_lahir" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500">
                                    </div>
                                </div>

                                <button type="submit" class="w-full bg-indigo-600 text-white py-2 px-4 rounded-md hover:bg-indigo-700 transition font-semibold">
                                    <i class="fas fa-user-plus mr-1"></i> Tambah Siswa
                                </button>
                            </form>
                        </div>

                        <div class="bg-white p-6 rounded-lg shadow lg:col-span-2">
                            <h3 class="text-xl font-semibold mb-4">Daftar Siswa (<?= count($siswa_list_crud) ?>)</h3>
                            <div class="overflow-x-auto">
                                <table class="min-w-full divide-y divide-gray-200">
                                    <thead class="bg-gray-50">
                                        <tr>
                                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Foto</th>
                                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Nama Siswa / ID</th>
                                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">J. Kelamin</th>
                                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">TTL</th>
                                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">NISN</th>
                                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID Card</th>
                                            <th class="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">Aksi</th>
                                        </tr>
                                    </thead>
                                    <tbody class="bg-white divide-y divide-gray-200">
                                        <?php if (empty($siswa_list_crud)): ?>
                                            <tr>
                                                <td colspan="7" class="px-4 py-4 text-center text-sm text-gray-500">
                                                    Tidak ada data siswa di kelas ini.
                                                </td>
                                            </tr>
                                        <?php else: ?>
                                            <?php foreach ($siswa_list_crud as $s): ?>
                                            <tr>
                                                <td class="px-4 py-3 whitespace-nowrap">
                                                    <?php if (!empty($s['foto_path'])): ?>
                                                        <img src="<?= htmlspecialchars($s['foto_path']) ?>" alt="Foto <?= htmlspecialchars($s['nama']) ?>" class="w-10 h-10 rounded-full object-cover border border-gray-300">
                                                    <?php else: ?>
                                                        <div class="w-10 h-10 rounded-full bg-gray-200 flex items-center justify-center border border-gray-300">
                                                            <i class="fas fa-user text-gray-400 text-sm"></i>
                                                        </div>
                                                    <?php endif; ?>
                                                </td>
                                                <td class="px-4 py-3 whitespace-nowrap">
                                                    <div class="text-sm font-medium text-gray-900"><?= htmlspecialchars($s['nama']) ?></div>
                                                    <div class="text-xs text-gray-400">ID: #<?= $s['siswa_id'] ?></div>
                                                </td>
                                                <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
                                                    <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium <?= $s['jenis_kelamin'] == 'L' ? 'bg-blue-100 text-blue-800' : 'bg-pink-100 text-pink-800' ?>">
                                                        <?= $s['jenis_kelamin'] == 'L' ? 'Laki-laki' : ($s['jenis_kelamin'] == 'P' ? 'Perempuan' : 'Tidak diisi') ?>
                                                    </span>
                                                </td>
                                                <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
                                                    <?php if (!empty($s['tempat_lahir']) || !empty($s['tanggal_lahir'])): ?>
                                                        <div class="max-w-xs">
                                                            <div class="font-medium"><?= !empty($s['tempat_lahir']) ? htmlspecialchars($s['tempat_lahir']) : 'Tidak diisi' ?></div>
                                                            <div class="text-xs text-gray-400">
                                                                <?= !empty($s['tanggal_lahir']) ? date('d/m/Y', strtotime($s['tanggal_lahir'])) : 'Tgl lahir tidak diisi' ?>
                                                            </div>
                                                        </div>
                                                    <?php else: ?>
                                                        <span class="text-gray-400">-</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
                                                    <?php if (!empty($s['nisn'])): ?>
                                                        <span class="font-mono bg-yellow-50 px-2 py-1 rounded border border-yellow-200">
                                                            <?= htmlspecialchars($s['nisn']) ?>
                                                        </span>
                                                    <?php else: ?>
                                                        <span class="text-gray-400 text-xs">Belum ada NISN</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
                                                    <?php if (!empty($s['id_card'])): ?>
                                                        <span class="font-mono bg-indigo-50 px-2 py-1 rounded border border-indigo-200">
                                                            <?= htmlspecialchars($s['id_card']) ?>
                                                        </span>
                                                    <?php else: ?>
                                                        <span class="text-gray-400 text-xs">Belum ada ID Card</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td class="px-4 py-3 whitespace-nowrap text-center text-sm font-medium">
                                                    <div class="flex justify-center space-x-2">
                                                        <button onclick="openEditModal(<?= htmlspecialchars(json_encode($s)) ?>)" type="button" class="text-indigo-600 hover:text-indigo-900 text-lg" title="Edit Siswa">
                                                            <i class="fas fa-edit"></i>
                                                        </button>

                                                        <form method="POST" onsubmit="return confirm('Apakah Anda yakin menghapus siswa <?= htmlspecialchars($s['nama']) ?> (ID: #<?= $s['siswa_id'] ?>)? SEMUA DATA KEHADIRANNYA akan ikut terhapus!');" class="inline">
                                                            <input type="hidden" name="crud_action" value="delete_student">
                                                            <input type="hidden" name="siswa_id" value="<?= $s['siswa_id'] ?>">
                                                            <input type="hidden" name="kelas_id" value="<?= $selected_class_data['id'] ?>">
                                                            <button type="submit" class="text-red-600 hover:text-red-900 text-lg" title="Hapus Siswa">
                                                                <i class="fas fa-trash"></i>
                                                            </button>
                                                        </form>
                                                    </div>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>

                <div id="editStudentModal" class="fixed inset-0 bg-gray-600 bg-opacity-75 flex items-center justify-center z-50 hidden">
                    <div class="bg-white rounded-lg shadow-xl w-full max-w-lg mx-4">
                        <div class="p-6 border-b flex justify-between items-center">
                            <h3 class="text-2xl font-semibold text-gray-900">Edit Data Siswa</h3>
                            <button onclick="closeEditModal()" type="button" class="text-gray-400 hover:text-gray-600 text-2xl">&times;</button>
                        </div>
                        <form id="editStudentForm" method="POST" enctype="multipart/form-data" class="p-6 space-y-4">
                            <input type="hidden" name="crud_action" value="edit_student">
                            <input type="hidden" name="kelas_id" value="<?= $selected_class_data['id'] ?? '' ?>">
                            <input type="hidden" name="siswa_id" id="edit_siswa_id">
                            <input type="hidden" name="existing_foto_path" id="edit_existing_foto_path">

                            <div>
                                <label for="edit_nama_siswa" class="block text-sm font-medium text-gray-700">Nama Lengkap *</label>
                                <input type="text" id="edit_nama_siswa" name="nama" required class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500">
                            </div>

                            <div class="flex items-center space-x-4">
                                <div id="edit_foto_preview_container" class="flex-shrink-0">
                                    <img id="edit_foto_preview" class="w-16 h-16 rounded-full object-cover border border-gray-300" src="" alt="Foto Siswa">
                                </div>
                                <div class="flex-grow">
                                    <div>
                                        <label for="edit_foto_siswa" class="block text-sm font-medium text-gray-700">Ganti Foto Siswa (Opsional)</label>
                                        <input type="file" id="edit_foto_siswa" name="foto_siswa" accept="image/*" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500">
                                        <p class="text-xs text-gray-500 mt-1">Format: JPG, PNG, JPEG. Maksimal 2MB.</p>
                                    </div>
                                    <div class="mt-2 hidden" id="remove_foto_option">
                                        <label class="inline-flex items-center">
                                            <input type="checkbox" name="remove_foto" id="remove_foto" value="1" class="form-checkbox h-4 w-4 text-red-600 rounded">
                                            <span class="ml-2 text-sm text-red-600">Hapus Foto (Kosongkan)</span>
                                        </label>
                                    </div>
                                </div>
                            </div>

                            <div class="grid grid-cols-2 gap-4">
                                <div>
                                    <label for="edit_jenis_kelamin" class="block text-sm font-medium text-gray-700">Jenis Kelamin</label>
                                    <select id="edit_jenis_kelamin" name="jenis_kelamin" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500">
                                        <option value="">Pilih Jenis Kelamin</option>
                                        <option value="L">Laki-laki</option>
                                        <option value="P">Perempuan</option>
                                    </select>
                                </div>
                                <div>
                                    <label for="edit_nisn" class="block text-sm font-medium text-gray-700">NISN (Opsional)</label>
                                    <input type="text" id="edit_nisn" name="nisn" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500" placeholder="Nomor NISN">
                                </div>
                            </div>

                            <div>
                                <label for="edit_id_card" class="block text-sm font-medium text-gray-700">ID Card / Nomor Kartu Pelajar (Opsional)</label>
                                <input type="text" id="edit_id_card" name="id_card" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500" placeholder="Nomor ID Card / Kartu Pelajar">
                                <p class="text-xs text-gray-500 mt-1">Nomor ID card untuk kartu pelajar.</p>
                            </div>

                            <div class="grid grid-cols-2 gap-4">
                                <div>
                                    <label for="edit_tempat_lahir" class="block text-sm font-medium text-gray-700">Tempat Lahir</label>
                                    <input type="text" id="edit_tempat_lahir" name="tempat_lahir" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500">
                                </div>
                                <div>
                                    <label for="edit_tanggal_lahir" class="block text-sm font-medium text-gray-700">Tanggal Lahir</label>
                                    <input type="date" id="edit_tanggal_lahir" name="tanggal_lahir" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500">
                                </div>
                            </div>

                            <button type="submit" class="w-full bg-green-600 text-white py-2 px-4 rounded-md hover:bg-green-700 transition font-semibold">
                                <i class="fas fa-save mr-1"></i> Simpan Perubahan
                            </button>
                        </form>
                    </div>
                </div>
                <?php elseif ($page === 'dashboard' || $is_public): ?>

                <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6 bg-white p-4 rounded-lg shadow">
                    <form method="GET" class="md:col-span-4 grid grid-cols-1 md:grid-cols-3 gap-4">
                        <input type="hidden" name="page" value="dashboard">
                        <?php if ($is_public) echo '<input type="hidden" name="view" value="public">'; ?>

                        <div>
                            <label class="block text-sm font-medium text-gray-700">Kelas</label>
                            <select name="class_id" onchange="this.form.submit()" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500">
                                <?php if (empty($kelas_list)): ?>
                                    <option disabled>Tidak ada kelas. Silakan Kelola Kelas dulu.</option>
                                <?php endif; ?>
                                <?php foreach ($kelas_list as $k): ?>
                                    <option value="<?= $k['id'] ?>" <?= $k['id'] == $current_class_id ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($k['nama_kelas']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700">Bulan</label>
                            <input type="month" name="month" value="<?= $current_month ?>" onchange="this.form.submit()" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500">
                        </div>

                        <div class="flex items-end">
                            <div class="bg-indigo-100 text-indigo-800 p-3 rounded-md w-full text-center">
                                <p class="text-sm">Kelas Aktif</p>
                                <p class="font-bold"><?= htmlspecialchars($kelas_data['nama_kelas'] ?? 'Pilih Kelas') ?></p>
                            </div>
                        </div>
                    </form>
                </div>

                <?php if (empty($siswa_list)): ?>
                    <div class="bg-yellow-50 border-l-4 border-yellow-400 p-4 text-center">
                        <p class="text-yellow-700">
                            <?php if (empty($kelas_list)): ?>
                                Tidak ada kelas. Silakan tambah kelas terlebih dahulu.
                            <?php else: ?>
                                Tidak ada siswa di kelas <?= htmlspecialchars($kelas_data['nama_kelas'] ?? 'ini') ?>.
                            <?php endif; ?>
                        </p>
                    </div>
                <?php else: ?>
                    <div class="bg-white rounded-lg shadow mb-6">
                        <div class="p-4 border-b font-semibold text-lg bg-indigo-600 text-white rounded-t-lg">
                            Tabel Kehadiran Harian - <?= htmlspecialchars($kelas_data['nama_kelas'] ?? '') ?> (<?= date('F Y', strtotime($current_month)) ?>)
                        </div>
                        <div class="table-container shadow-inner">
                            <table class="w-full text-sm border-collapse">
                                <thead>
                                    <tr>
                                        <th class="p-3 text-left border-b font-bold tracking-wider w-48 bg-indigo-50">Nama Siswa</th>
                                        <?php foreach ($days_in_month as $day): ?>
                                            <th class="p-3 text-center border-b font-bold tracking-wider w-10
                                                <?= $day['is_weekend'] ? 'bg-red-100 text-red-600' : 'bg-indigo-50 text-gray-700' ?>"
                                                title="<?= $day['dow'] ?> <?= $day['day'] ?>">
                                                <?= $day['day'] ?>
                                            </th>
                                        <?php endforeach; ?>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    $status_colors = getStatusColors();
                                    foreach ($siswa_list as $siswa):
                                    ?>
                                    <tr class="even:bg-gray-50">
                                        <td class="p-3 border-b font-semibold whitespace-nowrap sticky left-0 z-5 bg-white">
                                            <?= htmlspecialchars($siswa['nama']) ?>
                                        </td>
                                        <?php foreach ($days_in_month as $day):
                                            $current_status = $attendance_data[$siswa['siswa_id']][$day['date']] ?? '';
                                        ?>
                                            <td class="p-1 border-b text-center align-middle whitespace-nowrap w-10">
                                                <?php if ($is_admin && !$day['is_weekend']): ?>
                                                <div class="status-container flex justify-center items-center"
                                                     data-siswa-id="<?= $siswa['siswa_id'] ?>"
                                                     data-tanggal="<?= $day['date'] ?>"
                                                     data-current-status="<?= $current_status ?>">
                                                    <?php foreach (['H', 'I', 'S', 'A'] as $status): ?>
                                                        <button type="button" class="status-btn <?= $status == $current_status ? $status_colors[$status] . ' active' : 'bg-gray-200 text-gray-600' ?>"
                                                                data-status="<?= $status ?>"
                                                                title="<?= $status == 'H' ? 'Hadir' : ($status == 'I' ? 'Izin' : ($status == 'S' ? 'Sakit' : 'Alpha')) ?>">
                                                            <?= $status ?>
                                                        </button>
                                                    <?php endforeach; ?>
                                                </div>
                                                <?php elseif (!$day['is_weekend']): ?>
                                                    <span class="inline-block px-2 py-1 text-xs font-semibold rounded-full <?= getStatusDisplayClass($current_status) ?>">
                                                        <?= $current_status ?: '-' ?>
                                                    </span>
                                                <?php endif; ?>
                                            </td>
                                        <?php endforeach; ?>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <div class="bg-white rounded-lg shadow mt-6">
                        <div class="p-4 border-b font-semibold text-lg bg-indigo-600 text-white rounded-t-lg">
                            Rekapitulasi Bulanan - <?= htmlspecialchars($kelas_data['nama_kelas'] ?? '') ?> (<?= date('F Y', strtotime($current_month)) ?>)
                        </div>
                        <div class="p-6">
                            <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8" id="total-cards-container">
                                </div>
                            <div class="overflow-x-auto">
                                <table class="w-full text-sm border-collapse">
                                    <thead class="bg-gray-50 border-b">
                                        <tr>
                                            <th class="p-3 text-left font-bold text-gray-700">Nama Siswa</th>
                                            <th class="p-3 text-center font-bold text-green-600">Hadir</th>
                                            <th class="p-3 text-center font-bold text-yellow-600">Izin</th>
                                            <th class="p-3 text-center font-bold text-blue-600">Sakit</th>
                                            <th class="p-3 text-center font-bold text-red-600">Alpha</th>
                                            <th class="p-3 text-center font-bold text-indigo-600">Total Hari</th>
                                            <th class="p-3 text-center font-bold text-indigo-600">Persentase H</th>
                                        </tr>
                                    </thead>
                                    <tbody id="summary-table-body">
                                        </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>

            <?php endif; ?>
        </div>
    </main>
</div>
<?php endif; ?>

<div id="toast" class="fixed bottom-4 right-4 bg-green-500 text-white px-6 py-3 rounded-lg shadow-xl transform translate-y-full transition-transform duration-300 z-50"><span id="toast-message"></span></div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const statusColorsMap = {
        'H': 'bg-green-500 text-white',
        'I': 'bg-yellow-500 text-white',
        'S': 'bg-blue-500 text-white',
        'A': 'bg-red-500 text-white'
    };
    const activeBorderClass = 'border-gray-900';
    const totalDays = <?= count($days_in_month) ?>;

    // --- TOAST FUNCTION ---
    function showToast(message, isError = false) {
        const toast = document.getElementById('toast');
        const toastMessage = document.getElementById('toast-message');

        toastMessage.textContent = message;

        if (isError) {
            toast.classList.remove('bg-green-500');
            toast.classList.add('bg-red-500');
        } else {
            toast.classList.remove('bg-red-500');
            toast.classList.add('bg-green-500');
        }

        toast.classList.remove('translate-y-full');
        toast.classList.add('translate-y-0');

        setTimeout(() => {
            toast.classList.remove('translate-y-0');
            toast.classList.add('translate-y-full');
        }, 3000);
    }

    // --- ATTENDANCE UPDATE LOGIC ---
    if (<?= $is_admin ? 'true' : 'false' ?>) {
        function updateStatusButton(button, isActive) {
            const status = button.dataset.status;
            button.classList.remove(...Object.values(statusColorsMap));
            button.classList.remove('bg-gray-200', 'text-gray-600', 'active', activeBorderClass);

            if (isActive) {
                button.classList.add(statusColorsMap[status], 'active', activeBorderClass);
            } else {
                button.classList.add('bg-gray-200', 'text-gray-600');
            }
        }

        document.querySelectorAll('.status-container').forEach(container => {
            container.addEventListener('click', async function(e) {
                const button = e.target.closest('.status-btn');
                if (!button) return;

                const siswaId = container.dataset.siswaId;
                const tanggal = container.dataset.tanggal;
                let newStatus = button.dataset.status;
                const currentStatus = container.dataset.currentStatus;

                if (!currentStatus) {
                    // Jika status kosong, klik pertama akan memilih status baru
                    updateStatusButton(button, true);
                    container.dataset.currentStatus = newStatus;
                } else if (button.classList.contains('active')) {
                    // Jika tombol aktif diklik, UNMARK (hapus status)
                    newStatus = 'UNMARK';
                    updateStatusButton(button, false);
                    container.dataset.currentStatus = '';
                } else {
                    // Jika tombol lain diklik, ganti status
                    container.querySelectorAll('.status-btn.active').forEach(btn => updateStatusButton(btn, false));
                    updateStatusButton(button, true);
                    container.dataset.currentStatus = newStatus;
                }

                container.style.opacity = '0.5';
                container.style.pointerEvents = 'none';

                try {
                    const response = await fetch('', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded'
                        },
                        body: new URLSearchParams({
                            action: 'update_attendance',
                            siswa_id: siswaId,
                            tanggal: tanggal,
                            status: newStatus
                        })
                    });

                    const result = await response.json();

                    if (result.success) {
                        showToast(newStatus === 'UNMARK' ? 'Status berhasil dihapus (Kosong)' : `Status berhasil diubah menjadi ${newStatus}`);
                        updateSummary();
                    } else {
                        showToast(result.message || 'Gagal mengubah status.', true);
                        // Kembalikan ke status awal jika gagal
                        container.dataset.currentStatus = currentStatus;
                        container.querySelectorAll('.status-btn').forEach(btn => {
                            updateStatusButton(btn, btn.dataset.status === currentStatus);
                        });
                    }
                } catch (error) {
                    console.error('Error:', error);
                    showToast('Terjadi kesalahan jaringan.', true);
                    // Kembalikan ke status awal jika gagal
                    container.dataset.currentStatus = currentStatus;
                    container.querySelectorAll('.status-btn').forEach(btn => {
                        updateStatusButton(btn, btn.dataset.status === currentStatus);
                    });
                } finally {
                    container.style.opacity = '1';
                    container.style.pointerEvents = 'auto';
                }
            });
        });
    }

        // =======================================================
    // PEMBARUAN FINAL: Fungsi updateSummary yang paling andal
    // =======================================================
    async function updateSummary() {
        try {
            const response = await fetch('', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: new URLSearchParams({
                    action: 'get_fresh_data',
                    class_id: '<?= $current_class_id ?>',
                    month: '<?= $current_month ?>'
                })
            });
            const result = await response.json();

            if (result.success) {
                const freshAttendanceData = result.attendance_data;
                const attendanceTableBody = document.querySelector('.table-container tbody');
                const summaryTableBody = document.getElementById('summary-table-body');
                const studentRows = attendanceTableBody ? attendanceTableBody.querySelectorAll('tr') : [];
                const summaryData = {};

                // 1. Update UI Absensi Harian (jika ada) & Hitung Rekap
                studentRows.forEach(row => {
                    const nama = row.cells[0].textContent.trim();
                    const container = row.querySelector('.status-container');

                    if (container) {
                        const siswaId = container.dataset.siswaId;
                        summaryData[siswaId] = { nama: nama, H: 0, I: 0, S: 0, A: 0, total_days: totalDays };

                        // Cek apakah data kehadiran siswa ada
                        if (freshAttendanceData[siswaId]) {
                            // Update UI harian
                            container.querySelectorAll('.status-btn').forEach(btn => {
                                updateStatusButton(btn, false);
                            });

                            // Loop melalui setiap sel hari
                            for (let i = 1; i < row.cells.length; i++) {
                                const cell = row.cells[i];
                                const cellContainer = cell.querySelector('.status-container');

                                if (cellContainer) {
                                    const cellDate = cellContainer.dataset.tanggal;
                                    const status = freshAttendanceData[siswaId][cellDate];
                                    cellContainer.dataset.currentStatus = status || '';

                                    // Update tombol di sel
                                    cellContainer.querySelectorAll('.status-btn').forEach(btn => {
                                        const btnStatus = btn.dataset.status;
                                        updateStatusButton(btn, btnStatus === status);
                                    });

                                    // Hitung rekap
                                    if (status && summaryData[siswaId].hasOwnProperty(status)) {
                                        summaryData[siswaId][status]++;
                                    }
                                }
                            }
                        }
                    }
                });

                // 2. Hitung Total Keseluruhan
                const totals = { H: 0, I: 0, S: 0, A: 0 };
                Object.values(summaryData).forEach(data => {
                    totals.H += data.H;
                    totals.I += data.I;
                    totals.S += data.S;
                    totals.A += data.A;
                });

                // 3. Update Kartu Total
                const cardsContainer = document.getElementById('total-cards-container');
                if (cardsContainer) {
                    const totalStudents = Object.keys(summaryData).length;

                    cardsContainer.innerHTML = `
                        <div class="bg-green-100 p-4 rounded-lg text-center shadow-sm"><p class="text-green-800 font-bold text-2xl">${totals.H}</p><p class="text-sm text-green-700">Total Hadir</p></div>
                        <div class="bg-yellow-100 p-4 rounded-lg text-center shadow-sm"><p class="text-yellow-800 font-bold text-2xl">${totals.I}</p><p class="text-sm text-yellow-700">Total Izin</p></div>
                        <div class="bg-blue-100 p-4 rounded-lg text-center shadow-sm"><p class="text-blue-800 font-bold text-2xl">${totals.S}</p><p class="text-sm text-blue-700">Total Sakit</p></div>
                        <div class="bg-red-100 p-4 rounded-lg text-center shadow-sm"><p class="text-red-800 font-bold text-2xl">${totals.A}</p><p class="text-sm text-red-700">Total Alpha</p></div>
                    `;
                }

                // 4. Update Tabel Rekapitulasi
                if (summaryTableBody) {
                    summaryTableBody.innerHTML = '';
                    for (const siswaId in summaryData) {
                        const data = summaryData[siswaId];
                        const totalMarked = data.H + data.I + data.S + data.A;

                        // Hitung total hari efektif di bulan ini (diasumsikan semua siswa dihitung)
                        const daysInMonth = <?= count($days_in_month) ?>;
                        const daysAttended = data.H;

                        // Cek jika totalMarked adalah 0 untuk menghindari pembagian dengan nol
                        // Jika tidak ada data yang ditandai, persentase hadir adalah 0%
                        const percentage = totalMarked > 0 ? ((daysAttended / totalMarked) * 100).toFixed(1) : 0.0;

                        const percentageColor = percentage >= 90 ? 'text-green-600' : (percentage >= 75 ? 'text-yellow-600' : 'text-red-600');

                        const row = summaryTableBody.insertRow(); row.className = 'even:bg-gray-50';
                        row.innerHTML = `<td class="p-3 border-b text-left">${data.nama}</td><td class="p-3 text-center border-b font-semibold text-green-700">${data.H}</td><td class="p-3 text-center border-b font-semibold text-yellow-700">${data.I}</td><td class="p-3 text-center border-b font-semibold text-blue-700">${data.S}</td><td class="p-3 text-center border-b font-semibold text-red-700">${data.A}</td><td class="p-3 text-center border-b font-bold">${totalMarked} / ${daysInMonth}</td><td class="p-3 text-center border-b font-bold ${percentageColor}">${percentage}%</td>`;
                    }
                }

            } else {
                showToast('Gagal memperbarui data.', true);
            }
        } catch (error) {
            console.error('Error updating summary:', error);
            showToast('Terjadi kesalahan jaringan saat memperbarui data.', true);
        }
    } // <--- Kurung kurawal penutup yang ditambahkan

    // Panggil saat halaman dimuat
    if (document.getElementById('summary-table-body')) {
        updateSummary();
    }

    // =======================================================
    // FIX: Fungsi Edit Siswa (Modal & Logic)
    // =======================================================
    // Ikon user sederhana SVG untuk placeholder
    const defaultFoto = 'data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="#9CA3AF"><path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/></svg>';

    // Fungsi harus didefinisikan di global scope agar bisa dipanggil dari inline onclick
    window.openEditModal = function(student) {
        const editModal = document.getElementById('editStudentModal');
        if (!editModal) {
            console.error('Modal edit siswa tidak ditemukan');
            return;
        }
        
        // Isi form dengan data siswa
        document.getElementById('edit_siswa_id').value = student.siswa_id;
        document.getElementById('edit_nama_siswa').value = student.nama;
        document.getElementById('edit_jenis_kelamin').value = student.jenis_kelamin || '';
        document.getElementById('edit_tempat_lahir').value = student.tempat_lahir || '';
        document.getElementById('edit_tanggal_lahir').value = student.tanggal_lahir || '';
        document.getElementById('edit_nisn').value = student.nisn || '';
        document.getElementById('edit_id_card').value = student.id_card || '';
        document.getElementById('edit_existing_foto_path').value = student.foto_path || '';

        // Reset file input dan remove foto checkbox
        document.getElementById('edit_foto_siswa').value = '';
        const removeFotoCheckbox = document.getElementById('remove_foto');
        if (removeFotoCheckbox) {
            removeFotoCheckbox.checked = false;
        }

        // Atur preview foto
        const previewImg = document.getElementById('edit_foto_preview');
        const removeOption = document.getElementById('remove_foto_option');
        if (previewImg && removeOption) {
            if (student.foto_path && student.foto_path !== '') {
                previewImg.src = student.foto_path;
                removeOption.classList.remove('hidden');
            } else {
                // Jika tidak ada foto, gunakan placeholder
                previewImg.src = defaultFoto;
                removeOption.classList.add('hidden');
            }
        }

        // Tampilkan modal
        editModal.classList.remove('hidden');
    };

    window.closeEditModal = function() {
        const editModal = document.getElementById('editStudentModal');
        if (editModal) {
            editModal.classList.add('hidden');
        }
    };

    // Agar modal bisa ditutup dengan klik di luar area modal
    const editModal = document.getElementById('editStudentModal');
    if (editModal) {
        editModal.addEventListener('click', function(e) {
            if (e.target === editModal) {
                window.closeEditModal();
            }
        });
    }

    // =======================================================
    // AKHIR FIX
    // =======================================================

});
</script>
</body>
</html>