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

// Cek apakah user sudah login dan role-nya admin
if (!isset($_SESSION['user']) || $_SESSION['user']['role'] !== 'admin') {
    header('Location: ../login.php');
    exit();
}

$current_user = $_SESSION['user'];

// Query untuk mendapatkan data kehadiran dengan filter
$where_conditions = [];
$filter_params = [];

// Filter berdasarkan tanggal
if (isset($_GET['tanggal']) && !empty($_GET['tanggal'])) {
    $where_conditions[] = "uk.tanggal = ?";
    $filter_params[] = $_GET['tanggal'];
} else {
    // Default tampilkan hari ini
    $where_conditions[] = "uk.tanggal = ?";
    $filter_params[] = date('Y-m-d');
}

// Filter berdasarkan mata pelajaran
if (isset($_GET['mapel']) && !empty($_GET['mapel'])) {
    $where_conditions[] = "uk.kode_mapel = ?";
    $filter_params[] = $_GET['mapel'];
}

// Filter berdasarkan kelas
if (isset($_GET['kelas']) && !empty($_GET['kelas'])) {
    $where_conditions[] = "us.kelas = ?";
    $filter_params[] = $_GET['kelas'];
}

// Build query
$where_clause = "";
if (!empty($where_conditions)) {
    $where_clause = "WHERE " . implode(" AND ", $where_conditions);
}

$query = "
    SELECT 
        uk.id,
        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_clause
    ORDER BY uk.tanggal DESC, uk.jam DESC
";

$stmt = $conn->prepare($query);
if (!empty($filter_params)) {
    $types = str_repeat('s', count($filter_params));
    $stmt->bind_param($types, ...$filter_params);
}
$stmt->execute();
$result = $stmt->get_result();

// Query untuk dropdown filter
$mapel_query = "SELECT * FROM ujn_mata_pelajaran ORDER BY nama_mapel";
$mapel_result = $conn->query($mapel_query);

$kelas_query = "SELECT DISTINCT kelas FROM ujn_siswa ORDER BY kelas";
$kelas_result = $conn->query($kelas_query);

// Hitung statistik lengkap
$total_kehadiran = $result->num_rows;
$today = date('Y-m-d');

// Statistik hari ini
$stats_today_query = "
    SELECT COUNT(*) as total_hari_ini 
    FROM ujn_kehadiran 
    WHERE tanggal = '$today'
";
$stats_today_result = $conn->query($stats_today_query);
$stats_today_data = $stats_today_result->fetch_assoc();
$total_hari_ini = $stats_today_data['total_hari_ini'];

// Total semua kehadiran
$total_all_query = "SELECT COUNT(*) as total FROM ujn_kehadiran";
$total_all_result = $conn->query($total_all_query);
$total_all = $total_all_result->fetch_assoc()['total'];

// Total siswa
$total_siswa_query = "SELECT COUNT(*) as total FROM ujn_siswa";
$total_siswa_result = $conn->query($total_siswa_query);
$total_siswa = $total_siswa_result->fetch_assoc()['total'];

