<x-app-layout>
    <div class="mb-12">
        <div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-6 mb-8">
            <div class="relative">
                <div
                    class="absolute -left-3 -top-3 w-20 h-20 bg-gradient-to-br from-violet-500/10 to-indigo-600/10 rounded-full blur-xl">
                </div>
                <h1 class="text-4xl font-black tracking-tight dark:text-white relative z-10 mb-2">
                    <span class="bg-gradient-to-r from-violet-600 to-indigo-600 bg-clip-text text-transparent">
                        Validasi Pengajuan Status Akademik
                    </span>
                </h1>
                <p class="text-slate-500 dark:text-slate-400 text-sm pl-1">
                    <i data-lucide="check-circle" class="w-4 h-4 inline mr-2"></i>
                    Validasi pengajuan perubahan status akademik
                </p>
            </div>

            <div class="flex items-center gap-4">
                <a href="{{ route('dashboard') }}"
                    class="px-4 py-2.5 bg-white dark:bg-gray-800 border border-slate-200 dark:border-gray-700 rounded-xl text-sm font-medium text-slate-600 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-gray-700 transition-all flex items-center gap-2 shadow-sm">
                    <i data-lucide="arrow-left" class="w-4 h-4"></i>
                    <span>Kembali</span>
                </a>
            </div>
        </div>

        <!-- Flash Messages -->
        @if (session('success'))
            <div
                class="mb-6 p-4 bg-gradient-to-r from-green-500/10 to-emerald-600/10 border border-green-500/20 rounded-2xl flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl bg-green-500/10 text-green-500 flex items-center justify-center">
                    <i data-lucide="check-circle" class="w-5 h-5"></i>
                </div>
                <div class="flex-1">
                    <p class="font-medium text-green-700 dark:text-green-400">{{ session('success') }}</p>
                </div>
                <button onclick="this.parentElement.remove()" class="text-green-500 hover:text-green-600">
                    <i data-lucide="x" class="w-4 h-4"></i>
                </button>
            </div>
        @endif

        @if (session('error'))
            <div
                class="mb-6 p-4 bg-gradient-to-r from-red-500/10 to-rose-600/10 border border-red-500/20 rounded-2xl flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl bg-red-500/10 text-red-500 flex items-center justify-center">
                    <i data-lucide="alert-triangle" class="w-5 h-5"></i>
                </div>
                <div class="flex-1">
                    <p class="font-medium text-red-700 dark:text-red-400">{{ session('error') }}</p>
                </div>
                <button onclick="this.parentElement.remove()" class="text-red-500 hover:text-red-600">
                    <i data-lucide="x" class="w-4 h-4"></i>
                </button>
            </div>
        @endif

        <!-- Statistics Cards -->
        <div class="grid grid-cols-2 md:grid-cols-6 gap-4 mb-6">
            <div class="bg-white dark:bg-[#1a1a2e] rounded-xl border border-slate-200 dark:border-white/5 p-4">
                <div class="text-center">
                    <p class="text-2xl font-bold text-purple-600">{{ $statistics['total'] ?? 0 }}</p>
                    <p class="text-xs text-slate-500">Total Pengajuan</p>
                </div>
            </div>
            <div class="bg-white dark:bg-[#1a1a2e] rounded-xl border border-slate-200 dark:border-white/5 p-4">
                <div class="text-center">
                    <p class="text-2xl font-bold text-green-600">{{ $statistics['aktif'] ?? 0 }}</p>
                    <p class="text-xs text-slate-500">Aktif</p>
                </div>
            </div>
            <div class="bg-white dark:bg-[#1a1a2e] rounded-xl border border-slate-200 dark:border-white/5 p-4">
                <div class="text-center">
                    <p class="text-2xl font-bold text-yellow-600">{{ $statistics['cuti'] ?? 0 }}</p>
                    <p class="text-xs text-slate-500">Cuti</p>
                </div>
            </div>
            <div class="bg-white dark:bg-[#1a1a2e] rounded-xl border border-slate-200 dark:border-white/5 p-4">
                <div class="text-center">
                    <p class="text-2xl font-bold text-red-600">{{ $statistics['drop_out'] ?? 0 }}</p>
                    <p class="text-xs text-slate-500">Drop Out</p>
                </div>
            </div>
            <div class="bg-white dark:bg-[#1a1a2e] rounded-xl border border-slate-200 dark:border-white/5 p-4">
                <div class="text-center">
                    <p class="text-2xl font-bold text-blue-600">{{ $statistics['lulus'] ?? 0 }}</p>
                    <p class="text-xs text-slate-500">Lulus</p>
                </div>
            </div>
            <div class="bg-white dark:bg-[#1a1a2e] rounded-xl border border-slate-200 dark:border-white/5 p-4">
                <div class="text-center">
                    <p class="text-2xl font-bold text-gray-600">{{ $statistics['tidak_aktif'] ?? 0 }}</p>
                    <p class="text-xs text-slate-500">Tidak Aktif</p>
                </div>
            </div>
        </div>

        <!-- Filter Section -->
        <div class="mb-6 bg-white dark:bg-[#1a1a2e] rounded-xl border border-slate-200 dark:border-white/5 p-4">
            <form method="GET" action="{{ route('validasi-pengajuan.index') }}" class="space-y-4">
                <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
                    @if (auth()->user()->role->name == 'superadmin' || auth()->user()->role->name == 'admin')
                        <div>
                            <label
                                class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Kampus</label>
                            <select name="kampus_id" id="kampusFilter"
                                class="w-full px-4 py-2 bg-white dark:bg-gray-800 border border-slate-200 dark:border-gray-700 rounded-lg text-sm focus:ring-2 focus:ring-violet-500">
                                <option value="all">Semua Kampus</option>
                                @if (isset($kampusList) && $kampusList->isNotEmpty())
                                    @foreach ($kampusList as $kampus)
                                        <option value="{{ $kampus->id }}"
                                            {{ request('kampus_id') == $kampus->id ? 'selected' : '' }}>
                                            {{ $kampus->nama }}
                                        </option>
                                    @endforeach
                                @endif
                            </select>
                        </div>
                    @endif

                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Jenis
                            Pengajuan</label>
                        <select name="jenis"
                            class="w-full px-4 py-2 bg-white dark:bg-gray-800 border border-slate-200 dark:border-gray-700 rounded-lg text-sm focus:ring-2 focus:ring-violet-500">
                            <option value="all">Semua Jenis</option>
                            <option value="aktif" {{ request('jenis') == 'aktif' ? 'selected' : '' }}>Aktif</option>
                            <option value="cuti" {{ request('jenis') == 'cuti' ? 'selected' : '' }}>Cuti</option>
                            <option value="drop_out" {{ request('jenis') == 'drop_out' ? 'selected' : '' }}>Drop Out
                            </option>
                            <option value="lulus" {{ request('jenis') == 'lulus' ? 'selected' : '' }}>Lulus</option>
                            <option value="tidak_aktif" {{ request('jenis') == 'tidak_aktif' ? 'selected' : '' }}>Tidak
                                Aktif</option>
                        </select>
                    </div>

                    <div class="md:col-span-2">
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Pencarian</label>
                        <div class="relative">
                            <i data-lucide="search"
                                class="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-slate-400"></i>
                            <input type="text" name="search" value="{{ request('search') }}"
                                placeholder="Cari NIM atau Nama Mahasiswa..."
                                class="w-full pl-10 pr-4 py-2 bg-white dark:bg-gray-800 border border-slate-200 dark:border-gray-700 rounded-lg text-sm focus:ring-2 focus:ring-violet-500">
                        </div>
                    </div>
                </div>

                <div class="flex justify-end gap-2">
                    <button type="submit"
                        class="px-4 py-2 bg-gradient-to-r from-violet-600 to-indigo-700 text-white rounded-lg text-sm font-medium hover:shadow-lg hover:shadow-violet-500/25 transition-all flex items-center gap-2">
                        <i data-lucide="filter" class="w-4 h-4"></i> Filter
                    </button>
                    <a href="{{ route('validasi-pengajuan.index') }}"
                        class="px-4 py-2 bg-white dark:bg-gray-800 border border-slate-200 dark:border-gray-700 rounded-lg text-sm font-medium text-slate-600 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-gray-700 transition-all flex items-center gap-2">
                        <i data-lucide="x" class="w-4 h-4"></i> Reset
                    </a>
                </div>
            </form>
        </div>

        <!-- Bulk Actions -->
        <div class="mb-4 p-4 bg-white dark:bg-[#1a1a2e] rounded-xl border border-slate-200 dark:border-white/5">
            <div class="flex flex-wrap items-center gap-4">
                <div class="flex items-center gap-2">
                    <span class="text-sm text-slate-600 dark:text-slate-400" id="selectedCount">0 pengajuan
                        dipilih</span>
                    <button type="button" onclick="clearSelection()"
                        class="text-xs text-violet-600 hover:underline">Hapus pilihan</button>
                </div>

                <div class="flex items-center gap-2 ml-auto">
                    <select id="bulkAction"
                        class="px-3 py-2 bg-white dark:bg-gray-800 border border-slate-200 dark:border-gray-700 rounded-lg text-sm focus:ring-2 focus:ring-violet-500">
                        <option value="">Pilih Aksi</option>
                        <option value="approve">Setujui Semua</option>
                        <option value="reject">Tolak Semua</option>
                    </select>
                    <button type="button" onclick="bulkAction()"
                        class="px-4 py-2 bg-violet-600 text-white rounded-lg text-sm font-medium hover:bg-violet-700 transition-all disabled:opacity-50 disabled:cursor-not-allowed"
                        id="bulkActionBtn" disabled>
                        <i data-lucide="check-circle" class="w-4 h-4 inline mr-1"></i>
                        Proses
                    </button>
                </div>
            </div>
        </div>

        <!-- Table -->
        <div class="bg-white dark:bg-[#1a1a2e] rounded-xl border border-slate-200 dark:border-white/5 overflow-hidden">
            <div class="overflow-x-auto">
                <table class="w-full">
                    <thead>
                        <tr class="bg-slate-50/50 dark:bg-white/5 border-b">
                            <th class="py-4 px-6 w-12">
                                <input type="checkbox" id="selectAll" class="w-4 h-4 text-violet-600 rounded">
                            </th>
                            <th class="text-left py-4 px-6 text-xs font-semibold text-slate-500 uppercase">No</th>
                            <th class="text-left py-4 px-6 text-xs font-semibold text-slate-500 uppercase">NIM</th>
                            <th class="text-left py-4 px-6 text-xs font-semibold text-slate-500 uppercase">Nama</th>
                            <th class="text-left py-4 px-6 text-xs font-semibold text-slate-500 uppercase">Kampus/Prodi
                            </th>
                            <th class="text-left py-4 px-6 text-xs font-semibold text-slate-500 uppercase">Status Saat
                                Ini</th>
                            <th class="text-left py-4 px-6 text-xs font-semibold text-slate-500 uppercase">Pengajuan
                            </th>
                            <th class="text-left py-4 px-6 text-xs font-semibold text-slate-500 uppercase">Semester
                                Cuti</th>
                            <th class="text-left py-4 px-6 text-xs font-semibold text-slate-500 uppercase">Tgl
                                Pengajuan</th>
                            <th class="text-left py-4 px-6 text-xs font-semibold text-slate-500 uppercase">Aksi
                                Validasi</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y">
                        @forelse($pengajuan as $index => $item)
                            @php
                                $statusAkademikClass = match ($item->status_akademik ?? '') {
                                    'aktif' => 'bg-green-500/10 text-green-600',
                                    'cuti' => 'bg-yellow-500/10 text-yellow-600',
                                    'drop_out' => 'bg-red-500/10 text-red-600',
                                    'lulus' => 'bg-blue-500/10 text-blue-600',
                                    'tidak_aktif' => 'bg-gray-500/10 text-gray-600',
                                    default => 'bg-slate-500/10 text-slate-600',
                                };

                                $statusAkademikText = match ($item->status_akademik ?? '') {
                                    'aktif' => 'Aktif',
                                    'cuti' => 'Cuti',
                                    'drop_out' => 'Drop Out',
                                    'lulus' => 'Lulus',
                                    'tidak_aktif' => 'Tidak Aktif',
                                    default => $item->status_akademik ?? '-',
                                };

                                $pengajuanClass = match ($item->pengajuan_jenis ?? '') {
                                    'aktif' => 'bg-green-500/10 text-green-600',
                                    'cuti' => 'bg-yellow-500/10 text-yellow-600',
                                    'drop_out' => 'bg-red-500/10 text-red-600',
                                    'lulus' => 'bg-blue-500/10 text-blue-600',
                                    'tidak_aktif' => 'bg-gray-500/10 text-gray-600',
                                    default => 'bg-slate-500/10 text-slate-600',
                                };

                                $pengajuanText = match ($item->pengajuan_jenis ?? '') {
                                    'aktif' => 'Aktif',
                                    'cuti' => 'Cuti',
                                    'drop_out' => 'Drop Out',
                                    'lulus' => 'Lulus',
                                    'tidak_aktif' => 'Tidak Aktif',
                                    default => $item->pengajuan_jenis ?? '-',
                                };
                            @endphp
                            <tr class="hover:bg-slate-50/50 dark:hover:bg-white/5">
                                <td class="py-4 px-6">
                                    <input type="checkbox" name="pengajuan_ids[]" value="{{ $item->id }}"
                                        class="pengajuan-checkbox w-4 h-4 text-violet-600 rounded">
                                </td>
                                <td class="py-4 px-6 font-mono text-sm">{{ $pengajuan->firstItem() + $index }}</td>
                                <td class="py-4 px-6 font-mono text-sm">{{ $item->nim ?? '-' }}</td>
                                <td class="py-4 px-6 font-medium">{{ $item->nama ?? '-' }}</td>
                                <td class="py-4 px-6">
                                    <div class="text-sm">{{ $item->kampus->nama ?? '-' }}</div>
                                    <div class="text-xs text-slate-500">{{ $item->prodi->nama ?? '-' }}</div>
                                </td>
                                <td class="py-4 px-6">
                                    <span class="px-2 py-1 text-xs rounded-lg {{ $statusAkademikClass }}">
                                        {{ $statusAkademikText }}
                                    </span>
                                </td>
                                <td class="py-4 px-6">
                                    <span class="px-2 py-1 text-xs rounded-lg {{ $pengajuanClass }}">
                                        {{ $pengajuanText }}
                                    </span>
                                    @if ($item->pengajuan_jenis === 'cuti' && ($item->pengajuan_file || $item->bukti_bayar_file))
                                        <button type="button" onclick="showDetail({{ $item->id }})"
                                            class="ml-2 text-xs text-blue-600 hover:underline">
                                            Lihat File
                                        </button>
                                    @endif
                                </td>
                                <td class="py-4 px-6 text-sm">
                                    @if ($item->pengajuan_jenis === 'cuti' && $item->cuti_semester)
                                        <span class="px-2 py-1 text-xs rounded-lg bg-purple-500/10 text-purple-600">
                                            @php
                                                $cutiSemester = is_array($item->cuti_semester)
                                                    ? $item->cuti_semester
                                                    : json_decode($item->cuti_semester, true);
                                                $cutiText = is_array($cutiSemester)
                                                    ? implode(', ', $cutiSemester)
                                                    : $item->cuti_semester;
                                            @endphp
                                            Semester {{ $cutiText }}
                                        </span>
                                    @else
                                        -
                                    @endif
                                </td>
                                <td class="py-4 px-6 text-sm">
                                    {{ $item->pengajuan_at ? $item->pengajuan_at->format('d/m/Y H:i') : '-' }}
                                </td>
                                <td class="py-4 px-6">
                                    <div class="flex items-center gap-2">
                                        <button type="button"
                                            onclick="approvePengajuan({{ $item->id }}, '{{ $item->nama }}')"
                                            class="p-2 text-green-600 hover:bg-green-50 dark:hover:bg-green-900/20 rounded-lg transition"
                                            title="Setujui">
                                            <i data-lucide="check-circle" class="w-4 h-4"></i>
                                        </button>
                                        <button type="button"
                                            onclick="rejectPengajuan({{ $item->id }}, '{{ $item->nama }}')"
                                            class="p-2 text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition"
                                            title="Tolak">
                                            <i data-lucide="x-circle" class="w-4 h-4"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="10" class="py-12 text-center text-slate-500">
                                    <i data-lucide="inbox" class="w-12 h-12 mx-auto mb-3 text-slate-400"></i>
                                    <p>Tidak ada pengajuan pending</p>
                                </td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>

            <!-- Pagination -->
            @if ($pengajuan->hasPages())
                <div class="p-4 border-t">
                    {{ $pengajuan->withQueryString()->links('vendor.pagination.tailwind') }}
                </div>
            @endif
        </div>
    </div>

    <!-- Modal Detail File -->
    <div id="detailModal" class="fixed inset-0 z-50 hidden overflow-y-auto">
        <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
            <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" onclick="closeDetailModal()">
            </div>
            <div
                class="inline-block align-bottom bg-white dark:bg-[#1a1a2e] rounded-3xl text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
                <div class="p-6">
                    <div class="flex justify-between items-center mb-4">
                        <h3 class="text-lg font-bold">Detail Pengajuan</h3>
                        <button onclick="closeDetailModal()" class="text-slate-400 hover:text-slate-500">
                            <i data-lucide="x" class="w-5 h-5"></i>
                        </button>
                    </div>
                    <div id="detailModalContent" class="space-y-4">
                        <div class="text-center py-8" id="detailLoading">
                            <div
                                class="inline-block animate-spin rounded-full h-8 w-8 border-4 border-violet-500 border-t-transparent">
                            </div>
                            <p class="mt-2 text-sm text-slate-500">Memuat...</p>
                        </div>
                        <div id="detailData" class="hidden"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            lucide.createIcons();

            // Select All
            const selectAll = document.getElementById('selectAll');
            const checkboxes = document.querySelectorAll('.pengajuan-checkbox');
            const bulkActionBtn = document.getElementById('bulkActionBtn');
            const selectedCount = document.getElementById('selectedCount');

            function updateSelectedCount() {
                const checked = document.querySelectorAll('.pengajuan-checkbox:checked').length;
                selectedCount.textContent = checked + ' pengajuan dipilih';
                if (bulkActionBtn) {
                    bulkActionBtn.disabled = checked === 0;
                }
            }

            if (selectAll) {
                selectAll.addEventListener('change', function() {
                    checkboxes.forEach(cb => cb.checked = this.checked);
                    updateSelectedCount();
                });
            }

            checkboxes.forEach(cb => {
                cb.addEventListener('change', updateSelectedCount);
            });

            window.clearSelection = function() {
                checkboxes.forEach(cb => cb.checked = false);
                if (selectAll) selectAll.checked = false;
                updateSelectedCount();
            };
        });

        // ========== SHOW DETAIL MODAL ==========
        function showDetail(id) {
            const modal = document.getElementById('detailModal');
            const loading = document.getElementById('detailLoading');
            const data = document.getElementById('detailData');

            modal.classList.remove('hidden');
            loading.classList.remove('hidden');
            data.classList.add('hidden');

            fetch(`/validasi-pengajuan/${id}`)
                .then(response => response.json())
                .then(m => {
                    loading.classList.add('hidden');

                    let html = `
                        <div class="space-y-4">
                            <div class="grid grid-cols-2 gap-4">
                                <div>
                                    <p class="text-xs text-slate-500">NIM</p>
                                    <p class="font-medium">${m.nim || '-'}</p>
                                </div>
                                <div>
                                    <p class="text-xs text-slate-500">Nama</p>
                                    <p class="font-medium">${m.nama || '-'}</p>
                                </div>
                                <div>
                                    <p class="text-xs text-slate-500">Kampus</p>
                                    <p class="font-medium">${m.kampus || '-'}</p>
                                </div>
                                <div>
                                    <p class="text-xs text-slate-500">Prodi</p>
                                    <p class="font-medium">${m.prodi || '-'}</p>
                                </div>
                                <div>
                                    <p class="text-xs text-slate-500">Angkatan</p>
                                    <p class="font-medium">${m.angkatan || '-'}</p>
                                </div>
                                <div>
                                    <p class="text-xs text-slate-500">Status Saat Ini</p>
                                    <p class="font-medium">${m.status_akademik_text || '-'}</p>
                                </div>
                                <div>
                                    <p class="text-xs text-slate-500">Pengajuan Menjadi</p>
                                    <p class="font-medium">${m.pengajuan_jenis_text || '-'}</p>
                                </div>
                    `;

                    if (m.cuti_semester) {
                        html += `
                                <div>
                                    <p class="text-xs text-slate-500">Semester Cuti</p>
                                    <p class="font-medium">Semester ${m.cuti_semester}</p>
                                </div>
                        `;
                    }

                    html += `
                                <div>
                                    <p class="text-xs text-slate-500">Tanggal Pengajuan</p>
                                    <p class="font-medium">${m.pengajuan_at || '-'}</p>
                                </div>
                                <div>
                                    <p class="text-xs text-slate-500">Diajukan Oleh</p>
                                    <p class="font-medium">${m.pengajuan_by || '-'}</p>
                                </div>
                            </div>
                    `;

                    // File Pengajuan
                    if (m.pengajuan_file) {
                        html += `
                            <div class="border-t pt-3">
                                <p class="text-sm font-medium mb-2">File Pengajuan</p>
                                <a href="/validasi-pengajuan/${m.id}/download-pengajuan"
                                   class="inline-flex items-center gap-2 px-3 py-2 bg-blue-50 text-blue-600 rounded-lg hover:bg-blue-100 transition text-sm">
                                    <i data-lucide="file-text" class="w-4 h-4"></i>
                                    Download File Pengajuan
                                </a>
                            </div>
                        `;
                    }

                    // Bukti Bayar
                    if (m.bukti_bayar_file) {
                        html += `
                            <div class="border-t pt-3">
                                <p class="text-sm font-medium mb-2">Bukti Pembayaran</p>
                                <a href="/validasi-pengajuan/${m.id}/download-bukti"
                                   class="inline-flex items-center gap-2 px-3 py-2 bg-green-50 text-green-600 rounded-lg hover:bg-green-100 transition text-sm">
                                    <i data-lucide="receipt" class="w-4 h-4"></i>
                                    Download Bukti Bayar
                                </a>
                            </div>
                        `;
                    }

                    html += `</div>`;
                    data.innerHTML = html;
                    data.classList.remove('hidden');
                    lucide.createIcons();
                })
                .catch(error => {
                    console.error('Error:', error);
                    loading.classList.add('hidden');
                    data.innerHTML = '<p class="text-center text-red-500">Gagal memuat data</p>';
                    data.classList.remove('hidden');
                });
        }

        function closeDetailModal() {
            document.getElementById('detailModal').classList.add('hidden');
        }

        // ========== APPROVE INDIVIDUAL ==========
        function approvePengajuan(id, nama) {
            Swal.fire({
                title: 'Konfirmasi',
                html: `Setujui pengajuan dari <strong>${nama}</strong>?`,
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#10b981',
                cancelButtonColor: '#64748b',
                confirmButtonText: 'Ya, Setujui!',
                cancelButtonText: 'Batal'
            }).then((result) => {
                if (result.isConfirmed) {
                    fetch(`/validasi-pengajuan/${id}/approve`, {
                            method: 'POST',
                            headers: {
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                                'Content-Type': 'application/json',
                                'Accept': 'application/json'
                            }
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                Swal.fire('Berhasil!', data.message, 'success').then(() => {
                                    window.location.reload();
                                });
                            } else {
                                Swal.fire('Gagal!', data.message, 'error');
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            Swal.fire('Error!', 'Terjadi kesalahan', 'error');
                        });
                }
            });
        }

        // ========== REJECT INDIVIDUAL ==========
        function rejectPengajuan(id, nama) {
            Swal.fire({
                title: 'Konfirmasi',
                html: `Tolak pengajuan dari <strong>${nama}</strong>?`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#ef4444',
                cancelButtonColor: '#64748b',
                confirmButtonText: 'Ya, Tolak!',
                cancelButtonText: 'Batal'
            }).then((result) => {
                if (result.isConfirmed) {
                    fetch(`/validasi-pengajuan/${id}/reject`, {
                            method: 'POST',
                            headers: {
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                                'Content-Type': 'application/json',
                                'Accept': 'application/json'
                            }
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                Swal.fire('Berhasil!', data.message, 'success').then(() => {
                                    window.location.reload();
                                });
                            } else {
                                Swal.fire('Gagal!', data.message, 'error');
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            Swal.fire('Error!', 'Terjadi kesalahan', 'error');
                        });
                }
            });
        }

        // ========== BULK ACTION ==========
        let selectedIds = [];

        function bulkAction() {
            selectedIds = Array.from(document.querySelectorAll('.pengajuan-checkbox:checked')).map(cb => cb.value);
            const action = document.getElementById('bulkAction').value;

            if (selectedIds.length === 0) {
                Swal.fire('Peringatan', 'Pilih minimal 1 pengajuan', 'warning');
                return;
            }

            if (!action) {
                Swal.fire('Peringatan', 'Pilih aksi yang akan dilakukan', 'warning');
                return;
            }

            let title = action === 'approve' ? 'Setujui' : 'Tolak';
            let color = action === 'approve' ? '#10b981' : '#ef4444';
            let message = action === 'approve' ? `Setujui ${selectedIds.length} pengajuan?` :
                `Tolak ${selectedIds.length} pengajuan?`;

            Swal.fire({
                title: 'Konfirmasi',
                text: message,
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: color,
                confirmButtonText: `Ya, ${title}!`,
                cancelButtonText: 'Batal'
            }).then((result) => {
                if (result.isConfirmed) {
                    submitBulkAction(action);
                }
            });
        }

        function submitBulkAction(action) {
            fetch('{{ route('validasi-pengajuan.bulk-action') }}', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify({
                        ids: selectedIds,
                        action: action
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        Swal.fire('Berhasil!', data.message, 'success').then(() => {
                            window.location.reload();
                        });
                    } else {
                        Swal.fire('Gagal!', data.message, 'error');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    Swal.fire('Error!', 'Terjadi kesalahan', 'error');
                });
        }
    </script>
</x-app-layout>
