<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">
                        Laporan Alokasi Herregistrasi
                    </span>
                </h1>
                <p class="text-slate-500 dark:text-slate-400 text-sm pl-1">
                    <i data-lucide="file-text" class="w-4 h-4 inline mr-2"></i>
                    Analisis herregistrasi (angsuran pertama semester 1 + biaya tetap) dan perhitungan bagi hasil
                </p>
            </div>

            <div class="flex items-center gap-3">
                <button type="button" id="cetakSelectedBtn"
                    class="px-4 py-2.5 bg-red-500 hover:bg-red-600 text-white rounded-xl text-sm font-medium transition-all flex items-center gap-2">
                    <i data-lucide="file-text" class="w-4 h-4"></i>
                    Cetak PDF
                </button>
            </div>
        </div>

        <!-- Filter Section -->
        <div
            class="bg-white dark:bg-[#1a1a2e] rounded-2xl border border-slate-200 dark:border-white/5 shadow-sm p-6 mb-8">
            <form method="GET" action="{{ route('laporan.alokasi-herregistrasi') }}" class="space-y-4"
                id="filterForm">
                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Kampus</label>
                        <select name="kampus_id"
                            class="w-full px-4 py-2 bg-white dark:bg-gray-800 border border-slate-200 dark:border-gray-700 rounded-xl"
                            onchange="this.form.submit()">
                            <option value="">Semua Kampus</option>
                            @foreach ($kampusList as $kampus)
                                <option value="{{ $kampus->id }}" {{ $kampusId == $kampus->id ? 'selected' : '' }}>
                                    {{ $kampus->nama }}</option>
                            @endforeach
                        </select>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Program
                            Studi</label>
                        <select name="prodi_id"
                            class="w-full px-4 py-2 bg-white dark:bg-gray-800 border border-slate-200 dark:border-gray-700 rounded-xl"
                            onchange="this.form.submit()">
                            <option value="">Semua Prodi</option>
                            @foreach ($prodiOptions as $prodi)
                                <option value="{{ $prodi->id }}" {{ $prodiId == $prodi->id ? 'selected' : '' }}>
                                    {{ $prodi->nama }}</option>
                            @endforeach
                        </select>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Tahun
                            Ajaran</label>
                        <select name="tahun_ajaran"
                            class="w-full px-4 py-2 bg-white dark:bg-gray-800 border border-slate-200 dark:border-gray-700 rounded-xl"
                            onchange="this.form.submit()">
                            <option value="">Semua Tahun</option>
                            @foreach ($tahunAjaranOptions as $tahun)
                                <option value="{{ $tahun }}" {{ $tahunAjaran == $tahun ? 'selected' : '' }}>
                                    {{ $tahun }}</option>
                            @endforeach
                        </select>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Tanggal
                            Mulai</label>
                        <input type="date" name="start_date" value="{{ $startDate }}"
                            class="w-full px-4 py-2 bg-white dark:bg-gray-800 border border-slate-200 dark:border-gray-700 rounded-xl">
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Tanggal
                            Selesai</label>
                        <input type="date" name="end_date" value="{{ $endDate }}"
                            class="w-full px-4 py-2 bg-white dark:bg-gray-800 border border-slate-200 dark:border-gray-700 rounded-xl">
                    </div>
                </div>
                <div class="flex gap-2">
                    <button type="submit"
                        class="px-4 py-2 bg-gradient-to-r from-violet-600 to-indigo-700 text-white rounded-xl text-sm font-medium flex items-center gap-2">
                        <i data-lucide="search" class="w-4 h-4"></i> Filter
                    </button>
                    <a href="{{ route('laporan.alokasi-herregistrasi') }}"
                        class="px-4 py-2 bg-slate-500 text-white rounded-xl text-sm font-medium flex items-center gap-2">
                        <i data-lucide="refresh-cw" class="w-4 h-4"></i> Reset
                    </a>
                </div>
            </form>
        </div>

        <!-- Statistik Cards -->
        <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
            <div class="bg-white dark:bg-[#1a1a2e] rounded-2xl border border-slate-200 dark:border-white/5 p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm text-slate-500 dark:text-slate-400">Total Herregistrasi</p>
                        <p class="text-3xl font-bold text-gray-900 dark:text-white">{{ $mahasiswas->total() }}</p>
                    </div>
                    <div
                        class="w-12 h-12 bg-violet-100 dark:bg-violet-900/30 rounded-xl flex items-center justify-center">
                        <i data-lucide="users" class="w-6 h-6 text-violet-600"></i>
                    </div>
                </div>
            </div>

            <div class="bg-white dark:bg-[#1a1a2e] rounded-2xl border border-slate-200 dark:border-white/5 p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm text-slate-500 dark:text-slate-400">Total Biaya Herregistrasi</p>
                        <p class="text-2xl font-bold text-gray-900 dark:text-white">Rp
                            {{ number_format($totalBiayaHerregistrasi, 0, ',', '.') }}</p>
                    </div>
                    <div
                        class="w-12 h-12 bg-emerald-100 dark:bg-emerald-900/30 rounded-xl flex items-center justify-center">
                        <i data-lucide="wallet" class="w-6 h-6 text-emerald-600"></i>
                    </div>
                </div>
            </div>

            <div class="bg-white dark:bg-[#1a1a2e] rounded-2xl border border-slate-200 dark:border-white/5 p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm text-slate-500 dark:text-slate-400">Bagi Hasil Kampus</p>
                        <p class="text-2xl font-bold text-violet-600">Rp
                            {{ number_format($totalBagiHasilKampus + ($totalSemuaBagiHasilTetapKampus ?? 0), 0, ',', '.') }}
                        </p>
                    </div>
                    <div
                        class="w-12 h-12 bg-violet-100 dark:bg-violet-900/30 rounded-xl flex items-center justify-center">
                        <i data-lucide="building-2" class="w-6 h-6 text-violet-600"></i>
                    </div>
                </div>
            </div>

            <div class="bg-white dark:bg-[#1a1a2e] rounded-2xl border border-slate-200 dark:border-white/5 p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm text-slate-500 dark:text-slate-400">Bagi Hasil K2</p>
                        <p class="text-2xl font-bold text-indigo-600">Rp
                            {{ number_format($totalBagiHasilK2 + ($totalSemuaBagiHasilTetapK2 ?? 0), 0, ',', '.') }}
                        </p>
                    </div>
                    <div
                        class="w-12 h-12 bg-indigo-100 dark:bg-indigo-900/30 rounded-xl flex items-center justify-center">
                        <i data-lucide="users" class="w-6 h-6 text-indigo-600"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Ringkasan per Kampus -->
        <div
            class="bg-white dark:bg-[#1a1a2e] rounded-2xl border border-slate-200 dark:border-white/5 shadow-sm overflow-hidden mb-8">
            <div class="p-6 border-b border-slate-200 dark:border-white/10">
                <h3 class="text-lg font-bold text-gray-900 dark:text-white flex items-center gap-2">
                    <i data-lucide="building-2" class="w-5 h-5 text-violet-500"></i>
                    Ringkasan Herregistrasi per Kampus
                </h3>
            </div>
            <div class="overflow-x-auto">
                <table class="w-full">
                    <thead>
                        <tr class="bg-slate-50 dark:bg-white/5 border-b border-slate-200 dark:border-white/10">
                            <th class="text-left py-4 px-4 text-xs font-semibold text-slate-500 uppercase">No</th>
                            <th class="text-left py-4 px-4 text-xs font-semibold text-slate-500 uppercase">Kampus</th>
                            <th class="text-center py-4 px-4 text-xs font-semibold text-slate-500 uppercase">Jml</th>
                            <th class="text-center py-4 px-4 text-xs font-semibold text-slate-500 uppercase">Total
                                Herregistrasi</th>
                            @php
                                $firstItem = reset($ringkasanData);
                                if ($firstItem && isset($firstItem['biaya_tetap'])) {
                                    foreach ($firstItem['biaya_tetap'] as $key => $biaya) {
                                        echo '<th class="text-center py-4 px-4 text-xs font-semibold text-slate-500 uppercase">Total ' .
                                            $biaya['nama'] .
                                            '</th>';
                                    }
                                }
                            @endphp
                            <th class="text-center py-4 px-4 text-xs font-semibold text-slate-500 uppercase">Total Biaya
                            </th>
                            <th class="text-center py-4 px-4 text-xs font-semibold text-slate-500 uppercase">Bagi Hasil
                                Kampus</th>
                            <th class="text-center py-4 px-4 text-xs font-semibold text-slate-500 uppercase">Bagi Hasil
                                K2</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y">
                        @php $no = 1; @endphp
                        @foreach ($ringkasanData as $item)
                            <tr class="hover:bg-slate-50">
                                <td class="py-3 px-4">{{ $no++ }}</td>
                                <td class="py-3 px-4">
                                    <div class="font-medium">{{ $item['kampus']->nama }}</div>
                                    <div class="text-xs text-slate-500">{{ $item['kampus']->singkatan ?? '' }}</div>
                                </td>
                                <td class="py-3 px-4 text-center">{{ number_format($item['jumlah_pendaftar']) }}</td>
                                <td class="py-3 px-4 text-center">Rp
                                    {{ number_format($item['biaya_herregistrasi']['total'], 0, ',', '.') }}</td>
                                @foreach ($item['biaya_tetap'] as $biaya)
                                    <td class="py-3 px-4 text-center">Rp
                                        {{ number_format($biaya['total'], 0, ',', '.') }}</td>
                                @endforeach
                                <td class="py-3 px-4 text-center font-bold">Rp
                                    {{ number_format($item['total_biaya'], 0, ',', '.') }}</td>
                                <td class="py-3 px-4 text-center text-violet-600">Rp
                                    {{ number_format($item['total_bagi_hasil_kampus'], 0, ',', '.') }}</td>
                                <td class="py-3 px-4 text-center text-indigo-600">Rp
                                    {{ number_format($item['total_bagi_hasil_k2'], 0, ',', '.') }}</td>
                            </tr>
                            @if (count($item['detail_jenjang']) > 0)
                                <tr class="bg-slate-50/50">
                                    <td colspan="20" class="py-2 px-4 pl-12 text-xs text-slate-500">
                                        <span class="font-medium">Detail per Jenjang:</span>
                                        @foreach ($item['detail_jenjang'] as $jenjang => $detail)
                                            <span class="ml-3">{{ $jenjang }}: {{ $detail['jumlah'] }} mhs (Rp
                                                {{ number_format($detail['total_biaya'], 0, ',', '.') }})</span>
                                        @endforeach
                                    </td>
                                </tr>
                            @endif
                        @endforeach
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Tabel Detail Mahasiswa dengan Checkbox -->
<div class="bg-white dark:bg-[#1a1a2e] rounded-2xl border border-slate-200 dark:border-white/5 shadow-sm overflow-hidden">
    <div class="p-6 border-b border-slate-200 dark:border-white/10 flex justify-between items-center">
        <h3 class="text-lg font-bold text-gray-900 dark:text-white flex items-center gap-2">
            <i data-lucide="list" class="w-5 h-5 text-violet-500"></i>
            Detail Herregistrasi
        </h3>
        <div class="flex items-center gap-4">
            <label class="flex items-center gap-2 text-sm text-slate-600 dark:text-slate-400">
                <input type="checkbox" id="selectAll" class="rounded border-slate-300 text-violet-600 focus:ring-violet-500">
                Pilih Semua
            </label>
            <span class="text-sm text-slate-500" id="selectedCount">0 dipilih</span>
        </div>
    </div>
    <form id="cetakForm" action="{{ route('laporan.alokasi-herregistrasi.preview') }}" method="POST" target="_blank">
        @csrf
        <input type="hidden" name="kampus_id" value="{{ $kampusId }}">
        <input type="hidden" name="prodi_id" value="{{ $prodiId }}">
        <input type="hidden" name="tahun_ajaran" value="{{ $tahunAjaran }}">
        <input type="hidden" name="start_date" value="{{ $startDate }}">
        <input type="hidden" name="end_date" value="{{ $endDate }}">

        <div class="overflow-x-auto">
            <table class="w-full">
                <thead>
                    <tr class="bg-slate-50 dark:bg-white/5 border-b border-slate-200 dark:border-white/10">
                        <th class="text-center py-4 px-2 text-xs font-semibold text-slate-500 uppercase w-10">
                            <input type="checkbox" id="selectAllTable" class="rounded border-slate-300 text-violet-600 focus:ring-violet-500">
                        </th>
                        <th class="text-left py-4 px-4 text-xs font-semibold text-slate-500 uppercase">No</th>
                        <th class="text-left py-4 px-4 text-xs font-semibold text-slate-500 uppercase">NIM</th>
                        <th class="text-left py-4 px-4 text-xs font-semibold text-slate-500 uppercase">Nama</th>
                        <th class="text-left py-4 px-4 text-xs font-semibold text-slate-500 uppercase">Kampus</th>
                        <th class="text-left py-4 px-4 text-xs font-semibold text-slate-500 uppercase">Prodi</th>
                        <th class="text-left py-4 px-4 text-xs font-semibold text-slate-500 uppercase">Jenjang</th>
                        <th class="text-left py-4 px-4 text-xs font-semibold text-slate-500 uppercase">Tahun Ajaran</th>
                        @if($mahasiswas->contains(fn($m) => ($m->spb1->dibayar ?? 0) > 0))
                        <th class="text-center py-4 px-4 text-xs font-semibold text-slate-500 uppercase">SPB_1</th>
                        @endif
                        @if($mahasiswas->contains(fn($m) => ($m->spp1->dibayar ?? 0) > 0))
                        <th class="text-center py-4 px-4 text-xs font-semibold text-slate-500 uppercase">SPP1_1</th>
                        @endif
                        @if($mahasiswas->contains(fn($m) => ($m->ukt1->dibayar ?? 0) > 0))
                        <th class="text-center py-4 px-4 text-xs font-semibold text-slate-500 uppercase">UKT1_1</th>
                        @endif
                        @php
                            // Kumpulkan semua jenis biaya tetap yang ada dari semua mahasiswa
                            $allBiayaTetap = [];
                            foreach ($mahasiswas as $mhs) {
                                $biayaTetapItems = $mhs->biaya_tetap_list ?? [];
                                foreach ($biayaTetapItems as $nama => $nominal) {
                                    if (!in_array($nama, $allBiayaTetap)) {
                                        $allBiayaTetap[] = $nama;
                                    }
                                }
                            }
                            sort($allBiayaTetap);
                        @endphp
                        @foreach ($allBiayaTetap as $biayaTetap)
                            <th class="text-center py-4 px-4 text-xs font-semibold text-slate-500 uppercase">{{ $biayaTetap }}</th>
                        @endforeach
                        <th class="text-center py-4 px-4 text-xs font-semibold text-slate-500 uppercase">Total</th>
                        <th class="text-left py-4 px-4 text-xs font-semibold text-slate-500 uppercase">Tgl Daftar</th>
                    </tr>
                </thead>
                <tbody class="divide-y">
                    @forelse($mahasiswas as $index => $mhs)
                    <tr class="hover:bg-slate-50">
                        <td class="text-center py-3 px-2">
                            <input type="checkbox" name="selected_ids[]" value="{{ $mhs->id }}" class="row-checkbox rounded border-slate-300 text-violet-600 focus:ring-violet-500">
                        </td>
                        <td class="py-3 px-4">{{ $mahasiswas->firstItem() + $index }}</td>
                        <td class="py-3 px-4 font-medium">{{ $mhs->nim ?? '-' }}</td>
                        <td class="py-3 px-4">{{ $mhs->nama ?? '-' }}</td>
                        <td class="py-3 px-4">{{ $mhs->kampus->nama ?? '-' }}</td>
                        <td class="py-3 px-4">{{ $mhs->prodi->nama ?? '-' }}</td>
                        <td class="py-3 px-4">
                            <span class="px-2 py-1 text-xs rounded-full bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-400">
                                {{ $mhs->prodi->jenjang ?? '-' }}
                            </span>
                        </td>
                        <td class="py-3 px-4">{{ $mhs->tahun_ajaran ?? '-' }}</td>
                        @if($mahasiswas->contains(fn($m) => ($m->spb1->dibayar ?? 0) > 0))
                        <td class="py-3 px-4 text-center">
                            @if(($mhs->spb1->dibayar ?? 0) > 0)
                                Rp {{ number_format($mhs->spb1->dibayar ?? 0, 0, ',', '.') }}
                            @else
                                -
                            @endif
                        </td>
                        @endif
                        @if($mahasiswas->contains(fn($m) => ($m->spp1->dibayar ?? 0) > 0))
                        <td class="py-3 px-4 text-center">
                            @if(($mhs->spp1->dibayar ?? 0) > 0)
                                Rp {{ number_format($mhs->spp1->dibayar ?? 0, 0, ',', '.') }}
                            @else
                                -
                            @endif
                        </td>
                        @endif
                        @if($mahasiswas->contains(fn($m) => ($m->ukt1->dibayar ?? 0) > 0))
                        <td class="py-3 px-4 text-center">
                            @if(($mhs->ukt1->dibayar ?? 0) > 0)
                                Rp {{ number_format($mhs->ukt1->dibayar ?? 0, 0, ',', '.') }}
                            @else
                                -
                            @endif
                        </td>
                        @endif
                        @php
                            $biayaTetapItems = $mhs->biaya_tetap_list ?? [];
                        @endphp
                        @foreach ($allBiayaTetap as $biayaTetap)
                            <td class="py-3 px-4 text-center">
                                @if (isset($biayaTetapItems[$biayaTetap]) && $biayaTetapItems[$biayaTetap] > 0)
                                    Rp {{ number_format($biayaTetapItems[$biayaTetap], 0, ',', '.') }}
                                @else
                                    -
                                @endif
                            </td>
                        @endforeach
                        <td class="py-3 px-4 text-center font-bold text-violet-600">Rp {{ number_format($mhs->total_keseluruhan ?? 0, 0, ',', '.') }}</td>
                        <td class="py-3 px-4">{{ $mhs->created_at ? $mhs->created_at->format('d/m/Y') : '-' }}</td>
                    </tr>
                    @empty
                    <tr>
                        <td colspan="20" class="py-12 text-center text-slate-500">
                            <i data-lucide="inbox" class="w-12 h-12 mx-auto mb-3 opacity-50"></i>
                            <p>Tidak ada data herregistrasi</p>
                        </td>
                    </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
        <input type="hidden" name="selected_ids" id="selectedIdsInput">
    </form>
    <div class="p-4 border-t border-slate-200 dark:border-white/10 flex justify-between items-center">
        <div>
            {{ $mahasiswas->appends(request()->query())->links() }}
        </div>
        <button type="button" id="cetakSelectedBtnFooter"
            class="px-4 py-2 bg-red-500 hover:bg-red-600 text-white rounded-xl text-sm font-medium transition-all flex items-center gap-2">
            <i data-lucide="file-text" class="w-4 h-4"></i>
            Cetak PDF ({{ count($mahasiswas) }} Mahasiswa)
        </button>
    </div>
