<!DOCTYPE html>
<html lang="id">

<head>
    <meta charset="UTF-8">
    <title>E-Surat Desa - Pengajuan Surat</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="{{ asset('assets/css/sb-admin-2.min.css') }}" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
</head>

<body id="page-top">
    <div id="wrapper">
        <ul class="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar">

            <a class="sidebar-brand d-flex align-items-center justify-content-center"
                href="{{ Auth::user()->role === 'admin' ? route('dashboard') : route('dashboarduser') }}">
                <div class="sidebar-brand-icon rotate-n-15">
                    <i class="fas fa-envelope-open-text"></i>
                </div>
                <div class="sidebar-brand-text mx-3">E-Surat Desa</div>
            </a>

            <hr class="sidebar-divider my-0">

            <li class="nav-item active">
                <a class="nav-link" href="{{ route('dashboarduser') }}">
                    <i class="fas fa-fw fa-tachometer-alt"></i>
                    <span>Dashboard</span>
                </a>
            </li>

            <hr class="sidebar-divider">

            <div class="sidebar-heading">Kependudukan</div>

            <li class="nav-item {{ Request::is('user/validasi*') ? 'active' : '' }}">
                <a class="nav-link" href="{{ route('user.validasi.index') }}">
                    <i class="fas fa-fw fa-id-card"></i>
                    <span>Validasi Penduduk</span>
                </a>
            </li>

            <hr class="sidebar-divider">

            <div class="sidebar-heading">Layanan</div>

            <li class="nav-item {{ Request::is('user/pengajuan*') ? 'active' : '' }}">
                <a class="nav-link" href="{{ route('user.pengajuan.index') }}">
                    <i class="fas fa-fw fa-file-alt"></i>
                    <span>Pengajuan Surat</span>
                </a>
            </li>

            <hr class="sidebar-divider d-none d-md-block">

            <li class="nav-item">
                <a href="{{ route('logout') }}" class="nav-link">
                    <i class="fas fa-fw fa-sign-out-alt"></i>
                    <span>Logout</span>
                </a>
            </li>

        </ul>
        <div id="content-wrapper" class="d-flex flex-column">
            <div id="content" class="p-4">

                <div class="card shadow mb-4 border-left-primary">
                    <div class="card-header py-3 d-flex justify-content-between align-items-center bg-white">
                        <h6 class="m-0 font-weight-bold text-primary">
                            <i class="fas fa-file-alt mr-2"></i> Daftar Pengajuan Surat Anda
                        </h6>
                        <button class="btn btn-success btn-sm shadow-sm" data-toggle="modal" data-target="#modalTambah">
                            <i class="fas fa-plus fa-sm"></i> Buat Pengajuan Baru
                        </button>
                    </div>

                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-hover table-bordered" width="100%" cellspacing="0">
                                <thead class="bg-light text-dark">
                                    <tr>
                                        <th style="width: 12%">Tgl Pengajuan</th>
                                        <th style="width: 18%">Jenis Surat</th>
                                        <th>Keterangan</th>
                                        <th class="text-center" style="width: 12%">Status</th>
                                        <th class="text-center" style="width: 10%">Berkas</th>
                                        <th class="text-center" style="width: 15%">Aksi</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @forelse ($pengajuan as $p)
                                    {{-- MODIFIKASI DISINI: Menambahkan ID untuk fitur highlight notifikasi --}}
                                    <tr id="surat-{{ $p->id }}">
                                        {{-- Tanggal Pengajuan --}}
                                        <td>{{ \Carbon\Carbon::parse($p->tanggal_pengajuan)->format('d/m/Y') }}</td>

                                        {{-- Jenis Surat --}}
                                        <td><span class="">{{ $p->jenis_surat }}</span></td>

                                        {{-- Keterangan --}}
                                        <td>{{ Str::limit($p->keterangan, 50) }}</td>

                                        {{-- Status Badge --}}
                                        <td class="text-center">
                                            @if(strtolower($p->status) == 'menunggu')
                                            <span class="badge badge-warning p-2 shadow-sm" style="min-width: 90px;">
                                                <i class="fas fa-clock mr-1"></i> Menunggu
                                            </span>
                                            @elseif(strtolower($p->status) == 'disetujui')
                                            <span class="badge badge-success p-2 shadow-sm" style="min-width: 90px;">
                                                <i class="fas fa-check mr-1"></i> Disetujui
                                            </span>
                                            @else
                                            <span class="badge badge-danger p-2 shadow-sm" style="min-width: 90px;">
                                                <i class="fas fa-times mr-1"></i> Ditolak
                                            </span>
                                            @endif
                                        </td>

                                        {{-- Berkas PDF --}}
                                        <td class="text-center">
                                            @if($p->berkas_persyaratan)
                                            <a href="{{ asset('berkas_pengajuan/' . $p->berkas_persyaratan) }}"
                                                target="_blank"
                                                class="btn btn-outline-danger btn-sm"
                                                title="Lihat Berkas PDF">
                                                <i class="fas fa-file-pdf"></i>
                                            </a>
                                            @else
                                            <span class="badge badge-secondary py-1 px-2" style="font-size: 0.75rem;">
                                                <i class="fas fa-times-circle"></i> Tidak ada
                                            </span>
                                            @endif
                                        </td>

                                        {{-- Tombol Aksi --}}
                                        <td class="text-center">
                                            @if(strtolower($p->status) == 'menunggu')
                                            <div class="btn-group" role="group">
                                                <button type="button"
                                                    class="btn btn-warning btn-sm btn-edit"
                                                    data-id="{{ $p->id }}"
                                                    data-jenis="{{ $p->jenis_surat }}"
                                                    data-ket="{{ $p->keterangan }}">
                                                    <i class="fas fa-edit"></i>
                                                </button>
                                                <form action="{{ route('user.pengajuan.destroy', $p->id) }}" method="POST" class="d-inline form-hapus">
                                                    @csrf
                                                    @method('DELETE')
                                                    <button type="button" class="btn btn-danger btn-sm btn-hapus-pengajuan" title="Batalkan" data-jenis="{{ $p->jenis_surat }}">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </form>
                                            </div>
                                            @else
                                            <span class="text-muted small font-italic">
                                                <i class="fas fa-check-double mr-1"></i> Selesai
                                            </span>
                                            @endif
                                        </td>
                                    </tr>
                                    @empty
                                    <tr>
                                        <td colspan="6" class="text-center py-5 text-muted">
                                            <i class="fas fa-clipboard-list fa-3x mb-3 d-block"></i>
                                            Belum ada data pengajuan. Silakan klik tombol <strong>Buat Pengajuan Baru</strong>.
                                        </td>
                                    </tr>
                                    @endforelse
                                </tbody>
                            </table>
                        </div>

                        {{-- Info Pagination --}}
                        <div class="mt-3 d-flex justify-content-between align-items-center">
                            <div class="small text-muted">
                                Menampilkan <strong>{{ $pengajuan->count() }}</strong> data pengajuan
                            </div>
                            <div>
                                {{ $pengajuan->links() }}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="modalTambah" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-lg" role="document">
            <form action="{{ route('user.pengajuan.store') }}" method="POST" enctype="multipart/form-data">
                @csrf
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title font-weight-bold">Tambah Pengajuan</h5>
                        <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <label>Nomor Surat <span class="text-danger">*</span></label>
                            <input
                                type="text"
                                name="nomor_surat"
                                class="form-control @error('nomor_surat') is-invalid @enderror"
                                placeholder="Masukkan nomor surat"
                                value="{{ old('nomor_surat') }}"
                                required>

                            {{-- Pesan Error dari Laravel --}}
                            @error('nomor_surat')
                            <div class="invalid-feedback">
                                {{ $message }}
                            </div>
                            @enderror
                        </div>

                        <div class="form-group">
                            <label>Jenis Surat</label>
                            <select name="jenis_surat" class="form-control" required>
                                <option value="" disabled selected>-- Pilih Jenis Surat --</option>
                                <option value="SKTM">Surat Keterangan Tidak Mampu (SKTM)</option>
                                <option value="SKCK">Surat Keterangan Catatan Kepolisian (SKCK)</option>
                                <option value="Surat Izin Usaha">Surat Izin Usaha</option>
                                <option value="Keterangan Kematian">Surat Keterangan Kematian</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <label>Tanggal Pengajuan <span class="text-danger">*</span></label>
                            <input
                                type="date"
                                name="tanggal_pengajuan"
                                class="form-control"
                                value="{{ date('Y-m-d') }}"
                                min="{{ date('Y-m-d') }}"
                                required>
                            <small class="text-muted">Pilih tanggal hari ini atau setelahnya.</small>
                        </div>

                        <div class="form-group">
                            <label>Keterangan</label>
                            <textarea name="keterangan" class="form-control" rows="4" placeholder="Masukkan keterangan..." required></textarea>
                        </div>

                        <div class="form-group">
                            <label>Berkas (PDF) <span class="text-danger">*</span></label>
                            <input
                                type="file"
                                name="berkas_persyaratan"
                                class="form-control-file @error('berkas_persyaratan') is-invalid @enderror"
                                accept="application/pdf"
                                required>

                            <small class="text-muted d-block">Maksimal berkas 2MB (Wajib diunggah)</small>

                            @error('berkas_persyaratan')
                            <span class="text-danger" style="font-size: 12px;">
                                <strong>{{ $message }}</strong>
                            </span>
                            @enderror
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Batal</button>

                        @if($status_validasi == 'DISETUJUI')
                        <button type="submit" class="btn btn-success">Kirim</button>
                        @else
                        <button type="button" class="btn btn-success btn-cek-status">Kirim</button>
                        @endif
                    </div>
                </div>
            </form>
        </div>
    </div>

    <div class="modal fade" id="modalEdit" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-lg" role="document">
            <form id="formEdit" action="" method="POST" enctype="multipart/form-data">
                @csrf
                @method('PUT')
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Edit Pengajuan</h5>
                        <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <label>Jenis Surat</label>
                            <select name="jenis_surat" id="edit_jenis" class="form-control" required>
                                <option value="" disabled>-- Pilih Jenis Surat --</option>
                                <option value="SKTM">Surat Keterangan Tidak Mampu (SKTM)</option>
                                <option value="SKCK">Surat Keterangan Catatan Kepolisian (SKCK)</option>
                                <option value="Surat Izin Usaha">Surat Izin Usaha</option>
                                <option value="Keterangan Kematian">Surat Keterangan Kematian</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Keterangan / Keperluan</label>
                            <textarea name="keterangan" id="edit_keterangan" class="form-control" rows="3" required></textarea>
                        </div>
                        <div class="form-group">
                            <label>Update Lampiran (Opsional)</label>
                            <input type="file" name="lampiran" class="form-control-file">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Batal</button>
                        <button type="submit" class="btn btn-primary">Simpan Perubahan</button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <script src="{{ asset('assets/js/sb-admin-2.min.js') }}"></script>

    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script>
        $(document).ready(function() {
            $('.btn-cek-status').click(function(e) {
                e.preventDefault();

                // Ambil status langsung dari variabel Blade
                let status = "{{ $status_validasi }}";

                if (status === 'DISETUJUI') {
                    // Jika ternyata sudah disetujui, langsung submit formnya
                    $(this).closest('form').submit();
                } else {
                    // Jika belum, tutup modal dan kasih peringatan
                    $('#modalTambahPengajuan').modal('hide');

                    Swal.fire({
                        title: 'Akses Dibatasi',
                        text: 'Status Anda saat ini: ' + status + '. Silakan lengkapi validasi penduduk.',
                        icon: 'warning',
                        confirmButtonColor: '#28a745',
                        confirmButtonText: 'Lengkapi Sekarang'
                    }).then((result) => {
                        if (result.isConfirmed) {
                            window.location.href = "{{ route('user.validasi.index') }}";
                        }
                    });
                }
            });
        });
        $(document).ready(function() {
            // --- 1. NOTIFIKASI SUKSES/GAGAL DARI SERVER ---
            @if(session('success'))
            Swal.fire({
                icon: 'success',
                title: 'Berhasil!',
                text: "{{ session('success') }}",
                showConfirmButton: false,
                timer: 2000,
                timerProgressBar: true
            });
            @endif

            @if(session('error'))
            Swal.fire({
                icon: 'error',
                title: 'Gagal!',
                text: "{{ session('error') }}",
            });
            @endif

            // --- 2. LOGIKA EDIT DATA ---
            $(document).on('click', '.btn-edit', function() {
                let id = $(this).data('id');
                let jenis = $(this).data('jenis');
                let ket = $(this).data('ket');

                // 1. Set URL Action secara dinamis sesuai ID data
                let urlAction = "{{ url('user/pengajuan/update') }}/" + id;
                $('#formEdit').attr('action', urlAction);

                // 2. Isi nilai ke dalam modal
                // Pastikan nilai 'jenis' di database SAMA PERSIS (besar/kecilnya) dengan value di <option>
                $('#edit_jenis').val(jenis).change();
                $('#edit_keterangan').val(ket);

                // 3. Tampilkan modal
                $('#modalEdit').modal('show');
            });
            $(document).ready(function() {
                // Logika Konfirmasi Hapus Pengajuan
                $(document).on('click', '.btn-hapus-pengajuan', function(e) {
                    let form = $(this).closest('form');
                    let jenisSurat = $(this).data('jenis');

                    Swal.fire({
                        title: 'Batalkan Pengajuan?',
                        html: `Apakah Anda yakin ingin menghapus pengajuan surat:<br><strong>${jenisSurat}</strong>?`,
                        icon: 'warning',
                        showCancelButton: true,
                        confirmButtonColor: '#e74a3b', // Warna merah (Danger)
                        cancelButtonColor: '#858796', // Warna abu-abu (Secondary)
                        confirmButtonText: 'Ya, Hapuskan',
                        cancelButtonText: 'Kembali',
                        reverseButtons: true
                    }).then((result) => {
                        if (result.isConfirmed) {
                            // Tampilkan loading saat proses hapus
                            Swal.fire({
                                title: 'Memproses...',
                                allowOutsideClick: false,
                                didOpen: () => {
                                    Swal.showLoading();
                                }
                            });
                            form.submit();
                        }
                    });
                });
            });
        });
    </script>
</body>

</html>