<?php
session_start();
if (!isset($_SESSION['username']) || !in_array($_SESSION['role'], ['admin', 'guru'])) {
    header("Location: index.php");
    exit;
}

include "config.php";
date_default_timezone_set("Asia/Jakarta");

// Proses hapus absensi
if (isset($_POST['hapus_absensi'])) {
    $hapus_id = (int)$_POST['hapus_id'];
    
    if ($hapus_id > 0) {
        $delete_query = mysqli_query($conn, "DELETE FROM absensi_guru WHERE id = $hapus_id");
        
        if ($delete_query) {
            echo "<div class='alert alert-success'>Data absensi berhasil dihapus.</div>";
            echo "<script>setTimeout(function(){ window.location.reload(); }, 1000);</script>";
        } else {
            echo "<div class='alert alert-danger'>Gagal menghapus data: " . mysqli_error($conn) . "</div>";
        }
    } else {
        echo "<div class='alert alert-danger'>Data tidak valid.</div>";
    }
}

// Konfigurasi pagination
$limit = 20;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1;
$offset = ($page - 1) * $limit;

// Ambil parameter filter
$tanggal = isset($_GET['tanggal']) ? $_GET['tanggal'] : date("Y-m-d");
$tanggal_akhir = isset($_GET['tanggal_akhir']) ? $_GET['tanggal_akhir'] : $tanggal;
$filter_tanggal = isset($_GET['filter_tanggal']) ? $_GET['filter_tanggal'] : 'hari';
$namaFilter = isset($_GET['nama']) ? $_GET['nama'] : "";
$statusFilter = isset($_GET['status']) ? $_GET['status'] : "";

// Format tanggal untuk tampilan
$tanggalTampil = date("d/m/Y", strtotime($tanggal));
$tanggalAkhirTampil = date("d/m/Y", strtotime($tanggal_akhir));

// Cek apakah tabel absensi_guru ada
$check_table = mysqli_query($conn, "SHOW TABLES LIKE 'absensi_guru'");
$table_exists = (mysqli_num_rows($check_table) > 0);

// Jika tabel absensi_guru tidak ada, buat tabel tersebut
if (!$table_exists) {
    echo "<div class='alert alert-warning'>Tabel absensi_guru belum tersedia. Silakan buat tabel terlebih dahulu.</div>";
    
    echo "<form method='POST' class='mb-4'>";
    echo "<button type='submit' name='create_table' class='btn btn-primary btn-create-table'><i class='bi bi-database-add'></i> Buat Tabel Absensi Guru</button>";
    echo "</form>";
    
    if (isset($_POST['create_table'])) {
        // Buat tabel absensi_guru dengan struktur yang benar
        $create_table = "CREATE TABLE absensi_guru (
            id INT(11) AUTO_INCREMENT PRIMARY KEY,
            guru_id INT(11) NOT NULL,
            tanggal DATE NOT NULL,
            jam_masuk TIME NULL,
            jam_pulang TIME NULL,
            status ENUM('H', 'I', 'S', 'A') DEFAULT 'H',
            keterangan VARCHAR(255) NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )";
        
        if (mysqli_query($conn, $create_table)) {
            // Insert data contoh
            $sample_data = [
                "INSERT INTO absensi_guru (guru_id, tanggal, jam_masuk, jam_pulang, status, keterangan) VALUES (1, CURDATE(), '06:45:23', '15:45:30', 'H', 'Tepat Waktu')",
                "INSERT INTO absensi_guru (guru_id, tanggal, jam_masuk, jam_pulang, status, keterangan) VALUES (2, CURDATE(), '07:25:10', '16:30:15', 'H', 'Telat')",
                "INSERT INTO absensi_guru (guru_id, tanggal, jam_masuk, status, keterangan) VALUES (3, CURDATE(), '06:50:00', 'H', 'Tepat Waktu')",
                "INSERT INTO absensi_guru (guru_id, tanggal, status, keterangan) VALUES (4, CURDATE(), 'I', 'Acara keluarga')"
            ];
            
            foreach ($sample_data as $query) {
                mysqli_query($conn, $query);
            }
            
            echo "<div class='alert alert-success'>Tabel absensi_guru berhasil dibuat dengan data contoh!</div>";
            $table_exists = true;
            echo "<script>setTimeout(function(){ window.location.reload(); }, 2000);</script>";
        } else {
            echo "<div class='alert alert-danger'>Gagal membuat tabel: " . mysqli_error($conn) . "</div>";
        }
    }
}

