<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<!DOCTYPE html>
<html lang="id">

<head>
    <meta charset="UTF-8">
    <title>E-Surat Desa - Validasi Penduduk</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">
    <style>
        .modal-content {
            border-radius: 12px;
            border: none;
        }

        .badge-pending {
            background-color: #f6c23e;
            color: white;
        }

        .badge-success {
            background-color: #1cc88a;
            color: white;
        }
    </style>
</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-users mr-2"></i> Daftar Validasi Penduduk (KTP)
                        </h6>
                        <button class="btn btn-primary btn-sm shadow-sm" data-toggle="modal" data-target="#validasiModal" id="btnTambah">
                            <i class="fas fa-plus fa-sm"></i> Tambah Data Penduduk
                        </button>
                    </div>

                    <div class="card-body">
                        <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>NIK</th>
                                            <th>Nama Lengkap</th>
                                            <th>Alamat</th>
                                            <th class="text-center">Status</th>
                                            <th class="text-center">Berkas</th>
                                            <th class="text-center">Aksi</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        @forelse ($dataValidasi as $v)
                                        <tr>
                                            <td>{{ $v->nik }}</td>
                                            <td>{{ $v->nama_lengkap }}</td>
                                            <td>{{ Str::limit($v->alamat, 30) }}</td>
                                            <td class="text-center">
                                                <span class="badge {{ $v->status == 'MENUNGGU' ? 'badge-warning' : ($v->status == 'DISETUJUI' ? 'badge-success' : 'badge-danger') }}">
                                                    {{ $v->status }}
                                                </span>
                                            </td>
                                            <td class="text-center">
                                                @if($v->foto_ktp)
                                                {{-- ICON PDF DENGAN BORDER MERAH SESUAI GAMBAR --}}
                                                <a href="{{ asset('foto_ktp/' . $v->foto_ktp) }}" target="_blank" class="d-inline-block p-1 border border-danger rounded">
                                                    <i class="fas fa-file-pdf fa-lg text-danger"></i>
                                                </a>
                                                @else
                                                <small class="text-muted">Tidak ada berkas</small>
                                                @endif
                                            </td>
                                            <td class="text-center">
                                                @if($v->status == 'MENUNGGU')
                                                <div class="btn-group">
                                                    <button class="btn btn-warning btn-sm btn-edit"
                                                        data-id="{{ $v->nik }}" {{-- Digunakan untuk URL action form --}}
                                                        data-nik="{{ $v->nik }}"
                                                        data-nama="{{ $v->nama_lengkap }}"
                                                        data-tempat_lahir="{{ $v->tempat_lahir }}"
                                                        data-tanggal_lahir="{{ $v->tanggal_lahir }}"
                                                        data-jk="{{ $v->jenis_kelamin }}"
                                                        data-agama="{{ $v->agama }}"
                                                        data-pekerjaan="{{ $v->pekerjaan }}"
                                                        data-alamat="{{ $v->alamat }}"
                                                        data-rt_rw="{{ $v->rt_rw }}"
                                                        data-desa="{{ $v->desa_kelurahan }}"
                                                        data-kecamatan="{{ $v->kecamatan }}"
                                                        data-status_kawin="{{ $v->status_perkawinan }}"
                                                        data-wni="{{ $v->kewarganegaraan }}">
                                                        <i class="fas fa-edit"></i>
                                                    </button>
                                                    <button type="button" class="btn btn-danger btn-sm btn-hapus"
                                                        data-id="{{ $v->nik }}"
                                                        data-nama="{{ $v->nama_lengkap }}">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </div>

                            </div>
                            @else
                            {{-- TAMPILAN SELESAI DENGAN DOUBLE CHECK SESUAI GAMBAR --}}
                            <span class="text-muted font-italic" style="font-size: 0.9rem;">
                                <i class="fas fa-check-double mr-1"></i> Selesai
                            </span>
                            @endif
                            </td>
                            </tr>
                            @empty
                            <tr>
                                <td colspan="6" class="text-center py-4 text-muted">Data penduduk tidak ditemukan.</td>
                            </tr>
                            @endforelse
                            </tbody>
                            </table>
                            <div class="mt-3">
                                {{ $dataValidasi->links() }}
                            </div>
                        </div>
                    </div>
                </div>

                <div class="modal fade" id="validasiModal" tabindex="-1" role="dialog">
                    <div class="modal-dialog modal-lg" role="document">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title font-weight-bold" id="modalTitle">Tambah Data Penduduk</h5>
                                <button class="close" type="button" data-dismiss="modal"><span>×</span></button>
                            </div>
                            <form id="validasiForm" method="POST" enctype="multipart/form-data">
                                @csrf
                                <div id="methodField"></div>
                                <div class="modal-body">
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label>NIK (16 Digit)</label>
                                            <input type="text" name="nik" id="m_nik" class="form-control" required maxlength="16" minlength="16" pattern="[0-9]+">
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label>Nama Lengkap</label>
                                                <input
                                                    type="text"
                                                    name="nama_lengkap"
                                                    id="m_nama"
                                                    class="form-control @error('nama_lengkap') is-invalid @enderror"
                                                    value="{{ old('nama_lengkap') }}"
                                                    placeholder="Contoh: Ananda Pratama"
                                                    oninput="validateInput(this)"
                                                    onpaste="handlePaste(this)"
                                                    required>

                                                @error('nama_lengkap')
                                                <span class="text-danger" style="font-size: 12px;">
                                                    <strong>{{ $message }}</strong>
                                                </span>
                                                @enderror

                                                <small id="name-error" class="text-danger" style="display:none;">
                                                    Nama tidak boleh mengandung angka!
                                                </small>
                                            </div>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label>Tempat Lahir</label>
                                            <input type="text" name="tempat_lahir" id="m_tempat_lahir" class="form-control" required>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label>Tanggal Lahir</label>
                                            <input type="date" name="tanggal_lahir" id="m_tanggal_lahir" class="form-control" required>
                                        </div>
                                        <div class="col-md-4 mb-3">
                                            <label>Jenis Kelamin</label>
                                            <select name="jenis_kelamin" id="m_jk" class="form-control" required>
                                                <option value="" disabled selected>-- Pilih Jenis Kelamin --</option>
                                                <option value="LAKI-LAKI">LAKI-LAKI</option>
                                                <option value="PEREMPUAN">PEREMPUAN</option>
                                            </select>
                                        </div>

                                        <div class="col-md-4 mb-3">
                                            <label>Agama</label>
                                            <select name="agama" id="m_agama" class="form-control" required>
                                                <option value="" disabled selected>-- Pilih Agama --</option>
                                                <option value="ISLAM">ISLAM</option>
                                                <option value="KRISTEN">KRISTEN</option>
                                                <option value="KATOLIK">KATOLIK</option>
                                                <option value="HINDU">HINDU</option>
                                                <option value="BUDHA">BUDHA</option>
                                                <option value="KHONGHUCU">KHONGHUCU</option>
                                            </select>
                                        </div>
                                        <div class="col-md-4 mb-3">
                                            <label>Pekerjaan</label>
                                            <input type="text" name="pekerjaan" id="m_pekerjaan" class="form-control" placeholder="Contoh: Karyawan Swasta" required>
                                        </div>
                                        <div class="col-md-8 mb-3">
                                            <label>Alamat</label>
                                            <input type="text" name="alamat" id="m_alamat" class="form-control" required>
                                        </div>
                                        <div class="col-md-4 mb-3">
                                            <label>RT/RW</label>
                                            <input type="text" name="rt_rw" id="m_rt_rw" class="form-control" placeholder="001/002" required>
                                        </div>
                                        <div class="col-md-4 mb-3">
                                            <label>Desa/Kelurahan</label>
                                            <input type="text" name="desa_kelurahan" id="m_desa" class="form-control" required>
                                        </div>
                                        <div class="col-md-4 mb-3">
                                            <label>Kecamatan</label>
                                            <input type="text" name="kecamatan" id="m_kecamatan" class="form-control" required>
                                        </div>
                                        <div class="col-md-4 mb-3">
                                            <label>Status Perkawinan</label>
                                            <select name="status_perkawinan" id="m_status_kawin" class="form-control" required>
                                                <option value="" disabled selected>-- Pilih Status --</option>
                                                <option value="BELUM KAWIN">BELUM KAWIN</option>
                                                <option value="KAWIN">KAWIN</option>
                                                <option value="CERAI HIDUP">CERAI HIDUP</option>
                                                <option value="CERAI MATI">CERAI MATI</option>
                                            </select>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label>Kewarganegaraan</label>
                                            <input type="text" name="kewarganegaraan" id="m_wni" class="form-control" value="WNI" required>
                                        </div>

                                        <div class="col-12">
                                            <label>Upload Foto KTP (JPG/PNG) <span class="text-danger" id="bintang_foto">*</span></label>
                                            <div style="display: block; width: fit-content;">
                                                <input type="file" name="foto_ktp" id="m_foto_ktp" class="form-control-file" accept="image/jpeg, image/png" required>
                                            </div>
                                            <small class="text-muted" id="fileNote">*Harus berupa file gambar (JPG/PNG).</small>
                                        </div>
                                    </div>
                                </div>
                                <div class="modal-footer">
                                    <button class="btn btn-secondary" type="button" data-dismiss="modal">Batal</button>
                                    <button class="btn btn-primary" type="submit">Simpan Data</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
                <div class="modal fade" id="validasiModal" tabindex="-1" role="dialog" aria-labelledby="modalTitle" aria-hidden="true">
                    <div class="modal-dialog modal-lg" role="document">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title" id="modalTitle">Edit Data Penduduk</h5>
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                    <span aria-hidden="true">&times;</span>
                                </button>
                            </div>
                            <form id="validasiForm" method="POST" enctype="multipart/form-data">
                                @csrf
                                <div id="methodField"></div>
                                <div class="modal-body">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label>NIK (16 Digit)</label>
                                                <input type="text" name="nik" id="m_nik" class="form-control" readonly>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label>Nama Lengkap</label>
                                                <input
                                                    type="text"
                                                    name="nama_lengkap"
                                                    id="m_nama"
                                                    class="form-control @error('nama_lengkap') is-invalid @enderror"
                                                    value="{{ old('nama_lengkap') }}"
                                                    placeholder="Contoh: Ananda Pratama"
                                                    oninput="validateInput(this)"
                                                    required>

                                                @error('nama_lengkap')
                                                <span class="text-danger" style="font-size: 12px;">
                                                    <strong>{{ $message }}</strong>
                                                </span>
                                                @enderror

                                                <small id="name-error" class="text-danger" style="display:none;">
                                                    Nama tidak boleh mengandung angka!
                                                </small>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label>Tempat Lahir</label>
                                                <input type="text" name="tempat_lahir" id="m_tempat_lahir" class="form-control" required>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label>Tanggal Lahir</label>
                                                <input type="date" name="tanggal_lahir" id="m_tanggal_lahir" class="form-control" required>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="row">
                                        <div class="col-md-4">
                                            <div class="form-group">
                                                <label>Jenis Kelamin</label>
                                                <select name="jenis_kelamin" id="m_jk" class="form-control" required>
                                                    <option value="LAKI-LAKI">LAKI-LAKI</option>
                                                    <option value="PEREMPUAN">PEREMPUAN</option>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="form-group">
                                                <label>Agama</label>
                                                <select name="agama" id="m_agama" class="form-control" required>
                                                    <option value="ISLAM">ISLAM</option>
                                                    <option value="KRISTEN">KRISTEN</option>
                                                    <option value="KATOLIK">KATOLIK</option>
                                                    <option value="HINDU">HINDU</option>
                                                    <option value="BUDHA">BUDHA</option>
                                                    <option value="KONGHUCU">KONGHUCU</option>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="form-group">
                                                <label>Pekerjaan</label>
                                                <input type="text" name="pekerjaan" id="m_pekerjaan" class="form-control" placeholder="Contoh: Karyawan Swasta" required>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="row">
                                        <div class="col-md-8">
                                            <div class="form-group">
                                                <label>Alamat</label>
                                                <input type="text" name="alamat" id="m_alamat" class="form-control" required>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="form-group">
                                                <label>RT/RW</label>
                                                <input type="text" name="rt_rw" id="m_rt_rw" class="form-control" placeholder="001/002" required>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="row">
                                        <div class="col-md-4">
                                            <div class="form-group">
                                                <label>Desa/Kelurahan</label>
                                                <input type="text" name="desa_kelurahan" id="m_desa" class="form-control" required>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="form-group">
                                                <label>Kecamatan</label>
                                                <input type="text" name="kecamatan" id="m_kecamatan" class="form-control" required>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="form-group">
                                                <label>Status Perkawinan</label>
                                                <select name="status_perkawinan" id="m_status_kawin" class="form-control" required>
                                                    <option value="BELUM KAWIN">BELUM KAWIN</option>
                                                    <option value="KAWIN">KAWIN</option>
                                                    <option value="CERAI HIDUP">CERAI HIDUP</option>
                                                    <option value="CERAI MATI">CERAI MATI</option>
                                                </select>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="form-group">
                                        <label>Kewarganegaraan</label>
                                        <input type="text" name="kewarganegaraan" id="m_wni" class="form-control" value="WNI" required>
                                    </div>

                                    <div class="form-group">
                                        <label>Upload Foto KTP (JPG/PNG)</label>
                                        <input type="file" name="foto_ktp" class="form-control-file">
                                        <small class="text-muted">*Kosongkan jika tidak ingin mengubah foto.</small>
                                    </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 Data</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>

                <form id="deleteForm" method="POST" style="display: none;">
                    @csrf
                    @method('DELETE')
                </form>
                <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
                <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
                <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.bundle.min.js"></script>
                <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

                <script>
    $(document).ready(function() {
        // --- 1. NOTIFIKASI OTOMATIS 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

        // MENAMPILKAN ERROR VALIDASI (Misal: Nama mengandung angka dari Controller)
        @if($errors->any())
        Swal.fire({
            icon: 'error',
            title: 'Validasi Gagal!',
            html: `
                <ul style="text-align: left;">
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            `,
        });
        @endif

        // --- 2. LOGIKA TAMBAH DATA ---
        $('#btnTambah').click(function() {
            $('#modalTitle').text('Tambah Data Penduduk');
            $('#validasiForm').attr('action', "{{ route('user.validasi.store') }}");
            $('#methodField').html('');
            $('#validasiForm')[0].reset();
            $('#name-error').hide(); // Sembunyikan error visual saat modal buka
            $('#validasiModal').modal('show');
        });

        // --- 3. LOGIKA EDIT DATA ---
        $('.btn-edit').click(function() {
            const id = $(this).data('nik');

            $('#modalTitle').text('Edit Data Penduduk');
            $('#validasiForm').attr('action', "/user/validasi/" + id);
            $('#methodField').html('@method("PUT")');

            // Pengisian field otomatis
            $('#m_nik').val($(this).data('nik'));
            $('#m_nama').val($(this).data('nama'));
            $('#m_tempat_lahir').val($(this).data('tempat_lahir'));
            $('#m_tanggal_lahir').val($(this).data('tanggal_lahir'));
            $('#m_jk').val($(this).data('jk'));
            $('#m_agama').val($(this).data('agama'));
            $('#m_pekerjaan').val($(this).data('pekerjaan'));
            $('#m_alamat').val($(this).data('alamat'));
            $('#m_rt_rw').val($(this).data('rt_rw'));
            $('#m_desa').val($(this).data('desa'));
            $('#m_kecamatan').val($(this).data('kecamatan'));
            $('#m_status_kawin').val($(this).data('status_kawin'));
            $('#m_wni').val($(this).data('wni'));

            $('#name-error').hide(); // Sembunyikan error saat edit dibuka
            $('#validasiModal').modal('show');
        });

        // --- 4. LOGIKA HAPUS DATA ---
        $('.btn-hapus').off('click').on('click', function(e) {
            e.preventDefault();

            const id = $(this).data('id');
            const nama = $(this).data('nama');

            Swal.fire({
                title: 'Hapus Data?',
                html: `Apakah Anda yakin ingin menghapus data:<br><strong>${nama}</strong>?`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#e74a3b',
                cancelButtonColor: '#858796',
                confirmButtonText: 'Ya, Hapus!',
                cancelButtonText: 'Batal',
                reverseButtons: true,
                focusCancel: true
            }).then((result) => {
                if (result.isConfirmed) {
                    Swal.fire({
                        title: 'Memproses...',
                        text: 'Mohon tunggu sebentar',
                        allowOutsideClick: false,
                        didOpen: () => {
                            Swal.showLoading();
                        }
                    });
                    $('#deleteForm').attr('action', "/user/validasi/" + id).submit();
                }
            });
        });
    });

    // --- 5. FUNGSI VALIDASI INPUT (LUAR DOCUMENT READY) ---
    function validateInput(input) {
        const errorElement = document.getElementById('name-error');
        const originalValue = input.value;

        // Cek angka (0-9)
        if (/[0-9]/.test(originalValue)) {
            errorElement.style.display = 'block';
            // Hapus angka dari input
            input.value = originalValue.replace(/[0-9]/g, '');
        } else {
            errorElement.style.display = 'none';
        }
    }

    function handlePaste(input) {
        setTimeout(function() {
            validateInput(input);
        }, 0);
    }
</script>
</body>

</html>