<?php
require_once '../config.php';
$app_title = getSetting($pdo, 'app_title');
$app_align = getSetting($pdo, 'app_align') ?: 'text-center';
$page_title = "Formulir Pengajuan - " . $app_title;
$active_page = 'form';
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($page_title) ?></title>
    <link rel="icon" type="image/png" href="<?= base_url('logo/logo.png?v='.time()) ?>">
    <link rel="shortcut icon" type="image/png" href="<?= base_url('logo/logo.png?v='.time()) ?>">
    <?php if(file_exists('logo/logo.png')): ?>
    <link rel="preload" as="image" href="<?= base_url('logo/logo.png') ?>">
    <?php endif; ?>
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- FontAwesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;700&display=swap" rel="stylesheet">
    <!-- Select2 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" rel="stylesheet" />
    <!-- SweetAlert2 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    <style>
        /* ==============================================================
           PENGATURAN VISUAL FORMULIR (MUDAH DIATUR SECARA MANUAL)
           Ubah nilai di bawah ini untuk mengubah tampilan form pengajuan.
           ============================================================== */
        :root {
            --form-max-width: 1000px;       /* Ukuran maksimal lebar form (contoh: 800px, 1000px, 1200px) */
            --form-bg-color: #ffffff;       /* Warna latar belakang kotak form */
            --form-border-radius: 16px;     /* Tingkat kelengkungan sudut form (contoh: 8px, 16px, 24px) */
            --form-padding: 30px 40px;      /* Jarak ruang dalam form (atas-bawah kiri-kanan) */
            --form-shadow: 0 8px 30px rgba(0,0,0,0.08); /* Efek bayangan form */
            --body-bg-color: #f8f9fa;       /* Warna latar belakang halaman keseluruhan */
            --font-family: 'Inter', sans-serif; /* Jenis huruf font utama */
        }

        html, body { height: 100%; overflow: hidden; font-family: var(--font-family); background-color: var(--body-bg-color); }
        
        .form-container { 
            width: 100%; 
            max-width: var(--form-max-width); 
            max-height: 90vh; 
            margin: 0 auto 2.5vh auto; 
            background: var(--form-bg-color); 
            padding: var(--form-padding); 
            border-radius: var(--form-border-radius); 
            box-shadow: var(--form-shadow); 
            overflow-y: auto; 
        }

        .form-label { font-weight: 600; color: #495057; font-size: 0.95rem; margin-bottom: 0.3rem; }
        .required::after { content: " *"; color: red; }
        .select2-container--bootstrap-5 .select2-selection { min-height: 38px; }
        
        /* Perbaikan scroll & padding khusus Mobile */
        @media (max-width: 767px) {
            html, body { height: auto; overflow: visible; }
            .form-container { 
                max-height: none; 
                margin: 15px auto; 
                padding: 20px 15px; 
                overflow-y: visible; 
                border-radius: 12px; /* Lebih kecil di HP */
            }
        }
    </style>
<body class="pb-5">

<main class="container mt-5 mb-4">
    <!-- Header Publik Terpusat -->
    <?php include 'header_public.php'; ?>

    <div class="form-container border-top border-primary border-3 mt-2 mb-2 position-relative">
        <!-- Tombol Beranda Kiri Atas -->
        <a href="../index.php" class="text-decoration-none fw-bold text-primary position-absolute d-none d-sm-block" style="top: 25px; left: 30px;">
            <i class="fas fa-home me-1"></i> Beranda
        </a>
        <!-- Tombol Lacak Kanan Atas -->
        <a href="track.php" class="text-decoration-none fw-bold text-primary position-absolute d-none d-sm-block" style="top: 25px; right: 30px;">
            Lacak Status <i class="fas fa-search ms-1"></i>
        </a>
        
        <!-- Versi Mobile (Tengah, Kecil & Samar) -->
        <div class="d-flex justify-content-center align-items-center gap-3 px-2 d-sm-none mb-4 opacity-75" style="font-size: 0.85rem;">
            <a href="../index.php" class="text-decoration-none text-muted fw-semibold">
                <i class="fas fa-home me-1"></i> Beranda
            </a>
            <span class="text-muted">|</span>
            <a href="track.php" class="text-decoration-none text-muted fw-semibold">
                Lacak <i class="fas fa-search ms-1"></i>
            </a>
        </div>

        <div class="text-center mb-3 mt-1">
            <h4 class="fw-bold text-dark mb-1"><i class="fas fa-file-signature text-primary me-2"></i>Formulir Pengajuan Online</h4>
            <p class="text-muted small mb-0">Lengkapi data di bawah ini dengan valid dan benar.</p>
        </div>

        <form id="formPengajuan" enctype="multipart/form-data">
            <div class="row g-3">
                <div class="col-md-6">
                    <label class="form-label required">Nama Lengkap</label>
                    <input type="text" class="form-control" name="nama_lengkap" placeholder="Masukkan nama" required>
                </div>
                <div class="col-md-6">
                    <label class="form-label required">Asal Instansi</label>
                    <input type="text" class="form-control" name="asal_instansi" placeholder="Misal: Univ Brawijaya" required>
                </div>
                <div class="col-md-6">
                    <label class="form-label required">No. WhatsApp</label>
                    <input type="text" class="form-control" name="no_wa" placeholder="08..." required>
                </div>
                <div class="col-md-6">
                    <label class="form-label required">Email</label>
                    <input type="email" class="form-control" name="email" placeholder="email@domain.com" required>
                </div>

                <div class="col-12">
                    <label class="form-label required">Alamat Lengkap (Jalan, RT/RW)</label>
                    <input type="text" class="form-control" name="alamat" placeholder="Nama Jalan, Nomor, RT/RW, dsb" required>
                </div>

                <!-- Input Wilayah Dinamis dengan Select2 -->
                <div class="col-md-4">
                    <label class="form-label required">Provinsi</label>
                    <select class="form-select select2" name="provinsi" id="provinsi" required>
                        <option value="">Pilih Provinsi...</option>
                    </select>
                </div>
                <div class="col-md-4">
                    <label class="form-label required">Kota / Kabupaten</label>
                    <select class="form-select select2" name="kota" id="kota" required disabled>
                        <option value="">Pilih Kota/Kabupaten...</option>
                    </select>
                </div>
                <div class="col-md-4">
                    <label class="form-label required">Kecamatan</label>
                    <select class="form-select select2" name="kecamatan" id="kecamatan" required disabled>
                        <option value="">Pilih Kecamatan...</option>
                    </select>
                    <input type="hidden" name="kecamatan_nama" id="kecamatan_nama">
                </div>

                <div class="col-md-6">
                    <label class="form-label required">Tujuan</label>
                    <select class="form-select select2-basic" name="tujuan" required>
                        <option value="">-- Pilih Tujuan --</option>
                        <option value="Magang / PKL">Magang / PKL</option>
                        <option value="Layanan Eazy Passport">Layanan Eazy Passport</option>
                        <option value="Kerjasama Instansi">Kerjasama Instansi</option>
                        <option value="Pengaduan Masyarakat">Pengaduan Masyarakat</option>
                        <option value="Undangan Kegiatan">Undangan Kegiatan</option>
                        <option value="Lainnya">Lainnya...</option>
                    </select>
                </div>
                <div class="col-md-6">
                    <label class="form-label required">Lampiran (PDF/JPG, Max 2MB)</label>
                    <input type="file" class="form-control" name="file_lampiran" accept=".pdf,.jpg,.jpeg,.png" required>
                </div>
                
                <div class="col-12 mt-2">
                    <label class="form-label">Catatan Tambahan</label>
                    <textarea class="form-control" name="catatan" rows="3" placeholder="Opsional (Keterangan spesifik)"></textarea>
                </div>

                <div class="col-12 mt-4 mb-2 text-center">
                    <button type="submit" id="btnSubmit" class="btn btn-primary btn-lg px-5 fw-bold shadow-sm rounded-pill w-100">
                        <i class="fas fa-paper-plane me-2"></i>Kirim Pengajuan
                    </button>
                </div>
            </div>
        </form>
    </div>
</main>

<footer class="fixed-bottom bg-transparent text-secondary py-3 text-center" style="pointer-events: none; z-index: 10;">
    <p class="mb-0 small fw-bold text-shadow-sm" style="text-shadow: 0 1px 2px rgba(255,255,255,0.8);">&copy; <?= date('Y') ?> <?= htmlspecialchars($app_title) ?>. Kantor Imigrasi Kelas I Non TPI Sukabumi.</p>
</footer>

<!-- Scripts -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>

<script>
    $(function() {
        // Init Select2
        $('.select2').select2({ theme: 'bootstrap-5', width: '100%' });
        $('.select2-basic').select2({ theme: 'bootstrap-5', minimumResultsForSearch: Infinity, width: '100%' });

        // Load Provinsi
        fetch('https://www.emsifa.com/api-wilayah-indonesia/api/provinces.json')
            .then(r => r.json())
            .then(provs => {
                let opts = '<option value="">Pilih Provinsi...</option>';
                provs.forEach(p => { opts += `<option value="${p.name}" data-id="${p.id}">${p.name}</option>`; });
                $('#provinsi').html(opts);
            });

        // Load Kota when Provinsi changes
        $('#provinsi').on('change', function() {
            const provId = $(this).find(':selected').data('id');
            const $kota = $('#kota');
            $kota.html('<option value="">Sedang memuat...</option>').prop('disabled', true);
            $('#kecamatan').prop('disabled', true).html('<option value="">-- Pilih Kecamatan --</option>');
            $('#kecamatan_nama').val('');
            if (provId) {
                fetch(`https://www.emsifa.com/api-wilayah-indonesia/api/regencies/${provId}.json`)
                    .then(r => r.json())
                    .then(kotas => {
                        let opts = '<option value="">Pilih Kota/Kabupaten...</option>';
                        kotas.forEach(k => { opts += `<option value="${k.name}" data-id="${k.id}">${k.name}</option>`; });
                        $kota.html(opts).prop('disabled', false);
                    });
            }
        });

        // Load Kecamatan when Kota changes
        $('#kota').on('change', function() {
            const kotaId = $(this).find(':selected').data('id');
            const $kec = $('#kecamatan');
            $kec.prop('disabled', true).html('<option value="">-- Pilih Kecamatan --</option>');
            $('#kecamatan_nama').val('');
            if (kotaId) {
                fetch(`https://www.emsifa.com/api-wilayah-indonesia/api/districts/${kotaId}.json`)
                    .then(r => r.json())
                    .then(dists => {
                        let opts = '<option value="">Pilih Kecamatan...</option>';
                        dists.forEach(d => { opts += `<option value="${d.name}" data-id="${d.id}">${d.name}</option>`; });
                        $kec.html(opts).prop('disabled', false);
                    });
            }
        });

        // Set hidden kecamatan name
        $('#kecamatan').on('change', function() {
            const kecName = $(this).find(':selected').text();
            $('#kecamatan_nama').val(kecName);
        });

        // Form Submit API
        document.getElementById('formPengajuan').addEventListener('submit', function(e) {
        e.preventDefault();
        const btn = document.getElementById('btnSubmit');
        const formData = new FormData(this);

        btn.disabled = true;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Memproses...';

        fetch('submit.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            btn.disabled = false;
            btn.innerHTML = '<i class="fas fa-paper-plane me-2"></i>Kirim Pengajuan';

            if(data.status === 'success') {
                let timerInterval;
                Swal.fire({
                    title: 'Pengajuan Berhasil Terkirim!',
                    html: `
                        <p class="mb-3">Mohon catat <b>Nomor Tiket</b> Anda:</p>
                        <h2 class="text-primary fw-bold mb-3 border p-3 rounded bg-light" style="letter-spacing: 2px;">${data.no_tiket}</h2>
                        <p class="text-muted small">Notifikasi juga telah dikirim ke WA dan Email Anda.</p>
                        <p class="text-danger small mt-2">Otomatis dialihkan dalam <b></b> detik.</p>
                    `,
                    icon: 'success',
                    timer: 10000,
                    timerProgressBar: true,
                    showConfirmButton: true,
                    confirmButtonText: '<i class="fas fa-check"></i> Tutup & Buat Baru',
                    allowOutsideClick: false,
                    didOpen: () => {
                        const b = Swal.getHtmlContainer().querySelector('b:last-of-type')
                        timerInterval = setInterval(() => {
                            b.textContent = Math.ceil(Swal.getTimerLeft() / 1000)
                        }, 100)
                    },
                    willClose: () => {
                        clearInterval(timerInterval)
                    }
                }).then((result) => {
                    window.location.reload();
                });
                $('#provinsi, #kota, .select2-basic').val('').trigger('change');
            } else {
                Swal.fire('Gagal!', data.message, 'error');
            }
        })
        .catch(error => {
            btn.disabled = false;
            btn.innerHTML = '<i class="fas fa-paper-plane me-2"></i>Kirim Pengajuan';
            Swal.fire('Error!', 'Terjadi kesalahan sistem/jaringan.', 'error');
        });
    });
});
</script>
</body>
</html>
