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

include 'config.php';

// Filter data
$filter_tanggal = isset($_GET['tanggal']) ? $_GET['tanggal'] : '';
$filter_kelas = isset($_GET['kelas']) ? $_GET['kelas'] : '';
$filter_status = isset($_GET['status']) ? $_GET['status'] : '';

// Query data perizinan
$query = "SELECT p.*, s.nama as siswa_nama, s.kelas, s.nis, 
                 wk.nama_wali as wali_nama
          FROM perizinan p 
          JOIN siswa s ON p.siswa_id = s.id 
          LEFT JOIN wali_kelas wk ON s.kelas = wk.kelas 
          WHERE 1=1";

$params = [];
if (!empty($filter_tanggal)) {
    $query .= " AND DATE(p.tanggal_izin) = ?";
    $params[] = $filter_tanggal;
}
if (!empty($filter_kelas)) {
    $query .= " AND s.kelas = ?";
    $params[] = $filter_kelas;
}
if (!empty($filter_status)) {
    $query .= " AND p.status = ?";
    $params[] = $filter_status;
}

$query .= " ORDER BY p.tanggal_izin DESC, p.created_at DESC";

// Eksekusi query
$perizinan = [];
if (!empty($params)) {
    $stmt = mysqli_prepare($conn, $query);
    if ($stmt) {
        $types = str_repeat('s', count($params));
        mysqli_stmt_bind_param($stmt, $types, ...$params);
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);
        while ($row = mysqli_fetch_assoc($result)) {
            $perizinan[] = $row;
        }
        mysqli_stmt_close($stmt);
    }
} else {
    $result = mysqli_query($conn, $query);
    while ($row = mysqli_fetch_assoc($result)) {
        $perizinan[] = $row;
    }
}

// Hitung statistik
$total_izin = count($perizinan);
$status_count = array_count_values(array_column($perizinan, 'status'));

// Query untuk filter kelas
$kelas_query = mysqli_query($conn, "SELECT DISTINCT kelas FROM siswa ORDER BY kelas");

// Pesan notifikasi
$message = '';
$message_type = '';
if (isset($_SESSION['message'])) {
    $message = $_SESSION['message'];
    $message_type = $_SESSION['message_type'];
    unset($_SESSION['message']);
    unset($_SESSION['message_type']);
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Riwayat Perizinan - Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
    <style>
        .table-responsive {
            max-height: 600px;
            overflow-y: auto;
        }
        .badge-pending {
            background: #ffc107;
            color: #000;
        }
        .badge-approved {
            background: #28a745;
            color: #fff;
        }
        .badge-rejected {
            background: #dc3545;
            color: #fff;
        }
        .stat-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 15px;
            text-align: center;
        }
        .bukti-img {
            max-width: 100px;
            max-height: 100px;
            cursor: pointer;
        }
        .btn-sm {
            margin: 2px;
        }
    </style>