// Total mata pelajaran
$total_mapel_query = "SELECT COUNT(*) as total FROM ujn_mata_pelajaran";
$total_mapel_result = $conn->query($total_mapel_query);
$total_mapel = $total_mapel_result->fetch_assoc()['total'];
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard Admin - 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.4.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
    <style>
        .navbar-brand {
            font-weight: bold;
        }
        .card {
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            border: none;
            transition: transform 0.2s ease;
        }
        .card:hover {
            transform: translateY(-2px);
        }
        .stats-card {
            color: white;
            border-radius: 10px;
            padding: 20px;
            text-align: center;
            margin-bottom: 20px;
            border: none;
        }
        .stats-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        .stats-success {
            background: linear-gradient(135deg, #28a745, #20c997);
        }
        .stats-warning {
            background: linear-gradient(135deg, #ffc107, #fd7e14);
        }
        .stats-danger {
            background: linear-gradient(135deg, #dc3545, #c82333);
        }
        .stats-number {
            font-size: 2.5rem;
            font-weight: bold;
            margin-bottom: 5px;
        }
        .stats-label {
            font-size: 0.9rem;
            opacity: 0.9;
        }
        .stats-icon {
            font-size: 2rem;
            margin-bottom: 10px;
            opacity: 0.8;
        }
        .filter-card {
            background: #f8f9fa;
            border-left: 4px solid #007bff;
        }
        .table-responsive {
            border-radius: 8px;
            overflow: hidden;
        }
        .table th {
            background: #343a40;
            color: white;
            border: none;
            font-weight: 600;
        }
        .badge-presensi {
            font-size: 0.8rem;
            padding: 6px 12px;
        }
        .user-info {
            background: linear-gradient(135deg, #dc3545, #c82333);
            color: white;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 20px;
        }
        .btn-export {
            background: linear-gradient(135deg, #28a745, #20c997);
            border: none;
            color: white;
        }
        .btn-export:hover {
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }
        .empty-state {
            text-align: center;
            padding: 40px;
            color: #6c757d;
        }
        .empty-state i {
            font-size: 4rem;
            margin-bottom: 20px;
            opacity: 0.5;
        }
        .admin-menu {
            background: linear-gradient(135deg, #f8f9fa, #e9ecef);
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
        }
        .menu-item {
            display: block;
            padding: 15px;
            margin-bottom: 10px;
            background: white;
            border-radius: 8px;
            text-decoration: none;
            color: #333;
            transition: all 0.3s ease;
            border-left: 4px solid #007bff;
        }
        .menu-item:hover {
            transform: translateX(5px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            color: #333;
            text-decoration: none;
        }
        .menu-item i {
            width: 30px;
            text-align: center;
            margin-right: 10px;
            color: #007bff;
        }
        .quick-actions {
            margin-bottom: 30px;
        }
    </style>
</head>
<body>
    <!-- Navbar -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container">
            <a class="navbar-brand" href="dashboard.php">
                <i class="fas fa-tachometer-alt me-2"></i>Admin Dashboard
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item">
                        <a class="nav-link active" href="dashboard.php">
                            <i class="fas fa-home me-1"></i>Dashboard
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="mata_pelajaran.php">
                            <i class="fas fa-database me-1"></i>Kelola Mata Pelajaran
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="kelola_siswa.php">
                            <i class="fas fa-users me-1"></i>Kelola Siswa
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="generate_qr.php">
                            <i class="fas fa-qrcode me-1"></i>Generate QR
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="../logout.php">
                            <i class="fas fa-sign-out-alt me-1"></i>Logout
                        </a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <!-- Konten Utama -->
    <div class="container mt-4">
        <!-- Info Pengguna -->
        <div class="user-info">
            <h5><i class="fas fa-user-shield me-2"></i>Selamat Datang, <?= htmlspecialchars($current_user['nama_lengkap']); ?></h5>
            <p class="mb-0">Anda login sebagai <strong>Administrator</strong> - Halaman Dashboard</p>
        </div>

        <!-- Menu Cepat Admin -->
        <div class="quick-actions">
            <div class="row">
                <div class="col-md-4">
                    <a href="mata_pelajaran.php" class="menu-item" target="_blank">
                        <i class="fas fa-camera"></i>Mata Pelajaran
                    </a>
                </div>
                <div class="col-md-4">
                    <a href="kelola_siswa.php" class="menu-item">
                        <i class="fas fa-users"></i>Kelola Data Siswa
                    </a>
                </div>
                <div class="col-md-4">
                    <a href="generate_qr.php" class="menu-item">
                        <i class="fas fa-qrcode"></i>Generate QR Code
                    </a>
                </div>
            </div>
        </div>

        <!-- Statistik -->
        <div class="row">
            <div class="col-md-3">
                <div class="stats-card stats-primary">
                    <div class="stats-icon">
                        <i class="fas fa-calendar-check"></i>
                    </div>
                    <div class="stats-number"><?= $total_hari_ini; ?></div>
                    <div class="stats-label">Kehadiran Hari Ini</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stats-card stats-success">
                    <div class="stats-icon">
                        <i class="fas fa-database"></i>
                    </div>
                    <div class="stats-number"><?= $total_all; ?></div>
                    <div class="stats-label">Total Kehadiran</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stats-card stats-warning">
                    <div class="stats-icon">
                        <i class="fas fa-users"></i>
                    </div>
                    <div class="stats-number"><?= $total_siswa; ?></div>
                    <div class="stats-label">Total Siswa</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stats-card stats-danger">
                    <div class="stats-icon">
                        <i class="fas fa-book"></i>
                    </div>
                    <div class="stats-number"><?= $total_mapel; ?></div>
                    <div class="stats-label">Mata Pelajaran</div>
                </div>
            </div>
        </div>

        <!-- Filter Data -->
        <div class="card filter-card">
            <div class="card-header bg-transparent">
                <h5 class="mb-0"><i class="fas fa-filter me-2"></i>Filter Data Kehadiran</h5>
            </div>
            <div class="card-body">
                <form method="GET" action="" class="row g-3">
                    <div class="col-md-3">
                        <label for="tanggal" class="form-label">Tanggal</label>
                        <input type="date" class="form-control" id="tanggal" name="tanggal" 
                               value="<?= isset($_GET['tanggal']) ? $_GET['tanggal'] : date('Y-m-d') ?>">
                    </div>
                    <div class="col-md-3">
                        <label for="mapel" class="form-label">Mata Pelajaran</label>
                        <select class="form-select" id="mapel" name="mapel">
                            <option value="">Semua Mata Pelajaran</option>
                            <?php 
                            // Reset pointer result
                            $mapel_result->data_seek(0);
                            while($mapel = $mapel_result->fetch_assoc()): ?>
                                <option value="<?= $mapel['kode_mapel'] ?>" 
                                    <?= (isset($_GET['mapel']) && $_GET['mapel'] == $mapel['kode_mapel']) ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($mapel['nama_mapel']) ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label for="kelas" class="form-label">Kelas</label>
                        <select class="form-select" id="kelas" name="kelas">
                            <option value="">Semua Kelas</option>
                            <?php 
                            // Reset pointer result
                            $kelas_result->data_seek(0);
                            while($kelas = $kelas_result->fetch_assoc()): ?>
                                <option value="<?= $kelas['kelas'] ?>" 
                                    <?= (isset($_GET['kelas']) && $_GET['kelas'] == $kelas['kelas']) ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($kelas['kelas']) ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    <div class="col-md-3 d-flex align-items-end">
                        <button type="submit" class="btn btn-primary me-2">
                            <i class="fas fa-search me-1"></i>Filter
                        </button>
                        <a href="dashboard.php" class="btn btn-outline-secondary">
                            <i class="fas fa-refresh me-1"></i>Reset
                        </a>
                    </div>
                </form>
            </div>
        </div>

        <!-- Tombol Export -->
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h4><i class="fas fa-list me-2"></i>Data Kehadiran Terbaru</h4>
            <div>
                <button class="btn btn-export" onclick="exportToExcel()">
                    <i class="fas fa-file-excel me-1"></i>Export to Excel
                </button>
                <a href="data_kehadiran.php" class="btn btn-primary ms-2">
                    <i class="fas fa-external-link-alt me-1"></i>Lihat Semua Data
                </a>
            </div>
        </div>

        <!-- Tabel Data Kehadiran -->
        <div class="card">
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-striped table-hover mb-0" id="dataTable">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>NIS</th>
                                <th>Nama Siswa</th>
                                <th>Kelas</th>
                                <th>Mata Pelajaran</th>
                                <th>Hari</th>
                                <th>Tanggal</th>
                                <th>Jam</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if ($result->num_rows > 0): ?>
                                <?php $no = 1; while ($row = $result->fetch_assoc()): ?>
                                    <tr>
                                        <td><?= $no++; ?></td>
                                        <td>
                                            <span class="fw-bold"><?= htmlspecialchars($row['nis']); ?></span>
                                        </td>
                                        <td><?= htmlspecialchars($row['nama']); ?></td>
                                        <td>
                                            <span class="badge bg-secondary"><?= htmlspecialchars($row['kelas']); ?></span>
                                        </td>
                                        <td>
                                            <span class="badge bg-primary"><?= htmlspecialchars($row['nama_mapel']); ?></span>
                                        </td>
                                        <td><?= htmlspecialchars($row['hari']); ?></td>
                                        <td>
                                            <span class="fw-bold"><?= date('d/m/Y', strtotime($row['tanggal'])); ?></span>
                                        </td>
                                        <td>
                                            <span class="badge bg-success"><?= date('H:i', strtotime($row['jam'])); ?></span>
                                        </td>
                                        <td>
                                            <span class="badge bg-success badge-presensi">
                                                <i class="fas fa-check me-1"></i>Hadir
                                            </span>
                                        </td>
                                    </tr>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="9">
                                        <div class="empty-state">
                                            <i class="fas fa-inbox"></i>
                                            <h5>Data tidak ditemukan</h5>
                                            <p>Tidak ada data kehadiran yang sesuai dengan filter yang dipilih.</p>
                                            <a href="dashboard.php" class="btn btn-primary">
                                                <i class="fas fa-refresh me-1"></i>Reset Filter
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Info Footer -->
        <div class="text-center mt-4 text-muted">
            <small>
                <i class="fas fa-info-circle me-1"></i>
                Menampilkan <strong><?= $total_kehadiran; ?></strong> data kehadiran berdasarkan filter yang dipilih.
                <a href="data_kehadiran.php" class="text-decoration-none">Lihat semua data</a>
            </small>
        </div>
    </div>

    <!-- JavaScript Libraries -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
    <script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
    
    <script>
        // Inisialisasi date picker
        flatpickr("#tanggal", {
            dateFormat: "Y-m-d",
            maxDate: "today"
        });

        // Fungsi export to Excel
        function exportToExcel() {
            // Get table element
            const table = document.getElementById('dataTable');
            
            // Clone table to avoid modifying the original
            const clonedTable = table.cloneNode(true);
            
            // Remove empty state row if exists
            const emptyStateRow = clonedTable.querySelector('.empty-state');
            if (emptyStateRow) {
                emptyStateRow.closest('tr').remove();
            }
            
            // Create workbook and worksheet
            const wb = XLSX.utils.book_new();
            const ws = XLSX.utils.table_to_sheet(clonedTable);
            
            // Add worksheet to workbook
            XLSX.utils.book_append_sheet(wb, ws, "Data Kehadiran");
            
            // Generate filename with current date
            const today = new Date().toISOString().split('T')[0];
            const filename = `Data_Kehadiran_${today}.xlsx`;
            
            // Export to Excel
            XLSX.writeFile(wb, filename);
        }

        // Auto-submit form when date changes
        document.getElementById('tanggal').addEventListener('change', function() {
            this.form.submit();
        });

        // Add some interactivity
        document.addEventListener('DOMContentLoaded', function() {
            // Add hover effects to table rows
            const tableRows = document.querySelectorAll('#dataTable tbody tr');
            tableRows.forEach(row => {
                row.addEventListener('mouseenter', function() {
                    this.style.backgroundColor = '#f8f9fa';
                    this.style.transition = 'all 0.2s ease';
                });
                
                row.addEventListener('mouseleave', function() {
                    this.style.backgroundColor = '';
                });
            });

            // Show loading state when filtering
            const filterForm = document.querySelector('form');
            filterForm.addEventListener('submit', function() {
                const submitBtn = this.querySelector('button[type="submit"]');
                submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Memfilter...';
                submitBtn.disabled = true;
            });
        });
    </script>
</body>
</html>

<?php 
// Tutup koneksi database
if (isset($conn)) {
    $conn->close();
}
?>