// Cek apakah tabel guru ada
$check_guru_table = mysqli_query($conn, "SHOW TABLES LIKE 'guru'");
$guru_table_exists = (mysqli_num_rows($check_guru_table) > 0);

// Jika tabel guru tidak ada, buat tabel tersebut
if (!$guru_table_exists && $table_exists) {
    $create_guru_table = "CREATE TABLE guru (
        id INT(11) AUTO_INCREMENT PRIMARY KEY,
        nip VARCHAR(20) NOT NULL,
        nama VARCHAR(100) NOT NULL,
        status ENUM('aktif', 'non-aktif') DEFAULT 'aktif',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )";
    
    if (mysqli_query($conn, $create_guru_table)) {
        // Insert data contoh guru
        $sample_guru = [
            "INSERT INTO guru (nip, nama) VALUES ('198203122005011001', 'Dr. Ahmad Susanto, M.Pd')",
            "INSERT INTO guru (nip, nama) VALUES ('197911052006042002', 'Drs. Budi Raharjo')",
            "INSERT INTO guru (nip, nama) VALUES ('198506152010012003', 'Siti Aminah, S.Pd')",
            "INSERT INTO guru (nip, nama) VALUES ('199005202015032004', 'Dewi Kusuma, S.Pd')"
        ];
        
        foreach ($sample_guru as $query) {
            mysqli_query($conn, $query);
        }
        
        echo "<div class='alert alert-success'>Tabel guru berhasil dibuat dengan data contoh!</div>";
        $guru_table_exists = true;
        echo "<script>setTimeout(function(){ window.location.reload(); }, 2000);</script>";
    } else {
        echo "<div class='alert alert-danger'>Gagal membuat tabel guru: " . mysqli_error($conn) . "</div>";
    }
}

// Query rekap hanya jika tabel sudah ada
$data = null;
$total_rows = 0;
if ($table_exists && $guru_table_exists) {
    // Periksa struktur tabel absensi_guru
    $check_columns = mysqli_query($conn, "SHOW COLUMNS FROM absensi_guru LIKE 'keterangan'");
    if (mysqli_num_rows($check_columns) == 0) {
        // Tambahkan kolom keterangan jika tidak ada
        $alter_query = mysqli_query($conn, "ALTER TABLE absensi_guru ADD COLUMN keterangan VARCHAR(255) NULL AFTER status");
        if (!$alter_query) {
            echo "<div class='alert alert-danger'>Gagal menambahkan kolom keterangan: " . mysqli_error($conn) . "</div>";
        }
    }
    
    // Query dasar
    $sql = "
        SELECT 
            a.id, 
            g.id AS guru_id, 
            g.nip,
            g.nama, 
            a.tanggal,
            a.jam_masuk, 
            a.jam_pulang,
            a.status,
            a.keterangan
        FROM absensi_guru a
        JOIN guru g ON a.guru_id = g.id
        WHERE g.status = 'aktif'
    ";
    
    $conditions = [];
    
    // Filter tanggal
    if ($filter_tanggal == 'hari') {
        $conditions[] = "a.tanggal = '" . mysqli_real_escape_string($conn, $tanggal) . "'";
    } else {
        $conditions[] = "a.tanggal BETWEEN '" . mysqli_real_escape_string($conn, $tanggal) . "' AND '" . mysqli_real_escape_string($conn, $tanggal_akhir) . "'";
    }
    
    // Filter lainnya
    if ($namaFilter !== "") {
        $conditions[] = "g.nama LIKE '%" . mysqli_real_escape_string($conn, $namaFilter) . "%'";
    }
    if ($statusFilter !== "") {
        $conditions[] = "a.status = '" . mysqli_real_escape_string($conn, $statusFilter) . "'";
    }
    
    // Gabungkan kondisi jika ada
    if (!empty($conditions)) {
        $sql .= " AND " . implode(" AND ", $conditions);
    }
    
    // Query untuk total data
    $count_sql = "SELECT COUNT(*) as total FROM ($sql) as count_table";
    $count_result = mysqli_query($conn, $count_sql);
    if ($count_result) {
        $count_row = mysqli_fetch_assoc($count_result);
        $total_rows = $count_row['total'];
    } else {
        echo "<div class='alert alert-danger'>Error dalam query count: " . mysqli_error($conn) . "</div>";
        $total_rows = 0;
    }
    
    // Tambahkan sorting dan pagination
    $sql .= " ORDER BY a.tanggal DESC, g.nama LIMIT $limit OFFSET $offset";
    
    $data = mysqli_query($conn, $sql);
    if (!$data) {
        echo "<div class='alert alert-danger'>Error dalam query: " . mysqli_error($conn) . "</div>";
        $data = null;
    }
}

