<!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; }
    </style>
</head>
<body class="container mt-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>Rekap Kehadiran</h2>
        <div>
            <a href="absensi.php" class="btn btn-outline-primary me-2"><i class="bi bi-qr-code"></i> Absensi</a>
            <a href="dashboard.php" class="btn btn-secondary"><i class="bi bi-arrow-left"></i> Kembali</a>
        </div>
    </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");

    // Konfigurasi pagination
    $limit = 20; // Jumlah data per halaman
    $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>";
        
        // Tombol untuk membuat kolom
        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>";
        
        // Proses pembuatan kolom jika tombol ditekan
        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;
                // Refresh halaman setelah 2 detik
                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 (jika diperlukan)
    if (isset($_POST['manual_pulang'])) {
        $absensi_id = (int)$_POST['absensi_id'];
        $jam_pulang = date("H:i:s");
        
        // Validasi input
        if ($absensi_id > 0) {
            // Update dengan jam_pulang
            $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) {
        // Query dasar
        $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'
        ";
        
        // Filter tanggal
        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) . "'";
        }
        
        // Filter lainnya
        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 (untuk pagination)
        $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'];
        }
        
        // Tambahkan sorting dan pagination
        $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="rekap.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; ?>
                                        
                                        <!-- Tombol Hapus - Hanya Tampil untuk Admin -->
                                        <?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>

            <!-- 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_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>
        // Script untuk modal input manual absensi pulang
        var pulangModal = document.getElementById('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');
        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';
            }
        }

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