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

include "config.php";
// Tambahkan timezone WIB
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);

// Query rekap data absensi guru - PERBAIKAN UTAMA
$data = null;
$total_rows = 0;

// Debug: Cek data yang ada di absensi_guru
$debug_sql = "SELECT 
    a.id, 
    a.guru_id, 
    a.tanggal,
    a.jam_masuk, 
    a.jam_pulang,
    a.status,
    a.operator,
    a.keterangan,
    a.created_at,
    g.nama as guru_nama,
    g.nip as guru_nip,
    ug.nama as users_guru_nama,
    ug.username as users_guru_username
FROM absensi_guru a
LEFT JOIN guru g ON a.guru_id = g.id
LEFT JOIN users_guru ug ON a.guru_id = ug.id
ORDER BY a.tanggal DESC
LIMIT 10";

$debug_result = mysqli_query($conn, $debug_sql);

if ($table_exists) {
    // PERBAIKAN QUERY: Gunakan COALESCE untuk mendapatkan nama dari berbagai sumber
    $sql = "
        SELECT 
            a.id, 
            a.guru_id, 
            a.tanggal,
            a.jam_masuk, 
            a.jam_pulang,
            a.status,
            a.operator,
            a.keterangan,
            a.created_at,
            -- Coba dapatkan nama dari berbagai sumber secara berurutan
            COALESCE(
                g.nama, 
                ug.nama, 
                CASE 
                    WHEN a.operator IS NOT NULL AND a.operator != '' 
                    THEN CONCAT('Operator: ', a.operator) 
                    ELSE CONCAT('Guru #', a.guru_id) 
                END
            ) AS nama_guru,
            COALESCE(g.nip, ug.username, '') AS nip_guru
        FROM absensi_guru a
        LEFT JOIN guru g ON a.guru_id = g.id
        LEFT JOIN users_guru ug ON a.guru_id = ug.id
        WHERE 1=1
    ";
    
    $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 - PERBAIKAN: Cari di semua sumber nama
    if ($namaFilter !== "") {
        $conditions[] = "(g.nama LIKE '%" . mysqli_real_escape_string($conn, $namaFilter) . "%' 
                         OR ug.nama LIKE '%" . mysqli_real_escape_string($conn, $namaFilter) . "%'
                         OR a.operator 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 "<!-- Error count: " . mysqli_error($conn) . " -->";
        $total_rows = 0;
    }
    
    // Tambahkan sorting dan pagination
    $sql .= " ORDER BY a.tanggal DESC, a.created_at DESC LIMIT $limit OFFSET $offset";
    
    $data = mysqli_query($conn, $sql);
    if (!$data) {
        echo "<!-- Error query: " . mysqli_error($conn) . " -->";
        $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;
    }
}

// Fungsi untuk mendapatkan nama guru dari berbagai sumber
function getNamaGuru($conn, $guru_id, $operator) {
    // Coba dari tabel guru
    $query = "SELECT nama FROM guru WHERE id = $guru_id";
    $result = mysqli_query($conn, $query);
    if ($result && mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
        return $row['nama'];
    }
    
    // Coba dari tabel users_guru
    $query = "SELECT nama FROM users_guru WHERE id = $guru_id";
    $result = mysqli_query($conn, $query);
    if ($result && mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
        return $row['nama'];
    }
    
    // Jika tidak ditemukan, gunakan operator atau ID
    if (!empty($operator) && $operator != '') {
        return "Operator: $operator";
    }
    
    return "Guru #$guru_id";
}
?>

<!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; }
        .text-muted-small { font-size: 0.85rem; color: #6c757d; }
        .debug-info { display: none; }
    </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): ?>
    <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 ?>
                    <small class="text-muted">(WIB)</small> <!-- UBAH WITA MENJADI WIB -->
                </div>
                <div class="col-md-4">
                    <strong>Status:</strong> <?= $statusFilter ? htmlspecialchars(getStatusText($statusFilter)) : 'Semua Status' ?>
                </div>
                <div class="col-md-4 text-end">
                    <small class="text-muted-small">Data terbaru ditampilkan terlebih dahulu</small>
                </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']);
                            $nama_guru = $row['nama_guru'];
                            $nip_guru = $row['nip_guru'];
                        ?>
                            <tr>
                                <td><?= $no++ ?></td>
                                <td><?= date("d/m/Y", strtotime($row['tanggal'])) ?></td>
                                <td><?= !empty($nip_guru) ? htmlspecialchars($nip_guru) : '-' ?></td>
                                <td><?= htmlspecialchars($nama_guru) ?></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($nama_guru) ?>"
                                                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($nama_guru) ?>"
                                                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>
                    <?php if ($debug_result && mysqli_num_rows($debug_result) > 0): ?>
                    <div class="mt-3 debug-info">
                        <small class="text-muted">
                            Data debug ditemukan: 
                            <?php 
                            $debug_count = 0;
                            while($debug = mysqli_fetch_assoc($debug_result)): 
                                $debug_count++;
                                echo "<br>Guru ID: {$debug['guru_id']}, Nama: {$debug['guru_nama']}, Operator: {$debug['operator']}";
                            endwhile; 
                            ?>
                        </small>
                    </div>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>
    <?php else: ?>
        <div class="alert alert-warning">
            <i class="bi bi-exclamation-triangle"></i>
            Tabel absensi_guru belum tersedia di database.
        </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 (<?= date('H:i') ?> WIB) akan dicatat sebagai jam pulang</div> <!-- UBAH WITA MENJADI WIB -->
                        </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>