@extends('layouts.app')

@section('title', 'Pengajuan Surat Keterangan')

@section('content')
    <section class="mt-1">
        <div class="relative text-white py-14 overflow-hidden hero-section h-auto flex items-center justify-center">
            <img src="{{ asset('images/pengaduan-hero.png') }}" alt="Pengajuan Surat" class="absolute inset-0 w-full h-full object-cover">
            <div class="absolute inset-0 bg-gradient-to-r from-green-900/90 via-green-900/70 to-green-800/50"></div>
            <div class="p-10 container mx-auto px-4 text-center relative z-10">
                <h1 class="text-xl md:text-3xl font-bold mb-3 drop-shadow-lg">Pengajuan Surat Keterangan</h1>
                <p class="text-lg text-green-100 max-w-xl mx-auto drop-shadow">Ajukan surat keterangan desa secara online, mudah dan cepat</p>
            </div>
        </div>

        <main class="container mx-auto px-4 py-12">
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-12">
                <section class="bg-white rounded-xl shadow-lg p-8 border border-green-100">
                    <h2 class="text-2xl font-bold text-green-900 mb-6 flex items-center">
                        <svg class="w-6 h-6 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                        </svg>
                        Form Pengajuan Surat
                    </h2>

                    <form id="letterForm" action="{{ route('pengajuan-surat.store') }}" method="POST" enctype="multipart/form-data" class="space-y-6">
                        @csrf
                        <input type="hidden" name="_form_token" value="{{ $formToken['token'] }}">
                        <input type="hidden" name="_form_time" value="{{ $formToken['time'] }}">
                        <div style="display:none!important">
                            <input type="text" name="_website" tabindex="-1" autocomplete="off">
                        </div>

                        <div>
                            <label for="nama_lengkap" class="block text-gray-700 font-medium mb-2">Nama Lengkap <span class="text-red-500">*</span></label>
                            <input type="text" id="nama_lengkap" name="nama_lengkap" required
                                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-green-500"
                                placeholder="Masukkan nama anda">
                            <div id="error-nama_lengkap" class="text-red-600 text-sm mt-1"></div>
                        </div>

                        <div>
                            <label for="nik" class="block text-gray-700 font-medium mb-2">NIK <span class="text-red-500">*</span></label>
                            <input type="text" id="nik" name="nik" required maxlength="16"
                                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-green-500"
                                placeholder="16 digit nomor NIK">
                            <div id="error-nik" class="text-red-600 text-sm mt-1"></div>
                        </div>

                        <div>
                            <label for="email" class="block text-gray-700 font-medium mb-2">Email (Opsional)</label>
                            <input type="email" id="email" name="email"
                                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-green-500"
                                placeholder="Masukkan email anda">
                            <div id="error-email" class="text-red-600 text-sm mt-1"></div>
                        </div>

                        <div>
                            <label for="telepon" class="block text-gray-700 font-medium mb-2">Nomor Telepon <span class="text-red-500">*</span></label>
                            <input type="tel" id="telepon" name="telepon" required
                                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-green-500"
                                placeholder="Masukkan nomor telepon">
                            <div id="error-telepon" class="text-red-600 text-sm mt-1"></div>
                        </div>

                        <div>
                            <label for="kategori" class="block text-gray-700 font-medium mb-2">Jenis Surat <span class="text-red-500">*</span></label>
                            <select id="kategori" name="kategori" required
                                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-green-500">
                                <option value="">Pilih Jenis Surat</option>
                                @foreach ($categories as $category)
                                    <option value="{{ $category }}">{{ $category }}</option>
                                @endforeach
                            </select>
                            <div id="error-kategori" class="text-red-600 text-sm mt-1"></div>
                        </div>

                        <div>
                            <label for="isi_pengaduan" class="block text-gray-700 font-medium mb-2">Keterangan / Keperluan <span class="text-red-500">*</span></label>
                            <textarea id="isi_pengaduan" name="isi_pengaduan" rows="5" required
                                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-green-500"
                                placeholder="Jelaskan keperluan pengajuan surat anda..."></textarea>
                            <div id="error-isi_pengaduan" class="text-red-600 text-sm mt-1"></div>
                        </div>

                        <div>
                            <label for="lampiran" class="block text-gray-700 font-medium mb-2">Lampiran Dokumen Pendukung</label>
                            <input type="file" id="lampiran" name="lampiran" accept=".jpg,.jpeg,.png,.pdf"
                                class="w-full text-sm text-gray-900 border border-gray-300 rounded cursor-pointer bg-gray-50 p-2.5 file:mr-4 file:py-2 file:px-4 file:rounded file:border-0 file:text-sm file:font-semibold file:bg-gray-600 file:text-white hover:file:bg-gray-700">
                            <p class="text-xs text-gray-600 mt-1">Format: JPG, PNG, PDF. Ukuran Maksimum: 2MB. (Opsional)</p>
                            <div id="error-lampiran" class="text-red-600 text-sm mt-1"></div>
                        </div>

                        <div class="pt-2">
                            <button type="submit" id="submitBtn"
                                class="w-full bg-green-700 text-white py-3 px-6 rounded-lg hover:bg-green-800 transition font-semibold">
                                Ajukan Surat
                            </button>
                        </div>
                    </form>
                </section>

                <section class="space-y-8 animate-fadeIn">
                    <div class="bg-white rounded-xl shadow-lg p-8 border border-green-100">
                        <h2 class="text-2xl font-bold text-green-900 mb-4 flex items-center">
                            <i data-feather="info" class="mr-2"></i> Informasi Layanan
                        </h2>
                        <div class="space-y-4 text-gray-700">
                            <p>Layanan pengajuan surat keterangan desa secara online. Ajukan surat yang anda butuhkan tanpa harus datang ke kantor desa. Cukup isi form, dapatkan kode tracking, dan pantau status pengajuan anda.</p>
                            <div class="bg-green-50 p-4 rounded-lg">
                                <h3 class="font-semibold text-green-900 mb-2">Proses Pengajuan Surat:</h3>
                                <ol class="list-decimal list-inside space-y-3">
                                    <li><strong>Isi Form Pengajuan</strong> — Lengkapi data diri, pilih jenis surat, dan jelaskan keperluan anda. Lampirkan dokumen pendukung jika diperlukan.</li>
                                    <li><strong>Verifikasi Data</strong> — Staff administrasi desa akan memverifikasi kelengkapan dan kebenaran data yang anda kirimkan. Status berubah menjadi <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-yellow-100 text-yellow-800">Diproses</span>.</li>
                                    <li><strong>Review Perangkat Desa</strong> — KASI / Kaur terkait akan mereview dan menyetujui pengajuan surat. Surat mulai dicetak dan ditandatangani.</li>
                                    <li><strong>Surat Siap</strong> — Surat telah diterbitkan dan siap diambil. Status berubah menjadi <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-green-100 text-green-800">Selesai</span>.</li>
                                    <li><strong>Ambil di Kantor Desa</strong> — Datang ke kantor desa dengan membawa KTP asli untuk mengambil surat. Jam pelayanan: Senin - Jumat, 08.00 - 15.00 WIB.</li>
                                </ol>
                            </div>
                            <div class="border-t border-gray-200 pt-4">
                                <h3 class="font-semibold text-green-900 mb-2">Ketentuan:</h3>
                                <ul class="list-disc list-inside space-y-2">
                                    <li>Data diri harus sesuai dengan KTP elektronik</li>
                                    <li>NIK harus 16 digit dan valid</li>
                                    <li>Lampirkan dokumen pendukung (KK, akta, dll) sesuai jenis surat yang diajukan</li>
                                    <li>Waktu proses maksimal <strong>3 hari kerja</strong> setelah data terverifikasi</li>
                                    <li>Surat dapat diambil langsung di kantor desa dengan menunjukkan KTP asli</li>
                                    <li>Kode pengajuan (<strong>SRT-XXXXXXXX</strong>) harap disimpan untuk cek status</li>
                                </ul>
                            </div>
                        </div>
                    </div>

                    <div id="initial-view" class="bg-white rounded-xl shadow-lg p-8 border border-green-100 transition-all duration-300">
                        <h2 class="text-2xl font-bold text-green-900 mb-6 flex items-center">
                            <i data-feather="check-circle" class="mr-2"></i> Cek Status Pengajuan
                        </h2>
                        <div class="space-y-4">
                            <button id="check-status-button"
                                class="w-full bg-green-700 text-white px-6 py-3 rounded-lg font-semibold hover:bg-green-800 transition duration-150">
                                Cek Status
                            </button>
                        </div>
                    </div>

                    <div id="input-form-view" class="hidden bg-white rounded-xl shadow-lg p-8 border border-green-100 mt-6 transition-all duration-300">
                        <h2 class="text-2xl font-bold text-green-900 mb-6 flex items-center">
                            <i data-feather="search" class="mr-2"></i> Masukkan Kode Pengajuan
                        </h2>
                        <form action="/check-status" method="GET" class="space-y-6">
                            <div>
                                <label for="complaint-code" class="block text-sm font-medium text-gray-700 mb-2">Kode Pengajuan</label>
                                <input type="text" id="complaint-code" name="code" required placeholder="Contoh: SRT-12345678"
                                    class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-green-500 focus:border-green-500 transition duration-150">
                                <p class="mt-2 text-sm text-gray-500">Masukkan kode unik pengajuan Anda untuk melihat statusnya.</p>
                            </div>
                            <button type="submit"
                                class="w-full bg-green-600 text-white px-6 py-3 rounded-lg font-semibold hover:bg-green-700 transition duration-150">
                                Cari Status
                            </button>
                        </form>
                        <button id="back-button"
                            class="mt-4 w-full text-green-900 px-6 py-2 rounded-lg font-semibold hover:text-green-700 transition duration-150 text-sm">
                            &larr; Kembali
                        </button>
                    </div>
                </section>
            </div>
        </main>
    </section>

    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="https://unpkg.com/@lottiefiles/lottie-player@latest/dist/lottie-player.js"></script>

    <script type="text/javascript">
        document.addEventListener('DOMContentLoaded', function() {
            const urlParams = new URLSearchParams(window.location.search);
            const categoryParam = urlParams.get('kategori');
            if (categoryParam) {
                const selectEl = document.getElementById('kategori');
                if (selectEl) selectEl.value = categoryParam;
            }

            const nikEl = document.getElementById('nik');
            if (nikEl) {
                nikEl.addEventListener('input', function() {
                    this.value = this.value.replace(/[^0-9]/g, '');
                });
            }

            const form = document.getElementById('letterForm');
            const btn = document.getElementById('submitBtn');

            if (!form) return;

            form.addEventListener('submit', function(e) {
                e.preventDefault();

                btn.disabled = true;
                btn.textContent = 'Mengirim...';

                document.querySelectorAll('[id^="error-"]').forEach(el => el.textContent = '');

                if (nikEl) {
                    const nikVal = nikEl.value.trim();
                    if (!/^\d{16}$/.test(nikVal)) {
                        document.getElementById('error-nik').textContent = 'NIK harus berupa 16 digit angka.';
                        btn.disabled = false;
                        btn.textContent = 'Ajukan Surat';
                        return;
                    }
                }

                const formData = new FormData(form);

                fetch('{{ route('pengajuan-surat.store') }}', {
                        method: 'POST',
                        body: formData,
                        headers: {
                            'X-CSRF-TOKEN': '{{ csrf_token() }}',
                            'Accept': 'application/json'
                        }
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            Swal.fire({
                                icon: 'success',
                                title: 'Pengajuan Terkirim!',
                                html: `
                                    <p class="mb-4">Terima kasih, pengajuan surat anda telah kami terima.</p>
                                    <p class="mb-4 text-red-500">Note: Harap simpan Kode Pengajuan Anda.</p>
                                    <div class="bg-green-50 border-2 border-green-200 p-4 rounded-lg">
                                        <p class="text-sm text-gray-600 mb-2">Kode Pengajuan Anda:</p>
                                        <p class="text-2xl font-bold text-green-900">${data.ticket_number}</p>
                                    </div>
                                `,
                                confirmButtonColor: '#15803d',
                                confirmButtonText: 'OK'
                            });
                            form.reset();
                        } else {
                            if (data.errors) {
                                for (let field in data.errors) {
                                    const errorDiv = document.getElementById('error-' + field);
                                    if (errorDiv) errorDiv.textContent = data.errors[field][0];
                                }
                            }
                        }
                    })
                    .catch(error => {
                        Swal.fire({
                            icon: 'error',
                            title: 'Terjadi Kesalahan',
                            text: 'Gagal mengirim pengajuan. Silakan coba lagi.'
                        });
                    })
                    .finally(() => {
                        btn.disabled = false;
                        btn.textContent = 'Ajukan Surat';
                    });
            });
        });

        feather.replace();

        document.getElementById('check-status-button')?.addEventListener('click', () => {
            document.getElementById('initial-view').classList.add('hidden');
            document.getElementById('input-form-view').classList.remove('hidden');
        });

        document.getElementById('back-button')?.addEventListener('click', () => {
            document.getElementById('input-form-view').classList.add('hidden');
            document.getElementById('initial-view').classList.remove('hidden');
        });
    </script>
@endsection
