<?php
session_start();
require_once 'config.php';

// Konfigurasi pagination
$limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;
$search = isset($_GET['search']) ? mysqli_real_escape_string($conn, $_GET['search']) : '';
$filter_hari = isset($_GET['filter_hari']) ? mysqli_real_escape_string($conn, $_GET['filter_hari']) : '';
$filter_mapel = isset($_GET['filter_mapel']) ? mysqli_real_escape_string($conn, $_GET['filter_mapel']) : '';

// Query untuk mendapatkan data kehadiran dengan pagination dan search
$where = " WHERE 1=1";
if (!empty($search)) {
    $where .= " AND (us.nama LIKE '%$search%' OR ump.nama_mapel LIKE '%$search%' OR us.nis LIKE '%$search%')";
}
if (!empty($filter_hari)) {
    $where .= " AND uk.hari = '$filter_hari'";
}
if (!empty($filter_mapel)) {
    $where .= " AND uk.kode_mapel = '$filter_mapel'";
}

$query_count = "
    SELECT COUNT(*) as total 
    FROM ujn_kehadiran uk
    JOIN ujn_siswa us ON uk.nis = us.nis
    JOIN ujn_mata_pelajaran ump ON uk.kode_mapel = ump.kode_mapel
    $where
";
$result_count = mysqli_query($conn, $query_count);
$total_data = mysqli_fetch_assoc($result_count)['total'];
$total_pages = ceil($total_data / $limit);

// Query data dengan pagination
$query = "
    SELECT uk.nis, us.nama, us.kelas, uk.kode_mapel, ump.nama_mapel, uk.hari, uk.tanggal, uk.jam 
    FROM ujn_kehadiran uk
    JOIN ujn_siswa us ON uk.nis = us.nis
    JOIN ujn_mata_pelajaran ump ON uk.kode_mapel = ump.kode_mapel
    $where
    ORDER BY uk.tanggal DESC, uk.jam DESC
    LIMIT $limit OFFSET $offset
";
$result = mysqli_query($conn, $query);

// Query untuk mendapatkan daftar hari unik
$query_hari = "SELECT DISTINCT hari FROM ujn_kehadiran ORDER BY 
               CASE hari 
                   WHEN 'Senin' THEN 1
                   WHEN 'Selasa' THEN 2
                   WHEN 'Rabu' THEN 3
                   WHEN 'Kamis' THEN 4
                   WHEN 'Jumat' THEN 5
                   WHEN 'Sabtu' THEN 6
                   WHEN 'Minggu' THEN 7
               END";
$result_hari = mysqli_query($conn, $query_hari);

// Query untuk mendapatkan daftar mata pelajaran
$query_mapel = "SELECT kode_mapel, nama_mapel FROM ujn_mata_pelajaran ORDER BY nama_mapel";
$result_mapel = mysqli_query($conn, $query_mapel);

