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

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

if (!isset($_SESSION['siswa_id'])) {
    die("Data siswa tidak ditemukan, silakan login ulang.");
}

$siswa_id = intval($_SESSION['siswa_id']);
$username = $_SESSION['username'];

// Ambil data siswa
$q = mysqli_query($conn, "SELECT nama, kelas FROM siswa WHERE id = $siswa_id");
if (!$q) {
    die("Error: " . mysqli_error($conn));
}
$siswa = mysqli_fetch_assoc($q);

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_izin'])) {
    $tanggal_izin = mysqli_real_escape_string($conn, $_POST['tanggal_izin']);
    $jenis_izin = mysqli_real_escape_string($conn, $_POST['jenis_izin']);
    $keterangan = mysqli_real_escape_string($conn, $_POST['keterangan']);
    $created_at = date('Y-m-d H:i:s');
    
    $bukti_foto = null;
    
    // Handle file upload
    if (isset($_FILES['bukti_foto']) && $_FILES['bukti_foto']['error'] === UPLOAD_ERR_OK) {
        $upload_dir = 'uploads/perizinan/';
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0777, true);
        }
        
        $file_extension = pathinfo($_FILES['bukti_foto']['name'], PATHINFO_EXTENSION);
        $allowed_extensions = ['jpg', 'jpeg', 'png', 'pdf'];
        
        if (in_array(strtolower($file_extension), $allowed_extensions)) {
            $file_name = 'izin_' . $siswa_id . '_' . time() . '.' . $file_extension;
            $file_path = $upload_dir . $file_name;
            
            if (move_uploaded_file($_FILES['bukti_foto']['tmp_name'], $file_path)) {
                $bukti_foto = $file_path;
            } else {
                $error = "Gagal mengupload bukti foto!";
            }
        } else {
            $error = "Format file tidak didukung! Hanya JPG, JPEG, PNG, dan PDF yang diizinkan.";
        }
    }

    if (!isset($error)) {
        $query = "INSERT INTO perizinan (siswa_id, tanggal_izin, jenis_izin, keterangan, bukti_foto, status, created_at) 
                  VALUES ($siswa_id, '$tanggal_izin', '$jenis_izin', '$keterangan', " . 
                  ($bukti_foto ? "'$bukti_foto'" : "NULL") . ", 'pending', '$created_at')";
        
        if (mysqli_query($conn, $query)) {
            $success = "Pengajuan izin berhasil dikirim!";
        } else {
            $error = "Gagal mengajukan izin: " . mysqli_error($conn);
        }
    }
}

// Ambil riwayat perizinan
$qRiwayat = mysqli_query($conn, "
    SELECT * FROM perizinan 
    WHERE siswa_id = $siswa_id 
    ORDER BY created_at DESC
");
$riwayat_izin = [];
if ($qRiwayat) {
    while ($row = mysqli_fetch_assoc($qRiwayat)) {
        $riwayat_izin[] = $row;
    }
}
?>

<!DOCTYPE html>
<html lang="id" class="dark">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Perizinan Siswa - Sistem Absensi QR</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary: #6366f1;
            --primary-dark: #4f46e5;
            --success: #10b981;
            --warning: #f59e0b;
            --danger: #ef4444;
            --card-bg: #ffffff;
            --card-bg-dark: #374151;
            --text-primary: #1f2937;
            --text-primary-dark: #f9fafb;
            --border-radius: 12px;
            --shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }

        .dark {
            --card-bg: var(--card-bg-dark);
            --text-primary: var(--text-primary-dark);
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', sans-serif;
            background: #f8fafc;
            color: var(--text-primary);
            line-height: 1.6;
        }

        .dark body {
            background: #0f172a;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 2rem;
        }

        .header {
            background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
            color: white;
            padding: 2rem;
            border-radius: var(--border-radius);
            margin-bottom: 2rem;
            text-align: center;
        }

        .header h1 {
            font-size: 2rem;
            margin-bottom: 0.5rem;
        }

        .card {
            background: var(--card-bg);
            border-radius: var(--border-radius);
            padding: 2rem;
            box-shadow: var(--shadow);
            margin-bottom: 2rem;
        }

        .form-group {
            margin-bottom: 1.5rem;
        }

        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 500;
        }

        .form-control {
            width: 100%;
            padding: 0.75rem;
            border: 1px solid #d1d5db;
            border-radius: 8px;
            font-size: 1rem;
            transition: border-color 0.3s;
        }

        .form-control:focus {
            outline: none;
            border-color: var(--primary);
        }

        .file-input {
            padding: 0.5rem;
        }

        .file-info {
            margin-top: 0.5rem;
            font-size: 0.875rem;
            color: #6b7280;
        }

        .btn {
            padding: 0.75rem 1.5rem;
            border: none;
            border-radius: 8px;
            font-size: 1rem;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s;
        }

        .btn-primary {
            background: var(--primary);
            color: white;
        }

        .btn-primary:hover {
            background: var(--primary-dark);
        }

        .table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 1rem;
        }

        .table th,
        .table td {
            padding: 1rem;
            text-align: left;
            border-bottom: 1px solid #e5e7eb;
        }

        .table th {
            background: #f8fafc;
            font-weight: 600;
        }

        .dark .table th {
            background: #374151;
        }

        .status {
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
            font-size: 0.875rem;
            font-weight: 500;
        }

        .status-pending {
            background: #fef3c7;
            color: #d97706;
        }

        .status-approved {
            background: #d1fae5;
            color: #059669;
        }

        .status-rejected {
            background: #fee2e2;
            color: #dc2626;
        }

        .bukti-link {
            color: var(--primary);
            text-decoration: none;
        }

        .bukti-link:hover {
            text-decoration: underline;
        }

        .alert {
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 1rem;
        }

        .alert-success {
            background: #d1fae5;
            color: #059669;
            border: 1px solid #a7f3d0;
        }

        .alert-error {
            background: #fee2e2;
            color: #dc2626;
            border: 1px solid #fecaca;
        }

        .back-btn {
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.75rem 1.5rem;
            background: #6b7280;
            color: white;
            text-decoration: none;
            border-radius: 8px;
            margin-bottom: 2rem;
            transition: background 0.3s;
        }

        .back-btn:hover {
            background: #4b5563;
        }
    </style>