</div>

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

                const selectAllTable = document.getElementById('selectAllTable');
                const rowCheckboxes = document.querySelectorAll('.row-checkbox');
                const selectedCountSpan = document.getElementById('selectedCount');
                const selectedIdsInput = document.getElementById('selectedIdsInput');
                const cetakForm = document.getElementById('cetakForm');

                function updateSelectedCount() {
                    const checked = document.querySelectorAll('.row-checkbox:checked');
                    const count = checked.length;
                    if (selectedCountSpan) {
                        selectedCountSpan.textContent = count + ' dipilih';
                    }
                    const selectedIds = Array.from(checked).map(cb => cb.value);
                    selectedIdsInput.value = selectedIds.join(',');

                    const cetakBtn = document.getElementById('cetakSelectedBtnFooter');
                    if (cetakBtn) {
                        if (count > 0) {
                            cetakBtn.innerHTML = '<i data-lucide="file-text" class="w-4 h-4"></i> Cetak PDF (' + count +
                                ' Mahasiswa)';
                        } else {
                            cetakBtn.innerHTML =
                                '<i data-lucide="file-text" class="w-4 h-4"></i> Cetak PDF (Semua Mahasiswa)';
                        }
                        lucide.createIcons();
                    }
                }

                if (selectAllTable) {
                    selectAllTable.addEventListener('change', function() {
                        rowCheckboxes.forEach(cb => {
                            cb.checked = selectAllTable.checked;
                        });
                        updateSelectedCount();
                    });
                }

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

                updateSelectedCount();

                function cetakPDF() {
                    const checked = document.querySelectorAll('.row-checkbox:checked');
                    const selectedIds = Array.from(checked).map(cb => cb.value);

                    if (selectedIds.length === 0) {
                        const allIds = Array.from(rowCheckboxes).map(cb => cb.value);
                        selectedIdsInput.value = allIds.join(',');
                    } else {
                        selectedIdsInput.value = selectedIds.join(',');
                    }

                    cetakForm.submit();
                }

                const cetakBtn = document.getElementById('cetakSelectedBtnFooter');
                if (cetakBtn) {
                    cetakBtn.addEventListener('click', cetakPDF);
                }

                const cetakBtnTop = document.getElementById('cetakSelectedBtn');
                if (cetakBtnTop) {
                    cetakBtnTop.addEventListener('click', cetakPDF);
                }
            });
        </script>
</x-app-layout>