// Hitung data yang ditampilkan
$start_data = $offset + 1;
$end_data = min($offset + $limit, $total_data);
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sistem Kehadiran Ujian</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        .hero-section {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 80px 0;
            margin-bottom: 40px;
        }
        .stats-card {
            background: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .table-container {
            background: white;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        .login-btn {
            position: absolute;
            top: 20px;
            right: 20px;
        }
        .pagination .page-link {
            color: #667eea;
        }
        .pagination .page-item.active .page-link {
            background-color: #667eea;
            border-color: #667eea;
        }
        .search-loading {
            display: none;
            position: absolute;
            right: 10px;
            top: 50%;
            transform: translateY(-50%);
        }
        .filter-section {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
        }
        .badge-hari {
            font-size: 0.8em;
            padding: 0.4em 0.6em;
        }
        .btn-reset {
            background-color: #6c757d;
            border-color: #6c757d;
            color: white;
        }
        .btn-reset:hover {
            background-color: #5a6268;
            border-color: #545b62;
            color: white;
        }
    </style>
</head>
<body>
    <!-- Hero Section -->
    <div class="hero-section text-center position-relative">
        <a href="login.php" class="btn btn-light login-btn">
            <i class="fas fa-sign-in-alt"></i> Login
        </a>

        <div class="container">
            <h1 class="display-4 fw-bold mb-3">
                <i class="fas fa-clipboard-check"></i> Sistem Kehadiran Ujian
            </h1>
            <p class="lead mb-4">Sistem digital untuk memantau kehadiran siswa selama ujian</p>
            
            <div class="row justify-content-center">
                <div class="col-md-8">
                    <div class="row">
                        <div class="col-md-4">
                            <div class="stats-card text-dark text-center">
                                <i class="fas fa-users fa-3x text-primary mb-3"></i>
                                <h3>
                                    <?php 
                                    $total_siswa = mysqli_query($conn, "SELECT COUNT(*) as total FROM ujn_siswa");
                                    echo mysqli_fetch_assoc($total_siswa)['total'];
                                    ?>
                                </h3>
                                <p class="mb-0">Total Siswa</p>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="stats-card text-dark text-center">
                                <i class="fas fa-book fa-3x text-success mb-3"></i>
                                <h3>
                                    <?php 
                                    $total_mapel = mysqli_query($conn, "SELECT COUNT(*) as total FROM ujn_mata_pelajaran");
                                    echo mysqli_fetch_assoc($total_mapel)['total'];
                                    ?>
                                </h3>
                                <p class="mb-0">Mata Pelajaran</p>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="stats-card text-dark text-center">
                                <i class="fas fa-calendar-check fa-3x text-warning mb-3"></i>
                                <h3>
                                    <?php 
                                    $total_kehadiran = mysqli_query($conn, "SELECT COUNT(*) as total FROM ujn_kehadiran");
                                    echo mysqli_fetch_assoc($total_kehadiran)['total'];
                                    ?>
                                </h3>
                                <p class="mb-0">Total Kehadiran</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Data Kehadiran Terbaru -->
    <div class="container">
        <div class="table-container">
            <div class="p-4 border-bottom">
                <div class="row align-items-center">
                    <div class="col-md-6">
                        <h3 class="mb-0">
                            <i class="fas fa-history text-primary"></i> Data Kehadiran Terbaru
                        </h3>
                    </div>
                    <div class="col-md-6 text-end">
                        <div class="d-flex align-items-center justify-content-end">
                            <!-- Informasi Menampilkan Data -->
                            <p class="text-muted mb-0 me-3">
                                Menampilkan <?= $start_data ?>-<?= $end_data ?> dari <?= $total_data ?> data
                            </p>
                            
                            <!-- Dropdown Limit -->
                            <form method="GET" class="d-inline" id="limitForm">
                                <?php if (!empty($search)): ?>
                                    <input type="hidden" name="search" value="<?= htmlspecialchars($search) ?>">
                                <?php endif; ?>
                                <?php if (!empty($filter_hari)): ?>
                                    <input type="hidden" name="filter_hari" value="<?= htmlspecialchars($filter_hari) ?>">
                                <?php endif; ?>
                                <?php if (!empty($filter_mapel)): ?>
                                    <input type="hidden" name="filter_mapel" value="<?= htmlspecialchars($filter_mapel) ?>">
                                <?php endif; ?>
                                <select name="limit" class="form-select d-inline-block w-auto" id="limitSelect">
                                    <option value="10" <?= $limit == 10 ? 'selected' : '' ?>>10</option>
                                    <option value="30" <?= $limit == 30 ? 'selected' : '' ?>>30</option>
                                    <option value="50" <?= $limit == 50 ? 'selected' : '' ?>>50</option>
                                    <option value="100" <?= $limit == 100 ? 'selected' : '' ?>>100</option>
                                    <option value="<?= $total_data ?>" <?= $limit == $total_data ? 'selected' : '' ?>>All</option>
                                </select>
                            </form>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Form Pencarian dan Filter -->
            <div class="p-3 border-bottom bg-light">
                <form method="GET" class="row g-3" id="searchForm">
                    <!-- Pencarian -->
                    <div class="col-md-4 position-relative">
                        <label class="form-label small text-muted mb-1">Pencarian</label>
                        <div class="input-group">
                            <span class="input-group-text">
                                <i class="fas fa-search"></i>
                            </span>
                            <input type="text" name="search" class="form-control" id="searchInput" 
                                   placeholder="Cari nama, NIS, atau mata pelajaran..." 
                                   value="<?= htmlspecialchars($search) ?>">
                        </div>
                        <div class="search-loading" id="searchLoading">
                            <i class="fas fa-spinner fa-spin text-primary"></i>
                        </div>
                    </div>

                    <!-- Filter Hari -->
                    <div class="col-md-3">
                        <label class="form-label small text-muted mb-1">Filter Hari</label>
                        <select name="filter_hari" class="form-select" id="filterHari">
                            <option value="">Semua Hari</option>
                            <?php while ($hari = mysqli_fetch_assoc($result_hari)): ?>
                                <option value="<?= htmlspecialchars($hari['hari']) ?>" 
                                    <?= $filter_hari == $hari['hari'] ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($hari['hari']) ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>

                    <!-- Filter Mata Pelajaran -->
                    <div class="col-md-3">
                        <label class="form-label small text-muted mb-1">Filter Mata Pelajaran</label>
                        <select name="filter_mapel" class="form-select" id="filterMapel">
                            <option value="">Semua Mata Pelajaran</option>
                            <?php while ($mapel = mysqli_fetch_assoc($result_mapel)): ?>
                                <option value="<?= htmlspecialchars($mapel['kode_mapel']) ?>" 
                                    <?= $filter_mapel == $mapel['kode_mapel'] ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($mapel['nama_mapel']) ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>

                    <!-- Tombol Aksi -->
                    <div class="col-md-2">
                        <label class="form-label small text-muted mb-1 d-block">&nbsp;</label>
                        <div class="d-flex gap-2">
                            <button type="submit" class="btn btn-primary flex-fill" id="searchButton">
                                <i class="fas fa-search me-1"></i> Terapkan
                            </button>
                            <button type="button" class="btn btn-reset" id="resetButton">
                                <i class="fas fa-undo me-1"></i> Reset
                            </button>
                        </div>
                    </div>
                </form>

                <!-- Info Filter Aktif -->
                <?php if (!empty($filter_hari) || !empty($filter_mapel) || !empty($search)): ?>
                    <div class="mt-3">
                        <small class="text-muted">Filter aktif:</small>
                        <?php if (!empty($search)): ?>
                            <span class="badge bg-info me-2">
                                <i class="fas fa-search me-1"></i>Pencarian: "<?= htmlspecialchars($search) ?>"
                            </span>
                        <?php endif; ?>
                        <?php if (!empty($filter_hari)): ?>
                            <span class="badge bg-primary me-2">
                                <i class="fas fa-calendar me-1"></i>Hari: <?= htmlspecialchars($filter_hari) ?>
                            </span>
                        <?php endif; ?>
                        <?php if (!empty($filter_mapel)): 
                            $mapel_name = '';
                            $mapel_query = mysqli_query($conn, "SELECT nama_mapel FROM ujn_mata_pelajaran WHERE kode_mapel = '$filter_mapel'");
                            if ($mapel_query && mysqli_num_rows($mapel_query) > 0) {
                                $mapel_data = mysqli_fetch_assoc($mapel_query);
                                $mapel_name = $mapel_data['nama_mapel'];
                            }
                        ?>
                            <span class="badge bg-success">
                                <i class="fas fa-book me-1"></i>Mapel: <?= htmlspecialchars($mapel_name) ?>
                            </span>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
            </div>
            
            <div class="table-responsive">
                <table class="table table-striped table-hover mb-0">
                    <thead class="table-dark">
                        <tr>
                            <th width="50">#</th>
                            <th>NIS</th>
                            <th>Nama Siswa</th>
                            <th>Kelas</th>
                            <th>Mata Pelajaran</th>
                            <th>Hari</th>
                            <th>Tanggal</th>
                            <th>Jam</th>
                        </tr>
                    </thead>
                    <tbody id="tableBody">
                        <?php if (mysqli_num_rows($result) > 0): ?>
                            <?php $no = $offset + 1; ?>
                            <?php while ($row = mysqli_fetch_assoc($result)): ?>
                                <tr>
                                    <td><?= $no++; ?></td>
                                    <td><?= htmlspecialchars($row['nis']); ?></td>
                                    <td><?= htmlspecialchars($row['nama']); ?></td>
                                    <td><?= htmlspecialchars($row['kelas']); ?></td>
                                    <td><?= htmlspecialchars($row['nama_mapel']); ?></td>
                                    <td>
                                        <span class="badge bg-info badge-hari"><?= htmlspecialchars($row['hari']); ?></span>
                                    </td>
                                    <td><?= date('d/m/Y', strtotime($row['tanggal'])); ?></td>
                                    <td><?= date('H:i', strtotime($row['jam'])); ?></td>
                                </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="8" class="text-center text-muted py-4">
                                    <i class="fas fa-info-circle fa-2x mb-3"></i><br>
                                    <?php if (!empty($search) || !empty($filter_hari) || !empty($filter_mapel)): ?>
                                        Tidak ada data kehadiran yang sesuai dengan filter yang dipilih
                                        <br>
                                        <a href="index.php" class="btn btn-primary mt-2">
                                            <i class="fas fa-times me-1"></i> Reset Filter
                                        </a>
                                    <?php else: ?>
                                        Belum ada data kehadiran
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <!-- Pagination -->
            <?php if ($total_pages > 1): ?>
                <div class="p-3 border-top">
                    <nav aria-label="Page navigation">
                        <ul class="pagination justify-content-center mb-0">
                            <?php if ($page > 1): ?>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?= $page - 1 ?>&limit=<?= $limit ?><?= !empty($search) ? '&search=' . urlencode($search) : '' ?><?= !empty($filter_hari) ? '&filter_hari=' . urlencode($filter_hari) : '' ?><?= !empty($filter_mapel) ? '&filter_mapel=' . urlencode($filter_mapel) : '' ?>">
                                        <i class="fas fa-chevron-left"></i> Previous
                                    </a>
                                </li>
                            <?php endif; ?>

                            <?php 
                            // Tampilkan maksimal 5 halaman di sekitar halaman aktif
                            $start_page = max(1, $page - 2);
                            $end_page = min($total_pages, $page + 2);
                            
                            for ($i = $start_page; $i <= $end_page; $i++): 
                            ?>
                                <li class="page-item <?= $i == $page ? 'active' : '' ?>">
                                    <a class="page-link" href="?page=<?= $i ?>&limit=<?= $limit ?><?= !empty($search) ? '&search=' . urlencode($search) : '' ?><?= !empty($filter_hari) ? '&filter_hari=' . urlencode($filter_hari) : '' ?><?= !empty($filter_mapel) ? '&filter_mapel=' . urlencode($filter_mapel) : '' ?>">
                                        <?= $i ?>
                                    </a>
                                </li>
                            <?php endfor; ?>

                            <?php if ($page < $total_pages): ?>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?= $page + 1 ?>&limit=<?= $limit ?><?= !empty($search) ? '&search=' . urlencode($search) : '' ?><?= !empty($filter_hari) ? '&filter_hari=' . urlencode($filter_hari) : '' ?><?= !empty($filter_mapel) ? '&filter_mapel=' . urlencode($filter_mapel) : '' ?>">
                                        Next <i class="fas fa-chevron-right"></i>
                                    </a>
                                </li>
                            <?php endif; ?>
                        </ul>
                    </nav>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Footer -->
    <footer class="bg-dark text-light text-center py-4 mt-5">
        <div class="container">
            <p class="mb-0">&copy; 2024 Sistem Kehadiran Ujian. All rights reserved.</p>
        </div>
    </footer>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const searchForm = document.getElementById('searchForm');
            const searchInput = document.getElementById('searchInput');
            const searchButton = document.getElementById('searchButton');
            const resetButton = document.getElementById('resetButton');
            const searchLoading = document.getElementById('searchLoading');
            const tableBody = document.getElementById('tableBody');
            const limitSelect = document.getElementById('limitSelect');
            const limitForm = document.getElementById('limitForm');
            const filterHari = document.getElementById('filterHari');
            const filterMapel = document.getElementById('filterMapel');

            // Handle form submission dengan AJAX
            searchForm.addEventListener('submit', function(e) {
                e.preventDefault();
                performSearch();
            });

            // Handle tombol reset
            resetButton.addEventListener('click', function() {
                // Reset semua form fields
                searchInput.value = '';
                filterHari.value = '';
                filterMapel.value = '';
                
                // Submit form kosong untuk reset
                performSearch();
            });

            // Handle perubahan limit
            limitSelect.addEventListener('change', function() {
                const formData = new FormData(limitForm);
                updateTable(formData);
            });

            // Handle perubahan filter
            filterHari.addEventListener('change', function() {
                performSearch();
            });

            filterMapel.addEventListener('change', function() {
                performSearch();
            });

            // Auto-search saat mengetik
            let searchTimeout;
            searchInput.addEventListener('input', function() {
                clearTimeout(searchTimeout);
                searchTimeout = setTimeout(() => {
                    performSearch();
                }, 500);
            });

            function performSearch() {
                const formData = new FormData(searchForm);
                updateTable(formData);
            }

            function updateTable(formData) {
                // Tampilkan loading
                searchLoading.style.display = 'block';
                searchButton.disabled = true;
                resetButton.disabled = true;

                // Buat URL parameter
                const params = new URLSearchParams();
                for (let [key, value] of formData) {
                    if (value) {
                        params.append(key, value);
                    }
                }

                // Tambahkan page=1 untuk reset ke halaman pertama saat search/limit/filter berubah
                if (!params.has('page')) {
                    params.append('page', '1');
                }

                // Request AJAX
                fetch(`index.php?${params.toString()}`, {
                    method: 'GET',
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                })
                .then(response => response.text())
                .then(html => {
                    // Parse HTML response
                    const parser = new DOMParser();
                    const doc = parser.parseFromString(html, 'text/html');
                    
                    // Update table body
                    const newTableBody = doc.getElementById('tableBody');
                    if (newTableBody) {
                        tableBody.innerHTML = newTableBody.innerHTML;
                    }

                    // Update pagination
                    const newPagination = doc.querySelector('.pagination');
                    const currentPagination = document.querySelector('.pagination');
                    if (newPagination && currentPagination) {
                        currentPagination.innerHTML = newPagination.innerHTML;
                    } else if (currentPagination && !newPagination) {
                        currentPagination.remove();
                    }

                    // Update info menampilkan data
                    const newInfo = doc.querySelector('.text-muted.mb-0.me-3');
                    const currentInfo = document.querySelector('.text-muted.mb-0.me-3');
                    if (newInfo && currentInfo) {
                        currentInfo.textContent = newInfo.textContent;
                    }

                    // Update URL tanpa reload halaman
                    const newUrl = `index.php?${params.toString()}`;
                    window.history.pushState({ path: newUrl }, '', newUrl);
                })
                .catch(error => {
                    console.error('Error:', error);
                    // Fallback ke form submission biasa jika AJAX gagal
                    searchForm.submit();
                })
                .finally(() => {
                    // Sembunyikan loading
                    searchLoading.style.display = 'none';
                    searchButton.disabled = false;
                    resetButton.disabled = false;
                });
            }

            // Handle browser back/forward buttons
            window.addEventListener('popstate', function() {
                location.reload();
            });
        });
    </script>
</body>
</html>

<?php mysqli_close($conn); ?>