</head>
<body>
    <div class="container">
        <a href="dashboard_siswa.php" class="back-btn">
            <i class="fas fa-arrow-left"></i> Kembali ke Dashboard
        </a>

        <div class="header">
            <h1><i class="fas fa-envelope-open-text"></i> Pengajuan Izin</h1>
            <p>Ajukan izin tidak masuk sekolah dengan mengisi form berikut</p>
        </div>

        <?php if (isset($success)): ?>
            <div class="alert alert-success">
                <i class="fas fa-check-circle"></i> <?php echo $success; ?>
            </div>
        <?php endif; ?>

        <?php if (isset($error)): ?>
            <div class="alert alert-error">
                <i class="fas fa-exclamation-circle"></i> <?php echo $error; ?>
            </div>
        <?php endif; ?>

        <div class="card">
            <h2 style="margin-bottom: 1.5rem;"><i class="fas fa-plus-circle"></i> Ajukan Izin Baru</h2>
            <form method="POST" enctype="multipart/form-data">
                <div class="form-group">
                    <label for="tanggal_izin">Tanggal Izin</label>
                    <input type="date" class="form-control" id="tanggal_izin" name="tanggal_izin" required 
                           min="<?php echo date('Y-m-d'); ?>">
                </div>

                <div class="form-group">
                    <label for="jenis_izin">Jenis Izin</label>
                    <select class="form-control" id="jenis_izin" name="jenis_izin" required>
                        <option value="">Pilih Jenis Izin</option>
                        <option value="Sakit">Sakit</option>
                        <option value="Izin">Izin Pribadi</option>
                        <option value="Keperluan Keluarga">Keperluan Keluarga</option>
                        <option value="Lainnya">Lainnya</option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="keterangan">Keterangan</label>
                    <textarea class="form-control" id="keterangan" name="keterangan" rows="4" 
                              placeholder="Jelaskan alasan izin secara detail..." required></textarea>
                </div>

                <div class="form-group">
                    <label for="bukti_foto">Bukti Foto/Surat (Opsional)</label>
                    <input type="file" class="form-control file-input" id="bukti_foto" name="bukti_foto" 
                           accept=".jpg,.jpeg,.png,.pdf">
                    <div class="file-info">
                        <i class="fas fa-info-circle"></i> Format yang didukung: JPG, JPEG, PNG, PDF (Maks. 2MB)
                    </div>
                </div>

                <button type="submit" name="submit_izin" class="btn btn-primary">
                    <i class="fas fa-paper-plane"></i> Ajukan Izin
                </button>
            </form>
        </div>

        <div class="card">
            <h2 style="margin-bottom: 1.5rem;"><i class="fas fa-history"></i> Riwayat Pengajuan Izin</h2>
            <?php if (empty($riwayat_izin)): ?>
                <p style="text-align: center; color: #6b7280; padding: 2rem;">
                    <i class="fas fa-inbox" style="font-size: 3rem; margin-bottom: 1rem; opacity: 0.5;"></i><br>
                    Belum ada pengajuan izin
                </p>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>Tanggal Izin</th>
                                <th>Jenis Izin</th>
                                <th>Keterangan</th>
                                <th>Bukti</th>
                                <th>Status</th>
                                <th>Tanggal Pengajuan</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($riwayat_izin as $izin): ?>
                                <tr>
                                    <td><?php echo date('d/m/Y', strtotime($izin['tanggal_izin'])); ?></td>
                                    <td><?php echo htmlspecialchars($izin['jenis_izin']); ?></td>
                                    <td><?php echo htmlspecialchars($izin['keterangan']); ?></td>
                                    <td>
                                        <?php if ($izin['bukti_foto']): ?>
                                            <a href="<?php echo htmlspecialchars($izin['bukti_foto']); ?>" 
                                               class="bukti-link" target="_blank">
                                                <i class="fas fa-file-image"></i> Lihat Bukti
                                            </a>
                                        <?php else: ?>
                                            <span style="color: #6b7280;">-</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php 
                                        $status_class = '';
                                        switch($izin['status']) {
                                            case 'pending': $status_class = 'status-pending'; break;
                                            case 'approved': $status_class = 'status-approved'; break;
                                            case 'rejected': $status_class = 'status-rejected'; break;
                                        }
                                        ?>
                                        <span class="status <?php echo $status_class; ?>">
                                            <?php echo ucfirst($izin['status']); ?>
                                        </span>
                                    </td>
                                    <td><?php echo date('d/m/Y H:i', strtotime($izin['created_at'])); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <script>
        // Set minimum date to today
        document.getElementById('tanggal_izin').min = new Date().toISOString().split('T')[0];
        
        // File size validation
        document.getElementById('bukti_foto').addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                const fileSize = file.size / 1024 / 1024; // MB
                if (fileSize > 2) {
                    alert('Ukuran file maksimal 2MB!');
                    e.target.value = '';
                }
            }
        });
    </script>
</body>
</html>