<?php
session_start();
include '../koneksi.php';

if (!isset($_SESSION['id']) || $_SESSION['role'] != 'guru') {
    header("Location: ../login.php");
    exit;
}

$user_id = $_SESSION['id'];
date_default_timezone_set('Asia/Jakarta');

$alertStatus = null;

if (isset($_POST['kirim'])) {

    $tanggal = date("Y-m-d");
    $jenis = mysqli_real_escape_string($koneksi, $_POST['jenis']);
    $keterangan = mysqli_real_escape_string($koneksi, $_POST['keterangan']);
    $file_surat = null;

    if (!empty($_FILES['file']['name'])) {
        $namaAsli = $_FILES['file']['name'];
        $ext = strtolower(pathinfo($namaAsli, PATHINFO_EXTENSION));
        $allowed = ['jpg','jpeg','png','gif','pdf'];

        if (in_array($ext, $allowed)) {
            $namaFile = "izin_guru_" . time() . "_" . rand(1000,9999) . "." . $ext;
            $tmp = $_FILES['file']['tmp_name'];
            $folder = "../uploads/";

            if (move_uploaded_file($tmp, $folder . $namaFile)) {
                $file_surat = $namaFile;
            }
        }
    }

    $sql = "INSERT INTO form_izin 
            (user_id, tanggal, jenis, keterangan, file_surat, status)
            VALUES 
            ('$user_id', '$tanggal', '$jenis', '$keterangan', '$file_surat', 'Menunggu')";

    if (mysqli_query($koneksi, $sql)) {
        $alertStatus = 'berhasil';
    } else {
        $alertStatus = 'gagal';
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Buat Form Izin Guru | MAYABSEN</title>

<link href="../bootstrap-5.3.8-dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700&display=swap" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<style>
body{
    background:#f4f8f6;
    font-family:'Poppins',sans-serif;
}

/* SWEETALERT */
.swal2-popup{
    border-radius:26px !important;
    padding:32px 28px !important;
}
.swal2-confirm{
    background:#b7e4c7 !important;
    color:#1b4332 !important;
    border-radius:50px !important;
    padding:10px 36px !important;
    font-weight:600;
    border:none !important;
    box-shadow:0 8px 18px rgba(0,0,0,.12);
}
.swal2-confirm:hover{
    background:#95d5b2 !important;
}

/* BACK */
.back-arrow{
    position:fixed;
    top:18px;
    left:18px;
    font-size:1.6rem;
    color:#1b4332;
    text-decoration:none;
    z-index:20;
}

/* WRAPPER */
.page-wrapper{
    width:92%;
    margin:70px auto 30px;
}

/* CARD */
.card{
    border:none;
    border-radius:22px;
    box-shadow:0 12px 30px rgba(0,0,0,.10);
}

/* TITLE */
.page-title{
    font-weight:700;
    color:#1b4332;
}

/* FORM */
.form-label{
    font-weight:600;
}
.form-control,
.form-select{
    border-radius:14px;
}
.form-control:focus,
.form-select:focus{
    box-shadow:none;
    border-color:#52b788;
}

/* PREVIEW */
#preview{
    display:none;
    margin-top:10px;
    max-width:130px;
    border-radius:12px;
    box-shadow:0 6px 16px rgba(0,0,0,.15);
}

@media (min-width:992px){
    .page-wrapper{ max-width:720px; }
}
</style>
</head>

<body>

<a href="log_form.php" class="back-arrow">
    <i class="bi bi-arrow-left"></i>
</a>

<div class="page-wrapper">
<div class="card p-4">

<div class="text-center mb-4">
    <h4 class="page-title mb-1">
        <i class="bi bi-pencil-square"></i>
        Form Izin Guru
    </h4>
    <p class="text-muted mb-0">
        Sampaikan izin dengan jelas & profesional 👨‍🏫✨
    </p>
</div>

<form method="POST" enctype="multipart/form-data">

    <div class="mb-3">
        <label class="form-label">Jenis Izin</label>
        <select name="jenis" class="form-select" required>
            <option value="">-- Pilih Jenis --</option>
            <option value="Sakit">Sakit</option>
            <option value="Izin">Izin</option>
            <option value="Dinas">Dinas</option>
            <option value="Kendala">Kendala Lainnya</option>
        </select>
    </div>

    <div class="mb-3">
        <label class="form-label">Keterangan</label>
        <textarea name="keterangan" rows="3" class="form-control" required></textarea>
    </div>

    <div class="mb-2">
        <label class="form-label">Upload File Pendukung (opsional)</label>
        <input type="file" name="file" id="fileInput" class="form-control">
        <small class="text-muted">JPG, PNG, GIF, PDF • Maks 3MB</small>
        <img id="preview" alt="Preview">
    </div>

    <button type="submit" name="kirim"
        class="btn btn-success rounded-pill w-100 mt-4 py-2">
        <i class="bi bi-send-fill"></i> Kirim Form Izin
    </button>

</form>

</div>
</div>

<script src="../bootstrap-5.3.8-dist/js/bootstrap.bundle.min.js"></script>

<script>
document.getElementById('fileInput').addEventListener('change', function() {
    const file = this.files[0];
    if (!file || !file.type.startsWith("image/")) return;
    const reader = new FileReader();
    reader.onload = e => {
        preview.src = e.target.result;
        preview.style.display = "block";
    }
    reader.readAsDataURL(file);
});
</script>

<?php if($alertStatus === 'berhasil'): ?>
<script>
Swal.fire({
    html: `
        <div style="font-size:3.4rem;color:#2e8b57;">
            <i class="bi bi-check-circle-fill"></i>
        </div>
        <h4 class="mt-3 fw-bold">Form Izin Terkirim 🎉</h4>
        <p class="text-muted mb-0" style="font-size:.95rem;">
            Terima kasih telah mengisi form izin 🙏<br>
            <b>Menunggu persetujuan admin</b>
        </p>
    `,
    confirmButtonText:'Oke, Siap',
    allowOutsideClick:false
}).then(() => {
    window.location.href = 'log_form.php';
});
</script>
<?php endif; ?>

<?php if($alertStatus === 'gagal'): ?>
<script>
Swal.fire({
    html: `
        <div style="font-size:3.2rem;color:#dc3545;">
            <i class="bi bi-x-circle-fill"></i>
        </div>
        <h4 class="mt-3 fw-bold">Gagal Mengirim</h4>
        <p class="text-muted mb-0">
            Terjadi kesalahan 😢<br>
            Silakan coba kembali
        </p>
    `,
    confirmButtonText:'Coba Lagi'
});
</script>
<?php endif; ?>

</body>
</html>