// Fungsi untuk menentukan keterangan berdasarkan jam masuk
function getKeterangan($jam_masuk, $existing_keterangan) {
    // Jika sudah ada keterangan dan bukan Telat/Tepat Waktu, pertahankan
    if (!empty($existing_keterangan) && $existing_keterangan !== 'Tepat Waktu' && $existing_keterangan !== 'Telat') {
        return $existing_keterangan;
    }
    
    // Jika tidak ada jam masuk, kembalikan string kosong
    if (empty($jam_masuk)) {
        return $existing_keterangan;
    }
    
    // Tentukan keterangan berdasarkan jam masuk
    $jam_batas = '07:00:00';
    return (strtotime($jam_masuk) > strtotime($jam_batas)) ? 'Telat' : 'Tepat Waktu';
}

// Proses manual input absensi pulang
if (isset($_POST['manual_pulang'])) {
    $absensi_id = (int)$_POST['absensi_id'];
    $jam_pulang = date("H:i:s");
    
    if ($absensi_id > 0) {
        $update_query = mysqli_query($conn, "UPDATE absensi_guru SET jam_pulang='$jam_pulang' WHERE id=$absensi_id");
        
        if ($update_query) {
            echo "<div class='alert alert-success'>Absensi pulang berhasil dicatat.</div>";
            echo "<script>setTimeout(function(){ window.location.reload(); }, 1000);</script>";
        } else {
            echo "<div class='alert alert-danger'>Gagal mencatat absensi pulang: " . mysqli_error($conn) . "</div>";
        }
    } else {
        echo "<div class='alert alert-danger'>Data tidak valid.</div>";
    }
}