</head>
<body class="container py-4">
    <h2 class="text-center mb-4"><i class="fas fa-envelope-open-text"></i> Riwayat Perizinan Siswa</h2>

    <a href="dashboard.php" class="btn btn-secondary mb-3">← Kembali ke Dashboard</a>

    <!-- Notifikasi -->
    <?php if ($message): ?>
        <div class="alert alert-<?php echo $message_type; ?> alert-dismissible fade show" role="alert">
            <?php echo $message; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <!-- Statistik -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="stat-card">
                <h4><?php echo $total_izin; ?></h4>
                <small>Total Izin</small>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card">
                <h4><?php echo $status_count['pending'] ?? 0; ?></h4>
                <small>Pending</small>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card">
                <h4><?php echo $status_count['approved'] ?? 0; ?></h4>
                <small>Approved</small>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card">
                <h4><?php echo $status_count['rejected'] ?? 0; ?></h4>
                <small>Rejected</small>
            </div>
        </div>
    </div>

    <!-- Filter Form -->
    <div class="card mb-4">
        <div class="card-header bg-light">
            <h5 class="mb-0"><i class="fas fa-filter"></i> Filter Data</h5>
        </div>
        <div class="card-body">
            <form method="GET" class="row g-3">
                <div class="col-md-3">
                    <label for="tanggal" class="form-label">Tanggal Izin</label>
                    <input type="date" class="form-control" id="tanggal" name="tanggal" 
                           value="<?php echo $filter_tanggal; ?>">
                </div>
                <div class="col-md-3">
                    <label for="kelas" class="form-label">Kelas</label>
                    <select class="form-control" id="kelas" name="kelas">
                        <option value="">Semua Kelas</option>
                        <?php mysqli_data_seek($kelas_query, 0); ?>
                        <?php while($kelas = mysqli_fetch_assoc($kelas_query)): ?>
                            <option value="<?php echo $kelas['kelas']; ?>" 
                                    <?php echo $filter_kelas == $kelas['kelas'] ? 'selected' : ''; ?>>
                                <?php echo $kelas['kelas']; ?>
                            </option>
                        <?php endwhile; ?>
                    </select>
                </div>
                <div class="col-md-3">
                    <label for="status" class="form-label">Status</label>
                    <select class="form-control" id="status" name="status">
                        <option value="">Semua Status</option>
                        <option value="pending" <?php echo $filter_status == 'pending' ? 'selected' : ''; ?>>Pending</option>
                        <option value="approved" <?php echo $filter_status == 'approved' ? 'selected' : ''; ?>>Approved</option>
                        <option value="rejected" <?php echo $filter_status == 'rejected' ? 'selected' : ''; ?>>Rejected</option>
                    </select>
                </div>
                <div class="col-md-3 d-flex align-items-end">
                    <button type="submit" class="btn btn-primary w-100">
                        <i class="fas fa-search"></i> Filter
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Tabel Riwayat Izin -->
    <div class="card">
        <div class="card-header bg-primary text-white">
            <strong><i class="fas fa-history"></i> Data Perizinan</strong>
            <span class="badge bg-light text-dark"><?php echo $total_izin; ?> Pengajuan</span>
        </div>
        <div class="card-body p-0">
            <?php if (empty($perizinan)): ?>
                <div class="text-center text-muted py-4">
                    <i class="fas fa-inbox fa-2x mb-2"></i><br>
                    <strong>Belum ada data perizinan</strong>
                </div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-bordered table-hover table-sm mb-0">
                        <thead class="table-light">
                            <tr>
                                <th width="5%">No</th>
                                <th width="10%">Tanggal Izin</th>
                                <th width="15%">Siswa</th>
                                <th width="10%">Kelas</th>
                                <th width="10%">Jenis Izin</th>
                                <th width="20%">Keterangan</th>
                                <th width="10%">Bukti</th>
                                <th width="10%">Wali Kelas</th>
                                <th width="10%">Status</th>
                                <th width="10%">Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($perizinan as $index => $data): ?>
                                <tr>
                                    <td class="text-center"><?php echo $index + 1; ?></td>
                                    <td>
                                        <?php echo date('d/m/Y', strtotime($data['tanggal_izin'])); ?>
                                        <br><small class="text-muted"><?php echo date('H:i', strtotime($data['created_at'])); ?></small>
                                    </td>
                                    <td>
                                        <?php echo htmlspecialchars($data['siswa_nama']); ?>
                                        <br><small class="text-muted">NIS: <?php echo htmlspecialchars($data['nis']); ?></small>
                                    </td>
                                    <td><?php echo htmlspecialchars($data['kelas']); ?></td>
                                    <td><?php echo htmlspecialchars($data['jenis_izin']); ?></td>
                                    <td><?php echo htmlspecialchars($data['keterangan']); ?></td>
                                    <td class="text-center">
                                        <?php if ($data['bukti_foto']): ?>
                                            <img src="<?php echo htmlspecialchars($data['bukti_foto']); ?>" 
                                                 class="bukti-img img-thumbnail" 
                                                 onclick="viewBukti('<?php echo htmlspecialchars($data['bukti_foto']); ?>')"
                                                 alt="Bukti" title="Klik untuk lihat">
                                        <?php else: ?>
                                            <span class="text-muted">-</span>
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo htmlspecialchars($data['wali_nama'] ?: '-'); ?></td>
                                    <td class="text-center">
                                        <span class="badge <?php 
                                            echo $data['status'] == 'pending' ? 'bg-warning' : 
                                                ($data['status'] == 'approved' ? 'bg-success' : 'bg-danger'); 
                                        ?>">
                                            <?php echo ucfirst($data['status']); ?>
                                        </span>
                                    </td>
                                    <td class="text-center">
                                        <button type="button" class="btn btn-info btn-sm" 
                                                onclick="viewIzinDetails(<?php echo $data['id']; ?>)"
                                                title="Lihat Detail">
                                            <i class="fas fa-eye"></i>
                                        </button>
                                        <?php if ($data['status'] == 'pending'): ?>
                                            <button type="button" class="btn btn-success btn-sm"
                                                    onclick="updateIzinStatus(<?php echo $data['id']; ?>, 'approved')"
                                                    title="Setujui">
                                                <i class="fas fa-check"></i>
                                            </button>
                                            <button type="button" class="btn btn-danger btn-sm"
                                                    onclick="updateIzinStatus(<?php echo $data['id']; ?>, 'rejected')"
                                                    title="Tolak">
                                                <i class="fas fa-times"></i>
                                            </button>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Modal Preview Bukti -->
    <div class="modal fade" id="buktiModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Preview Bukti</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body text-center">
                    <img id="buktiImage" src="" class="img-fluid" alt="Bukti">
                </div>
            </div>
        </div>
    </div>

    <!-- Modal Detail Izin -->
    <div class="modal fade" id="detailModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Detail Perizinan</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="detailContent">
                    <div class="text-center">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function viewBukti(imageSrc) {
            document.getElementById('buktiImage').src = imageSrc;
            new bootstrap.Modal(document.getElementById('buktiModal')).show();
        }

        function viewIzinDetails(id) {
            // Fetch detail izin via AJAX
            fetch('get_izin_detail.php?id=' + id)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        let statusBadge = '';
                        switch(data.data.status) {
                            case 'pending':
                                statusBadge = '<span class="badge bg-warning">Pending</span>';
                                break;
                            case 'approved':
                                statusBadge = '<span class="badge bg-success">Disetujui</span>';
                                break;
                            case 'rejected':
                                statusBadge = '<span class="badge bg-danger">Ditolak</span>';
                                break;
                        }
                        
                        let buktiHtml = data.data.bukti_foto ? 
                            `<img src="${data.data.bukti_foto}" class="img-fluid mt-2" style="max-height: 200px;">` : 
                            '<span class="text-muted">Tidak ada bukti</span>';
                        
                        document.getElementById('detailContent').innerHTML = `
                            <table class="table table-bordered">
                                <tr>
                                    <th width="35%">Nama Siswa</th>
                                    <td>${data.data.siswa_nama}</td>
                                </tr>
                                <tr>
                                    <th>NIS</th>
                                    <td>${data.data.nis}</td>
                                </tr>
                                <tr>
                                    <th>Kelas</th>
                                    <td>${data.data.kelas}</td>
                                </tr>
                                <tr>
                                    <th>Tanggal Izin</th>
                                    <td>${data.data.tanggal_izin_formatted}</td>
                                </tr>
                                <tr>
                                    <th>Jenis Izin</th>
                                    <td>${data.data.jenis_izin}</td>
                                </tr>
                                <tr>
                                    <th>Keterangan</th>
                                    <td>${data.data.keterangan}</td>
                                </tr>
                                <tr>
                                    <th>Bukti</th>
                                    <td>${buktiHtml}</td>
                                </tr>
                                <tr>
                                    <th>Status</th>
                                    <td>${statusBadge}</td>
                                </tr>
                                <tr>
                                    <th>Wali Kelas</th>
                                    <td>${data.data.wali_nama || '-'}</td>
                                </tr>
                                <tr>
                                    <th>Tanggal Pengajuan</th>
                                    <td>${data.data.created_at_formatted}</td>
                                </tr>
                            </table>
                        `;
                    } else {
                        document.getElementById('detailContent').innerHTML = `
                            <div class="alert alert-danger">${data.message}</div>
                        `;
                    }
                })
                .catch(error => {
                    document.getElementById('detailContent').innerHTML = `
                        <div class="alert alert-danger">Gagal memuat data detail</div>
                    `;
                });
            
            new bootstrap.Modal(document.getElementById('detailModal')).show();
        }

        function updateIzinStatus(id, status) {
            let statusText = status === 'approved' ? 'menyetujui' : 'menolak';
            if (confirm(`Yakin ingin ${statusText} izin ini?`)) {
                // Create form data for POST request
                const formData = new FormData();
                formData.append('id', id);
                formData.append('status', status);
                
                fetch('proses_update_izin.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // Reload page to show updated data
                        window.location.reload();
                    } else {
                        alert('Gagal mengupdate status: ' + data.message);
                    }
                })
                .catch(error => {
                    alert('Terjadi kesalahan: ' + error);
                });
            }
        }
    </script>
</body>
</html>