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

include 'config.php';
date_default_timezone_set("Asia/Jakarta");

// Ambil kelas yang diampu oleh wali kelas
$username = $_SESSION['username'];
$wali_kelas = mysqli_fetch_assoc(mysqli_query($conn, "SELECT kelas, nama_wali FROM wali_kelas WHERE nip_wali='$username' LIMIT 1"));
$kelas_diampu = $wali_kelas['kelas'] ?? '';

if (empty($kelas_diampu)) {
    die("<script>alert('Anda tidak memiliki kelas yang diampu!'); window.location='dashboard_wali_kelas.php';</script>");
}

// Handle status update
if (isset($_POST['update_status'])) {
    $izin_id = intval($_POST['izin_id']);
    $status = $_POST['status'];
    
    // Cek struktur tabel perizinan terlebih dahulu
    $query = "UPDATE perizinan SET status = '$status', updated_at = NOW() WHERE id = $izin_id";
    
    if (mysqli_query($conn, $query)) {
        $_SESSION['success'] = "Status izin berhasil diupdate!";
    } else {
        // Jika gagal, coba tanpa catatan_wali
        $query_simple = "UPDATE perizinan SET status = '$status' WHERE id = $izin_id";
        if (mysqli_query($conn, $query_simple)) {
            $_SESSION['success'] = "Status izin berhasil diupdate!";
        } else {
            $_SESSION['error'] = "Gagal mengupdate status: " . mysqli_error($conn);
        }
    }
    
    header("Location: daftar_ajuan_izin.php");
    exit;
}

// Ambil daftar ajuan izin
$query_izin = "
    SELECT p.*, s.nama as siswa_nama, s.nis, s.kelas 
    FROM perizinan p 
    JOIN siswa s ON p.siswa_id = s.id 
    WHERE s.kelas = '$kelas_diampu' 
    ORDER BY p.created_at DESC
";