// Fungsi untuk mendapatkan teks status
function getStatusText($status) {
    switch($status) {
        case 'H': return 'Hadir';
        case 'I': return 'Izin';
        case 'S': return 'Sakit';
        case 'A': return 'Alpa';
        default: return $status;
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sistem Absensi QR - Rekap Kehadiran Guru</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <style>
        .status-hadir { color: green; }
        .status-terlambat { color: orange; }
        .status-tanpa-keterangan { color: red; }
        .status-izin { color: blue; }
        .status-sakit { color: purple; }
        .table th { background-color: #f8f9fa; }
        .notice { color: red; font-weight: bold; }
        .card-header { background-color: #f0f8ff; }
        .filter-section { background-color: #f8f9fa; border-radius: 5px; padding: 15px; }
        .btn-create-table { margin-top: 10px; }
        .badge-status { font-size: 0.85em; padding: 5px 10px; border-radius: 15px; }
        .pagination { justify-content: center; margin-top: 20px; }
        .export-buttons { margin-bottom: 15px; }
        .date-range { display: none; }
        .badge-tepat-waktu { background-color: #28a745; color: white; }
        .badge-telat { background-color: #ffc107; color: black; }
        .navbar-custom { background-color: #f8f9fa; border-bottom: 1px solid #dee2e6; }
    </style>
</head>
<body class="container mt-4">
    <!-- Navbar Custom -->
    <nav class="navbar navbar-expand-lg navbar-light navbar-custom mb-4">
        <div class="container-fluid">
            <a class="navbar-brand" href="dashboard.php">
                <i class="bi bi-house-door"></i> Dashboard
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item">
                        <a href="input_izin_guru.php" class="btn btn-outline-success me-2"><i class="bi bi-pencil-square"></i> Input Izin Guru</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>Rekap Kehadiran Guru</h2>
        <div>
            <a href="rekap_bulanan_guru.php" class="btn btn-info me-2"><i class="bi bi-calendar-month"></i> Rekap Bulanan</a>
        </div>
    </div>

    <div class="card mb-4">
        <div class="card-header">
            <h5 class="mb-0"><i class="bi bi-funnel"></i> Filter Data</h5>
        </div>
        <div class="card-body">
            <form method="GET" class="row g-3">
                <div class="col-md-3">
                    <label class="form-label"><strong>Jenis Filter Tanggal</strong></label>
                    <select name="filter_tanggal" id="filter_tanggal" class="form-select" onchange="toggleDateRange()">
                        <option value="hari" <?= $filter_tanggal == 'hari' ? 'selected' : '' ?>>Hari Ini</option>
                        <option value="rentang" <?= $filter_tanggal == 'rentang' ? 'selected' : '' ?>>Rentang Tanggal</option>
                    </select>
                </div>
                <div class="col-md-3" id="tanggal_mulai_container">
                    <label class="form-label"><strong>Tanggal</strong></label>
                    <input type="date" name="tanggal" value="<?= htmlspecialchars($tanggal) ?>" class="form-control">
                </div>
                <div class="col-md-3 date-range" id="tanggal_akhir_container">
                    <label class="form-label"><strong>Tanggal Akhir</strong></label>
                    <input type="date" name="tanggal_akhir" value="<?= htmlspecialchars($tanggal_akhir) ?>" class="form-control">
                </div>
                <div class="col-md-3">
                    <label class="form-label"><strong>Nama Guru</strong></label>
                    <input type="text" name="nama" value="<?= htmlspecialchars($namaFilter) ?>" class="form-control" placeholder="Cari nama...">
                </div>
                <div class="col-md-3">
                    <label class="form-label"><strong>Status</strong></label>
                    <select name="status" class="form-select">
                        <option value="">Semua Status</option>
                        <option value="H" <?= $statusFilter == 'H' ? 'selected' : '' ?>>Hadir</option>
                        <option value="I" <?= $statusFilter == 'I' ? 'selected' : '' ?>>Izin</option>
                        <option value="S" <?= $statusFilter == 'S' ? 'selected' : '' ?>>Sakit</option>
                        <option value="A" <?= $statusFilter == 'A' ? 'selected' : '' ?>>Alpa</option>
                    </select>
                </div>
                <div class="col-md-12 d-flex justify-content-end gap-2">
                    <button type="submit" class="btn btn-primary"><i class="bi bi-search"></i> Tampilkan</button>
                    <a href="rekap_guru.php" class="btn btn-outline-secondary">Reset</a>
                </div>
            </form>
        </div>
    </div>

    <?php if ($table_exists && $guru_table_exists): ?>
    <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0"><i class="bi bi-list-check"></i> Hasil Rekap Kehadiran Guru</h5>
            <div>
                <span class="badge bg-primary">Total: <?= $total_rows ?> Data</span>
                <div class="btn-group export-buttons ms-2">
                    <button type="button" class="btn btn-sm btn-success" data-bs-toggle="modal" data-bs-target="#exportModal">
                        <i class="bi bi-download"></i> Ekspor
                    </button>
                </div>
            </div>
        </div>
        <div class="card-body">
            <div class="row mb-3">
                <div class="col-md-4">
                    <strong>Periode:</strong> 
                    <?= $filter_tanggal == 'hari' ? $tanggalTampil : $tanggalTampil . ' - ' . $tanggalAkhirTampil ?>
                </div>
                <div class="col-md-4">
                    <strong>Status:</strong> <?= $statusFilter ? htmlspecialchars(getStatusText($statusFilter)) : 'Semua Status' ?>
                </div>
            </div>

            <?php if ($data && mysqli_num_rows($data) > 0): ?>
            <div class="table-responsive">
                <table class="table table-bordered table-striped table-hover">
                    <thead class="table-light">
                        <tr>
                            <th>No</th>
                            <th>Tanggal</th>
                            <th>NIP</th>
                            <th>Nama Guru</th>
                            <th>Jam Masuk</th>
                            <th>Jam Pulang</th>
                            <th>Status</th>
                            <th>Keterangan</th>
                            <th>Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $no = $offset + 1; while($row = mysqli_fetch_assoc($data)): 
                            $keterangan = getKeterangan($row['jam_masuk'], $row['keterangan']);
                        ?>
                            <tr>
                                <td><?= $no++ ?></td>
                                <td><?= date("d/m/Y", strtotime($row['tanggal'])) ?></td>
                                <td><?= htmlspecialchars($row['nip']) ?></td>
                                <td><?= htmlspecialchars($row['nama']) ?></td>
                                <td><?= !empty($row['jam_masuk']) ? htmlspecialchars($row['jam_masuk']) : '-' ?></td>
                                <td>
                                    <?php if (!empty($row['jam_pulang'])): ?>
                                        <span class="text-success"><?= htmlspecialchars($row['jam_pulang']) ?></span>
                                    <?php else: ?>
                                        <span class="text-danger">Belum absen pulang</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php 
                                    $status_class = '';
                                    $status_text = '';
                                    switch($row['status']) {
                                        case 'H': 
                                            $status_class = 'status-hadir'; 
                                            $status_text = 'Hadir';
                                            break;
                                        case 'I': 
                                            $status_class = 'status-izin'; 
                                            $status_text = 'Izin';
                                            break;
                                        case 'S': 
                                            $status_class = 'status-sakit'; 
                                            $status_text = 'Sakit';
                                            break;
                                        case 'A': 
                                            $status_class = 'status-tanpa-keterangan'; 
                                            $status_text = 'Alpa';
                                            break;
                                        default: 
                                            $status_text = $row['status'];
                                    }
                                    ?>
                                    <span class="badge badge-status <?= $status_class ?>">
                                        <?= $status_text ?>
                                    </span>
                                </td>
                                <td>
                                    <?php if ($keterangan === 'Tepat Waktu'): ?>
                                        <span class="badge badge-tepat-waktu">Tepat Waktu</span>
                                    <?php elseif ($keterangan === 'Telat'): ?>
                                        <span class="badge badge-telat">Telat</span>
                                    <?php else: ?>
                                        <?= !empty($keterangan) ? htmlspecialchars($keterangan) : '-' ?>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <div class="btn-group">
                                        <a href="riwayat_guru.php?id=<?= $row['guru_id'] ?>" class="btn btn-sm btn-info" title="Riwayat"><i class="bi bi-clock-history"></i></a>
                                        <?php if (empty($row['jam_pulang']) && $row['status'] == 'H'): ?>
                                        <button type="button" class="btn btn-sm btn-warning" data-bs-toggle="modal" data-bs-target="#pulangModal" 
                                                data-id="<?= $row['id'] ?>" data-nama="<?= htmlspecialchars($row['nama']) ?>"
                                                title="Input Absensi Pulang Manual">
                                            <i class="bi bi-pencil"></i>
                                        </button>
                                        <?php endif; ?>
                                        <!-- Tombol Hapus -->
                                        <button type="button" class="btn btn-sm btn-danger" data-bs-toggle="modal" data-bs-target="#hapusModal" 
                                                data-id="<?= $row['id'] ?>" data-nama="<?= htmlspecialchars($row['nama']) ?>"
                                                data-tanggal="<?= date('d/m/Y', strtotime($row['tanggal'])) ?>"
                                                title="Hapus Absensi">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>

            <!-- Pagination -->
            <?php if ($total_rows > $limit): ?>
            <nav aria-label="Page navigation">
                <ul class="pagination">
                    <?php if ($page > 1): ?>
                    <li class="page-item">
                        <a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['page' => $page - 1])) ?>" aria-label="Previous">
                            <span aria-hidden="true">&laquo;</span>
                        </a>
                    </li>
                    <?php endif; ?>

                    <?php
                    $total_pages = ceil($total_rows / $limit);
                    $start_page = max(1, $page - 2);
                    $end_page = min($total_pages, $start_page + 4);
                    
                    if ($end_page - $start_page < 4) {
                        $start_page = max(1, $end_page - 4);
                    }
                    
                    for ($i = $start_page; $i <= $end_page; $i++): 
                    ?>
                    <li class="page-item <?= $i == $page ? 'active' : '' ?>">
                        <a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['page' => $i])) ?>"><?= $i ?></a>
                    </li>
                    <?php endfor; ?>

                    <?php if ($page < $total_pages): ?>
                    <li class="page-item">
                        <a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['page' => $page + 1])) ?>" aria-label="Next">
                            <span aria-hidden="true">&raquo;</span>
                        </a>
                    </li>
                    <?php endif; ?>
                </ul>
            </nav>
            <?php endif; ?>

            <?php else: ?>
                <div class="alert alert-info text-center py-4">
                    <i class="bi bi-info-circle display-4"></i>
                    <h4 class="mt-3">Tidak ada data absensi</h4>
                    <p class="mb-0">Tidak ada data absensi untuk kriteria yang dipilih.</p>
                </div>
            <?php endif; ?>
        </div>
    </div>
    <?php endif; ?>

    <!-- Modal Input Manual Absensi Pulang -->
    <div class="modal fade" id="pulangModal" tabindex="-1" aria-labelledby="pulangModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="pulangModalLabel">Input Absensi Pulang Manual</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="POST">
                    <div class="modal-body">
                        <input type="hidden" name="absensi_id" id="modal_absensi_id">
                        <p>Anda akan mencatat absensi pulang untuk:</p>
                        <h5 id="modal_nama_guru" class="text-center mb-3"></h5>
                        <div class="mb-3">
                            <label class="form-label">Waktu Pulang</label>
                            <input type="time" class="form-control" value="<?= date('H:i') ?>" disabled>
                            <div class="form-text">Waktu saat ini akan dicatat sebagai jam pulang</div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                        <button type="submit" name="manual_pulang" class="btn btn-primary">Simpan Absensi Pulang</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Modal Konfirmasi Hapus -->
    <div class="modal fade" id="hapusModal" tabindex="-1" aria-labelledby="hapusModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="hapusModalLabel">Konfirmasi Hapus Absensi</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="POST">
                    <div class="modal-body">
                        <input type="hidden" name="hapus_id" id="modal_hapus_id">
                        <p>Apakah Anda yakin ingin menghapus data absensi berikut?</p>
                        <div class="alert alert-warning">
                            <strong>Nama Guru:</strong> <span id="modal_hapus_nama"></span><br>
                            <strong>Tanggal:</strong> <span id="modal_hapus_tanggal"></span>
                        </div>
                        <p class="text-danger">Data yang dihapus tidak dapat dikembalikan!</p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                        <button type="submit" name="hapus_absensi" class="btn btn-danger">Hapus</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Modal Ekspor Data -->
    <div class="modal fade" id="exportModal" tabindex="-1" aria-labelledby="exportModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exportModalLabel">Ekspor Data</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>Pilih format ekspor:</p>
                    <div class="d-grid gap-2">
                        <a href="export_guru.php?<?= http_build_query(array_merge($_GET, ['format' => 'excel'])) ?>" class="btn btn-success">
                            <i class="bi bi-file-earmark-excel"></i> Excel
                        </a>
                        <a href="export_guru.php?<?= http_build_query(array_merge($_GET, ['format' => 'pdf'])) ?>" class="btn btn-danger">
                            <i class="bi bi-file-earmark-pdf"></i> PDF
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Script untuk modal input manual absensi pulang
        var pulangModal = document.getElementById('pulangModal');
        if (pulangModal) {
            pulangModal.addEventListener('show.bs.modal', function (event) {
                var button = event.relatedTarget;
                var absensiId = button.getAttribute('data-id');
                var namaGuru = button.getAttribute('data-nama');
                
                document.getElementById('modal_absensi_id').value = absensiId;
                document.getElementById('modal_nama_guru').textContent = namaGuru;
            });
        }

        // Script untuk modal hapus
        var hapusModal = document.getElementById('hapusModal');
        if (hapusModal) {
            hapusModal.addEventListener('show.bs.modal', function (event) {
                var button = event.relatedTarget;
                var absensiId = button.getAttribute('data-id');
                var namaGuru = button.getAttribute('data-nama');
                var tanggalAbsensi = button.getAttribute('data-tanggal');
                
                document.getElementById('modal_hapus_id').value = absensiId;
                document.getElementById('modal_hapus_nama').textContent = namaGuru;
                document.getElementById('modal_hapus_tanggal').textContent = tanggalAbsensi;
            });
        }

        // Toggle tampilan filter tanggal
        function toggleDateRange() {
            var filterType = document.getElementById('filter_tanggal').value;
            var tanggalAkhirContainer = document.getElementById('tanggal_akhir_container');
            var tanggalMulaiLabel = document.querySelector('#tanggal_mulai_container label');
            
            if (filterType === 'rentang') {
                tanggalAkhirContainer.style.display = 'block';
                if (tanggalMulaiLabel) {
                    tanggalMulaiLabel.textContent = 'Tanggal Mulai';
                }
            } else {
                if (tanggalAkhirContainer) {
                    tanggalAkhirContainer.style.display = 'none';
                }
                if (tanggalMulaiLabel) {
                    tanggalMulaiLabel.textContent = 'Tanggal';
                }
            }
        }

        // Jalankan saat halaman dimuat
        document.addEventListener('DOMContentLoaded', function() {
            toggleDateRange();
        });
    </script>
</body>
</html>