<!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</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; }
        .share-dropdown .dropdown-menu { min-width: 280px; padding: 10px; }
        .share-dropdown .dropdown-item { padding: 8px 12px; border-radius: 5px; }
        .share-dropdown .dropdown-item:hover { background: #f0fdf4; }
        .share-dropdown .dropdown-item i { margin-right: 10px; font-size: 1.1em; }
        .wa-link-text { font-size: 12px; color: #6c757d; word-break: break-all; }
        .share-content { 
            background: #f8f9fa; 
            padding: 15px; 
            border-radius: 8px; 
            border: 1px solid #e9ecef;
            font-family: 'Courier New', monospace;
            white-space: pre-wrap;
            max-height: 400px;
            overflow-y: auto;
        }
        .copy-btn { cursor: pointer; }
        .copy-btn:hover { opacity: 0.8; }
        .copy-success { color: #28a745; }
    </style>
</head>
<body class="container mt-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>Rekap Kehadiran</h2>
        <div>
            <?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");

            // Ambil data profil untuk link WhatsApp
            $profil_query = mysqli_query($conn, "SELECT link_grup_wa, link_saluran_wa FROM profil_sekolah LIMIT 1");
            $profil_data = mysqli_fetch_assoc($profil_query);
            $link_grup = isset($profil_data['link_grup_wa']) ? $profil_data['link_grup_wa'] : '';
            $link_saluran = isset($profil_data['link_saluran_wa']) ? $profil_data['link_saluran_wa'] : '';

            // Ambil data absensi hari ini untuk share
            $tanggal_hari_ini = date("Y-m-d");
            $share_data = [];
            $share_query = mysqli_query($conn, "
                SELECT 
                    s.nama,
                    s.kelas,
                    s.nis,
                    a.jam AS jam_masuk,
                    a.jam_pulang,
                    a.status,
                    a.keterangan
                FROM absensi a
                JOIN siswa s ON a.siswa_id = s.id
                WHERE a.tanggal = '$tanggal_hari_ini' AND s.status = 'aktif'
                ORDER BY s.kelas, s.nama
            ");
            
            if ($share_query) {
                while ($row = mysqli_fetch_assoc($share_query)) {
                    $share_data[] = $row;
                }
            }

            // Generate konten share
            $share_content = "";
            if (count($share_data) > 0) {
                $share_content = "📋 REKAP ABSENSI " . strtoupper(date('d F Y')) . "\n";
                $share_content .= "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
                
                $no = 1;
                $kelas_sebelum = '';
                $hadir = 0; $izin = 0; $sakit = 0; $alpa = 0;
                
                foreach ($share_data as $row) {
                    $status_text = '';
                    switch($row['status']) {
                        case 'H': $status_text = '✅ HADIR'; $hadir++; break;
                        case 'I': $status_text = '📝 IZIN'; $izin++; break;
                        case 'S': $status_text = '🏥 SAKIT'; $sakit++; break;
                        case 'A': $status_text = '❌ ALPA'; $alpa++; break;
                        default: $status_text = $row['status'];
                    }
                    
                    if ($kelas_sebelum != $row['kelas']) {
                        if ($kelas_sebelum != '') $share_content .= "\n";
                        $share_content .= "【 KELAS {$row['kelas']} 】\n";
                        $kelas_sebelum = $row['kelas'];
                    }
                    
                    $jam_masuk = !empty($row['jam_masuk']) ? date('H:i', strtotime($row['jam_masuk'])) : '-';
                    $jam_pulang = !empty($row['jam_pulang']) ? date('H:i', strtotime($row['jam_pulang'])) : '-';
                    
                    $share_content .= sprintf("%2d. %-20s | %s | Masuk: %s | Pulang: %s\n", 
                        $no++, 
                        $row['nama'],
                        $status_text,
                        $jam_masuk,
                        $jam_pulang
                    );
                }
                
                $share_content .= "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
                $share_content .= "Total Siswa: " . count($share_data) . " orang\n";
                $share_content .= "✅ Hadir: $hadir | 📝 Izin: $izin | 🏥 Sakit: $sakit | ❌ Alpa: $alpa";
            }

            // Encode untuk URL (digunakan untuk wa.me)
            $encoded_content = urlencode($share_content);
            ?>
            
            <!-- Dropdown Share -->
            <?php if (!empty($link_grup) || !empty($link_saluran) || count($share_data) > 0): ?>
            <div class="btn-group share-dropdown">
                <button type="button" class="btn btn-success dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
                    <i class="bi bi-share"></i> Share
                </button>
                <ul class="dropdown-menu dropdown-menu-end">
                    <?php if (!empty($link_grup) && count($share_data) > 0): ?>
                    <li>
                        <a href="<?= htmlspecialchars($link_grup) ?>" target="_blank" class="dropdown-item" 
                           onclick="return shareToGrup('<?= htmlspecialchars($link_grup) ?>')">
                            <i class="bi bi-people" style="color: #25D366;"></i> 
                            <strong>Share ke Grup WhatsApp</strong>
                            <div class="wa-link-text">Klik untuk buka grup dan paste teks</div>
                        </a>
                    </li>
                    <?php endif; ?>
                    <?php if (!empty($link_saluran) && count($share_data) > 0): ?>
                    <li>
                        <a href="<?= htmlspecialchars($link_saluran) ?>" target="_blank" class="dropdown-item"
                           onclick="return shareToSaluran('<?= htmlspecialchars($link_saluran) ?>')">
                            <i class="bi bi-megaphone" style="color: #25D366;"></i> 
                            <strong>Share ke Saluran WhatsApp</strong>
                            <div class="wa-link-text">Klik untuk buka saluran dan paste teks</div>
                        </a>
                    </li>
                    <?php endif; ?>
                    <?php if (count($share_data) > 0): ?>
                    <li><hr class="dropdown-divider"></li>
                    <li>
                        <button type="button" class="dropdown-item" data-bs-toggle="modal" data-bs-target="#shareModal">
                            <i class="bi bi-eye" style="color: #0d6efd;"></i> 
                            <strong>Preview & Copy Data</strong>
                            <div class="wa-link-text"><?= date('d/m/Y') ?> - <?= count($share_data) ?> siswa</div>
                        </button>
                    </li>
                    <?php endif; ?>
                    <?php if (count($share_data) == 0): ?>
                    <li>
                        <button type="button" class="dropdown-item" disabled>
                            <i class="bi bi-info-circle"></i> 
                            <strong>Belum ada data absensi hari ini</strong>
                        </button>
                    </li>
                    <?php endif; ?>
                </ul>
            </div>
            <?php endif; ?>
            
            <a href="dashboard.php" class="btn btn-secondary"><i class="bi bi-arrow-left"></i> Kembali</a>
        </div>
    </div>

    <!-- Modal Preview Data Absensi -->
    <div class="modal fade" id="shareModal" tabindex="-1" aria-labelledby="shareModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="shareModalLabel">
                        <i class="bi bi-clipboard-data"></i> Data Absensi <?= date('d/m/Y') ?>
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <?php if (count($share_data) > 0): ?>
                        <div class="mb-3">
                            <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
                                <span class="badge bg-primary">Total: <?= count($share_data) ?> Siswa</span>
                                <div class="d-flex gap-2 flex-wrap">
                                    <button class="btn btn-sm btn-outline-primary copy-btn" onclick="copyShareContent()">
                                        <i class="bi bi-clipboard"></i> Salin Teks
                                    </button>
                                    <?php if (!empty($link_grup)): ?>
                                    <button class="btn btn-sm btn-success" onclick="shareToGrup('<?= htmlspecialchars($link_grup) ?>')">
                                        <i class="bi bi-whatsapp"></i> Buka Grup
                                    </button>
                                    <?php endif; ?>
                                    <?php if (!empty($link_saluran)): ?>
                                    <button class="btn btn-sm btn-success" onclick="shareToSaluran('<?= htmlspecialchars($link_saluran) ?>')">
                                        <i class="bi bi-megaphone"></i> Buka Saluran
                                    </button>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                        <div class="share-content" id="shareContent"><?= htmlspecialchars($share_content) ?></div>
                        <div class="mt-3 alert alert-info">
                            <i class="bi bi-info-circle"></i> 
                            <strong>Cara share:</strong> Klik tombol <strong>"Buka Grup"</strong> atau <strong>"Buka Saluran"</strong>, 
                            lalu <strong>paste (Ctrl+V)</strong> teks di atas ke chat.
                        </div>
                    <?php else: ?>
                        <div class="alert alert-info text-center py-4">
                            <i class="bi bi-info-circle display-4"></i>
                            <h4 class="mt-3">Belum ada data absensi</h4>
                            <p class="mb-0">Belum ada siswa yang melakukan absensi hari ini.</p>
                        </div>
                    <?php endif; ?>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button>
                    <?php if (count($share_data) > 0): ?>
                        <button class="btn btn-outline-primary" onclick="copyShareContent()">
                            <i class="bi bi-clipboard"></i> Salin Teks
                        </button>
                        <?php if (!empty($link_grup)): ?>
                        <button class="btn btn-success" onclick="shareToGrup('<?= htmlspecialchars($link_grup) ?>')">
                            <i class="bi bi-whatsapp"></i> Buka Grup
                        </button>
                        <?php endif; ?>
                        <?php if (!empty($link_saluran)): ?>
                        <button class="btn btn-success" onclick="shareToSaluran('<?= htmlspecialchars($link_saluran) ?>')">
                            <i class="bi bi-megaphone"></i> Buka Saluran
                        </button>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <?php
    // Konfigurasi pagination
    $limit = 20;
    $page = isset($_GET['page']) ? (int)$_GET['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';
    $kelasFilter = isset($_GET['kelas']) ? $_GET['kelas'] : "";
    $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));

    // Ambil daftar kelas unik
    $kelasList = [];
    $qKelas = mysqli_query($conn, "SELECT DISTINCT kelas FROM siswa WHERE status = 'aktif' ORDER BY kelas ASC");
    if ($qKelas) {
        while ($row = mysqli_fetch_assoc($qKelas)) {
            $kelasList[] = $row['kelas'];
        }
    }

    // Cek apakah kolom jam_pulang ada di tabel absensi
    $check_jam_pulang = mysqli_query($conn, "SHOW COLUMNS FROM absensi LIKE 'jam_pulang'");
    $jam_pulang_exists = (mysqli_num_rows($check_jam_pulang) > 0);
    
    // Jika kolom jam_pulang tidak ada, buat kolom tersebut
    if (!$jam_pulang_exists) {
        echo "<div class='alert alert-warning'>Kolom jam_pulang belum tersedia di tabel absensi. Silakan buat kolom terlebih dahulu.</div>";
        
        echo "<form method='POST' class='mb-4'>";
        echo "<button type='submit' name='create_column' class='btn btn-primary btn-create-table'><i class='bi bi-database-add'></i> Buat Kolom Jam Pulang</button>";
        echo "</form>";
        
        if (isset($_POST['create_column'])) {
            $alter_query = mysqli_query($conn, "ALTER TABLE absensi ADD COLUMN jam_pulang TIME NULL AFTER jam");
            if ($alter_query) {
                echo "<div class='alert alert-success'>Kolom jam_pulang berhasil dibuat!</div>";
                $jam_pulang_exists = true;
                echo "<script>setTimeout(function(){ window.location.reload(); }, 2000);</script>";
            } else {
                echo "<div class='alert alert-danger'>Gagal membuat kolom: " . mysqli_error($conn) . "</div>";
            }
        }
    }

    // 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 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>";
        }
    }

    // Proses hapus absensi
    if (isset($_POST['hapus_absensi']) && $_SESSION['role'] == 'admin') {
        $absensi_id = (int)$_POST['absensi_id'];
        
        if ($absensi_id > 0) {
            $delete_query = mysqli_query($conn, "DELETE FROM absensi WHERE id = $absensi_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>";
            }
        }
    }

    // Query rekap hanya jika kolom jam_pulang sudah ada
    $data = null;
    $total_rows = 0;
    if ($jam_pulang_exists) {
        $sql = "
            SELECT 
                a.id, 
                s.id AS siswa_id, 
                s.nis,
                s.nama, 
                s.kelas, 
                a.jam AS jam_masuk, 
                a.jam_pulang,
                a.status,
                a.keterangan,
                a.tanggal
            FROM absensi a
            JOIN siswa s ON a.siswa_id = s.id
            WHERE s.status = 'aktif'
        ";
        
        if ($filter_tanggal == 'hari') {
            $sql .= " AND a.tanggal = '" . mysqli_real_escape_string($conn, $tanggal) . "'";
        } else {
            $sql .= " AND a.tanggal BETWEEN '" . mysqli_real_escape_string($conn, $tanggal) . "' AND '" . mysqli_real_escape_string($conn, $tanggal_akhir) . "'";
        }
        
        if ($kelasFilter !== "") {
            $sql .= " AND s.kelas = '" . mysqli_real_escape_string($conn, $kelasFilter) . "'";
        }
        if ($namaFilter !== "") {
            $sql .= " AND s.nama LIKE '%" . mysqli_real_escape_string($conn, $namaFilter) . "%'";
        }
        if ($statusFilter !== "") {
            $sql .= " AND a.status = '" . mysqli_real_escape_string($conn, $statusFilter) . "'";
        }
        
        // 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'];
        }
        
        $sql .= " ORDER BY a.tanggal DESC, s.kelas, s.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 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;
        }
    }
    ?>

    <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>Kelas</strong></label>
                    <select name="kelas" class="form-select">
                        <option value="">Semua Kelas</option>
                        <?php foreach ($kelasList as $kelas): ?>
                            <option value="<?= htmlspecialchars($kelas) ?>" <?= ($kelas == $kelasFilter) ? "selected" : "" ?>>
                                <?= htmlspecialchars($kelas) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label"><strong>Nama Siswa</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="jam_absensi.php" class="btn btn-outline-secondary">Reset</a>
                </div>
            </form>
        </div>
    </div>

    <?php if ($jam_pulang_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</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>Kelas:</strong> <?= $kelasFilter ? htmlspecialchars($kelasFilter) : 'Semua Kelas' ?>
                </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>NIS</th>
                            <th>Nama</th>
                            <th>Kelas</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)): ?>
                            <tr>
                                <td><?= $no++ ?></td>
                                <td><?= date("d/m/Y", strtotime($row['tanggal'])) ?></td>
                                <td><?= htmlspecialchars($row['nis']) ?></td>
                                <td><?= htmlspecialchars($row['nama']) ?></td>
                                <td><?= htmlspecialchars($row['kelas']) ?></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><?= !empty($row['keterangan']) ? htmlspecialchars($row['keterangan']) : '-' ?></td>
                                <td>
                                    <div class="btn-group">
                                        <a href="riwayat.php?id=<?= $row['siswa_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="<?= $row['nama'] ?>"
                                                title="Input Absensi Pulang Manual">
                                            <i class="bi bi-pencil"></i>
                                        </button>
                                        <?php endif; ?>
                                        <?php if ($_SESSION['role'] == 'admin'): ?>
                                        <button type="button" class="btn btn-sm btn-danger" data-bs-toggle="modal" data-bs-target="#hapusModal" 
                                                data-id="<?= $row['id'] ?>" data-nama="<?= $row['nama'] ?>" data-tanggal="<?= date('d/m/Y', strtotime($row['tanggal'])) ?>"
                                                title="Hapus Absensi">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>

            <?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_siswa" 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 Hapus Absensi -->
    <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">Hapus Data 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="absensi_id" id="hapus_absensi_id">
                        <p>Anda yakin ingin menghapus data absensi ini?</p>
                        <div class="alert alert-warning">
                            <strong>Detail:</strong><br>
                            Nama: <span id="hapus_nama_siswa"></span><br>
                            Tanggal: <span id="hapus_tanggal"></span>
                        </div>
                        <p class="text-danger"><strong>Peringatan:</strong> Tindakan ini tidak dapat dibatalkan!</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 Data</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.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.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>
        // Variable untuk menyimpan konten share
        var shareContent = <?= json_encode($share_content) ?>;

        // 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 namaSiswa = button.getAttribute('data-nama');
                
                document.getElementById('modal_absensi_id').value = absensiId;
                document.getElementById('modal_nama_siswa').textContent = namaSiswa;
            });
        }

        // Script untuk modal hapus absensi
        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 namaSiswa = button.getAttribute('data-nama');
                var tanggal = button.getAttribute('data-tanggal');
                
                document.getElementById('hapus_absensi_id').value = absensiId;
                document.getElementById('hapus_nama_siswa').textContent = namaSiswa;
                document.getElementById('hapus_tanggal').textContent = tanggal;
            });
        }

        // 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';
                tanggalMulaiLabel.textContent = 'Tanggal Mulai';
            } else {
                tanggalAkhirContainer.style.display = 'none';
                tanggalMulaiLabel.textContent = 'Tanggal';
            }
        }

        document.addEventListener('DOMContentLoaded', function() {
            toggleDateRange();
        });

        // Fungsi untuk copy konten share
        function copyShareContent() {
            var content = document.getElementById('shareContent');
            if (!content) return;
            
            var range = document.createRange();
            range.selectNode(content);
            window.getSelection().removeAllRanges();
            window.getSelection().addRange(range);
            
            try {
                document.execCommand('copy');
                var btn = document.querySelector('.copy-btn');
                if (btn) {
                    var originalText = btn.innerHTML;
                    btn.innerHTML = '<i class="bi bi-check"></i> Tersalin!';
                    setTimeout(function() {
                        btn.innerHTML = originalText;
                    }, 2000);
                }
            } catch (err) {
                alert('Gagal menyalin teks. Silakan copy manual.');
            }
            
            window.getSelection().removeAllRanges();
        }

        // Fungsi share ke Grup WhatsApp
        function shareToGrup(link) {
            // Salin teks ke clipboard dulu
            copyShareContent();
            // Buka link grup di tab baru
            window.open(link, '_blank');
            return false;
        }

        // Fungsi share ke Saluran WhatsApp
        function shareToSaluran(link) {
            // Salin teks ke clipboard dulu
            copyShareContent();
            // Buka link saluran di tab baru
            window.open(link, '_blank');
            return false;
        }
    </script>
</body>
</html>