$result_izin = mysqli_query($conn, $query_izin);
$daftar_izin = [];
if ($result_izin) {
    while ($row = mysqli_fetch_assoc($result_izin)) {
        $daftar_izin[] = $row;
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Daftar Ajuan Izin - Kelas <?php echo $kelas_diampu; ?></title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <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>
        .status-pending { background-color: #fff3cd !important; }
        .status-approved { background-color: #d4edda !important; }
        .status-rejected { background-color: #f8d7da !important; }
        
        .bukti-img {
            max-width: 60px;
            max-height: 60px;
            border-radius: 4px;
            cursor: pointer;
            transition: transform 0.3s;
            border: 1px solid #dee2e6;
        }
        
        .bukti-img:hover {
            transform: scale(1.1);
        }
        
        .modal-image {
            max-width: 100%;
            max-height: 80vh;
            border-radius: 8px;
        }
        
        .table th {
            background-color: #f8f9fa;
            font-weight: 600;
        }
    </style>
</head>
<body class="container mt-4">
    <h2>Daftar Ajuan Izin - Kelas <?php echo $kelas_diampu; ?></h2>
    <a href="dashboard_wali_kelas.php" class="btn btn-secondary mb-3">← Kembali</a>

    <?php if (isset($_SESSION['success'])): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle"></i> <?php echo $_SESSION['success']; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php unset($_SESSION['success']); ?>
    <?php endif; ?>

    <?php if (isset($_SESSION['error'])): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="fas fa-exclamation-circle"></i> <?php echo $_SESSION['error']; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php unset($_SESSION['error']); ?>
    <?php endif; ?>

    <div class="table-responsive">
        <table class="table table-bordered table-sm">
            <thead class="table-light">
                <tr>
                    <th>No</th>
                    <th>Tanggal</th>
                    <th>NIS</th>
                    <th>Nama</th>
                    <th>Kelas</th>
                    <th>Jenis Izin</th>
                    <th>Keterangan</th>
                    <th>Bukti</th>
                    <th>Status</th>
                    <th>Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($daftar_izin)): ?>
                    <tr>
                        <td colspan="10" class="text-center py-4">
                            <i class="fas fa-inbox fa-2x text-muted mb-2"></i><br>
                            <span class="text-muted">Belum ada pengajuan izin dari siswa kelas <?php echo $kelas_diampu; ?></span>
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($daftar_izin as $index => $izin): 
                        $status_class = "status-" . $izin['status'];
                        $status_icon = $izin['status'] === 'pending' ? 'clock' : ($izin['status'] === 'approved' ? 'check' : 'times');
                        $status_color = $izin['status'] === 'pending' ? 'warning' : ($izin['status'] === 'approved' ? 'success' : 'danger');
                    ?>
                    <tr class="<?= $status_class ?>">
                        <td><?= $index + 1 ?></td>
                        <td><?= date('d/m/Y', strtotime($izin['tanggal_izin'])) ?></td>
                        <td><?= htmlspecialchars($izin['nis']) ?></td>
                        <td><strong><?= htmlspecialchars($izin['siswa_nama']) ?></strong></td>
                        <td><?= htmlspecialchars($izin['kelas']) ?></td>
                        <td><?= htmlspecialchars($izin['jenis_izin']) ?></td>
                        <td style="max-width: 200px;"><?= htmlspecialchars($izin['keterangan']) ?></td>
                        <td>
                            <?php if (!empty($izin['bukti_foto'])): ?>
                                <img src="<?= htmlspecialchars($izin['bukti_foto']) ?>" 
                                     alt="Bukti Izin" 
                                     class="bukti-img"
                                     data-bs-toggle="modal" 
                                     data-bs-target="#imageModal"
                                     onclick="document.getElementById('modalImage').src = '<?= htmlspecialchars($izin['bukti_foto']) ?>'">
                            <?php else: ?>
                                <span class="badge bg-secondary">
                                    <i class="fas fa-times"></i> Tidak Ada
                                </span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <span class="badge bg-<?= $status_color ?>">
                                <i class="fas fa-<?= $status_icon ?>"></i>
                                <?= ucfirst($izin['status']) ?>
                            </span>
                        </td>
                        <td>
                            <button class="btn btn-warning btn-sm" 
                                    data-bs-toggle="modal" 
                                    data-bs-target="#statusModal"
                                    onclick="setModalData(<?= $izin['id'] ?>, '<?= $izin['status'] ?>')">
                                <i class="fas fa-edit"></i> Ubah
                            </button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <div class="mt-3">
        <div class="alert alert-info">
            <strong>Keterangan Warna:</strong>
            <span class="badge bg-warning">Kuning = Menunggu</span>
            <span class="badge bg-success">Hijau = Disetujui</span>
            <span class="badge bg-danger">Merah = Ditolak</span>
        </div>
    </div>

    <!-- Modal Ubah Status -->
    <div class="modal fade" id="statusModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-edit"></i> Ubah Status Izin</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST" id="statusForm">
                    <div class="modal-body">
                        <input type="hidden" name="izin_id" id="modalIzinId">
                        
                        <div class="mb-3">
                            <label for="status" class="form-label">Status</label>
                            <select class="form-select" id="status" name="status" required>
                                <option value="pending">Pending</option>
                                <option value="approved">Disetujui</option>
                                <option value="rejected">Ditolak</option>
                            </select>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                        <button type="submit" name="update_status" class="btn btn-success">
                            <i class="fas fa-save"></i> Simpan
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Modal Gambar -->
    <div class="modal fade" id="imageModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-image"></i> Bukti Izin</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body text-center">
                    <img id="modalImage" src="" alt="Bukti Izin" class="modal-image">
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function setModalData(izinId, currentStatus) {
            document.getElementById('modalIzinId').value = izinId;
            document.getElementById('status').value = currentStatus;
        }
    </script>
</body>
</html>