<x-app-layout>
    @section('page-title', $pageTitle)

    <div class="d-flex justify-content-between align-items-center mb-4 flex-wrap gap-3">
        <div>
            <h3 class="my-0 fw-bold">Manajemen Peminjaman</h3>
            <p class="text-muted mb-0">Daftar ini hanya menampilkan buku yang masih berstatus "Dipinjam".</p>
        </div>
        <div class="d-flex align-items-center gap-2">
            <form action="#" method="GET" class="d-flex m-0 p-0 bg-white border rounded p-1" onsubmit="alert('Fitur download Excel sedang disiapkan tim Backend'); return false;">
                <input type="month" name="bulan_laporan" class="form-control form-control-sm border-0 me-1" required>
                <button type="submit" class="btn btn-sm btn-success text-nowrap">
                    <i class="bi bi-file-earmark-excel-fill me-1"></i>Excel
                </button>
            </form>

            <a href="{{ route('admin.peminjaman.create') }}" class="btn btn-primary text-nowrap">
                <i class="bi bi-plus-circle-fill me-1"></i>Peminjaman Manual
            </a>
        </div>
    </div>

    <div class="card border-0 shadow-sm">
        <div class="card-body">
            <div class="table-responsive">
                <table id="peminjamanTable" class="table table-striped table-hover nowrap dt-responsive" style="width:100%">
                    <thead class="table-light">
                        <tr>
                            <th>NO</th>
                            <th>ID PEMINJAMAN</th>
                            <th>PEMINJAM (JABATAN/KELAS)</th>
                            <th>JUDUL BUKU</th>
                            <th>TGL. PINJAM</th>
                            <th>TENGGAT KEMBALI</th>
                            <th>STATUS</th>
                            <th>AKSI</th>
                        </tr>
                    </thead>
                    <tbody>
                        @php
                        $now = \Carbon\Carbon::now();
                        $counter = 1;
                        @endphp

                        @forelse ($peminjamanAktif as $transaksi)
                        @php
                        $tenggat = $transaksi['tenggat_kembali'];
                        $isTerlambat = $now->startOfDay()->isAfter($tenggat->startOfDay());
                        $isHariIni = $now->startOfDay()->isSameDay($tenggat->startOfDay());
                        $selisihHari = $now->startOfDay()->diffInDays($tenggat->startOfDay(), false);

                        $isGuru = isset($transaksi['role']) && strtolower($transaksi['role']) == 'guru';

                        if ($isTerlambat) {
                        if ($isGuru) {
                        $statusClass = 'badge rounded-pill bg-info-subtle text-info-emphasis';
                        $statusText = 'Terlambat (Bebas Denda)';
                        } else {
                        $statusClass = 'badge rounded-pill bg-danger-subtle text-danger-emphasis';
                        $statusText = 'Terlambat ' . $tenggat->startOfDay()->diffInDays($now->startOfDay()) . ' hari';
                        }
                        } elseif ($isHariIni) {
                        $statusClass = 'badge rounded-pill bg-warning-subtle text-warning-emphasis';
                        $statusText = 'Jatuh Tempo Hari Ini';
                        } else {
                        $statusClass = 'badge rounded-pill bg-success-subtle text-success-emphasis';
                        $statusText = 'Sisa ' . abs($selisihHari) . ' hari';
                        }
                        @endphp

                        <tr>
                            <td>{{ $counter++ }}</td>
                            <td>
                                <span class="badge bg-primary-subtle text-primary fw-bold">{{ $transaksi['id_peminjaman'] }}</span>
                            </td>
                            <td>
                                <div class="fw-bold">{{ $transaksi['peminjam'] }}</div>
                                <div class="small text-muted">{{ $transaksi['nomor_hp'] }}</div>
                            </td>
                            <td>
                                <ul class="mb-0 ps-3 small">
                                    @foreach ($transaksi['books'] as $buku)
                                    <li>{{ $buku['judul'] }}</li>
                                    @endforeach
                                </ul>
                            </td>
                            <td>{{ $transaksi['tanggal_pinjam']->format('d/m/Y') }}</td>
                            <td>{{ $transaksi['tenggat_kembali']->format('d/m/Y') }}</td>
                            <td>
                                <span class="{{ $statusClass }}">{{ $statusText }}</span>
                            </td>
                            <td>
                                <button class="btn btn-sm btn-outline-primary" data-bs-toggle="modal"
                                    data-bs-target="#modalPengembalian-{{ $transaksi['id_peminjaman'] }}">
                                    Proses Pengembalian
                                </button>
                            </td>
                        </tr>

                        {{-- MODAL PENGEMBALIAN --}}
                        <div class="modal fade" id="modalPengembalian-{{ $transaksi['id_peminjaman'] }}" tabindex="-1" aria-hidden="true">
                            <div class="modal-dialog modal-lg modal-dialog-centered">
                                <div class="modal-content border-0 shadow-lg rounded-3">
                                    <div class="modal-header p-4">
                                        <h5 class="modal-title fw-bold">Proses Pengembalian ({{ count($transaksi['books']) }} Buku)</h5>
                                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                    </div>
                                    <div class="modal-body p-4">
                                        <div class="alert alert-light border mb-4">
                                            <div class="d-flex justify-content-between">
                                                <span>Peminjam: <strong>{{ $transaksi['peminjam'] }}</strong></span>
                                                <span>ID: <strong>{{ $transaksi['id_peminjaman'] }}</strong></span>
                                            </div>
                                        </div>

                                        @if($isGuru)
                                        <div class="alert alert-info py-2 small mb-3">
                                            <i class="bi bi-shield-check me-1"></i> Role Guru: Bebas dari beban denda keterlambatan dan catatan denda/sanksi.
                                        </div>
                                        @endif

                                        <h6 class="fw-bold mb-3">Daftar Buku yang Dikembalikan:</h6>
                                        @foreach ($transaksi['books'] as $buku)
                                        <div class="card mb-3 border bg-light book-return-item" data-book-id="{{ $buku['id'] }}">
                                            <div class="card-body p-3">
                                                <h6 class="fw-bold text-primary mb-2">{{ $buku['judul'] }}</h6>
                                                <div class="row">
                                                    @if(!$isGuru)
                                                    <div class="col-md-6">
                                                        <label class="form-label small text-muted mb-1">Kondisi Buku</label>
                                                        <div class="d-flex gap-3">
                                                            <div class="form-check">
                                                                <input class="form-check-input radio-kondisi" type="radio" name="kondisi_{{ $buku['id'] }}_{{ $transaksi['id_peminjaman'] }}" value="baik" checked>
                                                                <label class="form-check-label small">Baik</label>
                                                            </div>
                                                            <div class="form-check">
                                                                <input class="form-check-input radio-kondisi" type="radio" name="kondisi_{{ $buku['id'] }}_{{ $transaksi['id_peminjaman'] }}" value="rusak">
                                                                <label class="form-check-label small">Rusak/Hilang</label>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-6 denda-rusak-input-wrapper d-none">
                                                        <label class="form-label small text-muted mb-1">Denda Kerusakan</label>
                                                        <input type="number" class="form-control form-control-sm denda-rusak-input" placeholder="0">
                                                    </div>
                                                    <div class="col-12">
                                                        <label class="form-label small text-muted mb-1"><i class="bi bi-pencil-square me-1"></i>Catatan Petugas</label>
                                                        <textarea class="form-control form-control-sm" rows="2" placeholder="Contoh: Ada coretan di halaman 10, Cover sedikit terlipat..."></textarea>
                                                    </div>
                                                    @else
                                                    <div class="col-12">
                                                        <span class="badge bg-success-subtle text-success-emphasis border"><i class="bi bi-check-circle me-1"></i> Buku dikembalikan oleh Guru</span>
                                                    </div>
                                                    @endif
                                                </div>
                                            </div>
                                        </div>
                                        @endforeach

                                        <hr>

                                        @if(!$isGuru)
                                        <div class="d-flex justify-content-between align-items-center mb-3">
                                            <span>Denda Keterlambatan ({{ $statusText }})</span>
                                            @php
                                            $isGuru = ($transaksi['role'] ?? '') === 'guru';
                                            $dendaTelat = 0;
                                            if ($isTerlambat && !$isGuru) {
                                            if ($isTerlambat && !$isGuru) {
                                            $hari = $tenggat->startOfDay()->diffInDays($now->startOfDay());
                                            $dendaTelat = $hari * 1000;
                                            }
                                            @endphp
                                            {{-- Data Attribute untuk JS --}}
                                            @if($isGuru && $isTerlambat)
                                            <strong class="text-success denda-keterlambatan-display"
                                                data-denda-keterlambatan="0">
                                                Bebas Denda
                                            </strong>
                                            @else
                                            <strong class="text-danger denda-keterlambatan-display"
                                                data-denda-keterlambatan="{{ $dendaTelat }}">
                                                Rp {{ number_format($dendaTelat, 0, ',', '.') }}
                                            </strong>
                                            @endif
                                        </div>

                                        <div class="d-flex justify-content-between align-items-center mb-3 bg-danger bg-opacity-10 p-2 rounded">
                                            <span class="fw-bold text-danger">TOTAL YANG HARUS DIBAYAR</span>
                                            <strong class="text-danger fs-5 total-denda-display">Rp {{ number_format($dendaTelat, 0, ',', '.') }}</strong>
                                        </div>
                                        @endif

                                        <div class="form-check form-switch mb-0 mt-3">
                                            <input class="form-check-input" type="checkbox" role="switch" checked id="waStrukToggle-{{ $transaksi['id_peminjaman'] }}">
                                            <label class="form-check-label small" for="waStrukToggle-{{ $transaksi['id_peminjaman'] }}">
                                                Kirim <strong>Bukti Pengembalian</strong> ke WhatsApp
                                            </label>
                                        </div>
                                        <div class="form-check form-switch mb-0">
                                            <input class="form-check-input email-toggle" type="checkbox" role="switch" checked id="emailStrukToggle-{{ $transaksi['id_peminjaman'] }}">
                                            <label class="form-check-label small" for="emailStrukToggle-{{ $transaksi['id_peminjaman'] }}">
                                                Kirim <strong>Bukti Pengembalian</strong> ke Email
                                            </label>
                                        </div>
                                    </div>
                                    <div class="modal-footer p-3 bg-light">
                                        <button type="button" class="btn btn-outline-secondary"
                                            data-bs-dismiss="modal">Batal</button>
                                        <button type="button" class="btn btn-primary btn-konfirmasi-kembali"
                                            data-nama-peminjam="{{ $transaksi['peminjam'] }}"
                                            data-nomor-hp="{{ $transaksi['nomor_hp'] }}"
                                            data-user-id="{{ $transaksi['user_id'] }}">
                                            Konfirmasi & Selesai
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        @empty
                        <tr>
                            <td colspan="8" class="text-center py-5">Tidak ada data.</td>
                        </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    @push('scripts')
    <script>
        $(document).ready(function() {
            $('#peminjamanTable').DataTable({
                pageLength: 10,
                order: [
                    [0, 'asc']
                ]
            });
        });

        document.addEventListener('DOMContentLoaded', function() {
            function formatRupiah(angka) {
                return new Intl.NumberFormat('id-ID', {
                    style: 'currency',
                    currency: 'IDR',
                    minimumFractionDigits: 0
                }).format(angka).replace(/\s/g, '');
            }

            function hitungTotalDenda(modal) {
                const dendaKeterlambatanEl = modal.querySelector('.denda-keterlambatan-display');
                const totalDendaEl = modal.querySelector('.total-denda-display');
                if (!dendaKeterlambatanEl || !totalDendaEl) return;

                let dendaKeterlambatan = parseInt(dendaKeterlambatanEl.dataset.dendaKeterlambatan) || 0;
                let totalDendaRusak = 0;

                modal.querySelectorAll('.denda-rusak-input').forEach(input => {
                    if (!input.closest('.denda-rusak-input-wrapper').classList.contains('d-none')) {
                        totalDendaRusak += parseInt(input.value) || 0;
                    }
                });
                totalDendaEl.textContent = formatRupiah(dendaKeterlambatan + totalDendaRusak);
            }

            document.querySelectorAll('.radio-kondisi').forEach(radio => {
                radio.addEventListener('change', function() {
                    const cardBody = this.closest('.card-body');
                    const dendaRusakWrapper = cardBody.querySelector('.denda-rusak-input-wrapper');
                    const dendaRusakInput = cardBody.querySelector('.denda-rusak-input');
                    if (this.value === 'rusak') {
                        dendaRusakWrapper.classList.remove('d-none');
                    } else {
                        dendaRusakWrapper.classList.add('d-none');
                        dendaRusakInput.value = 0;
                    }
                    hitungTotalDenda(this.closest('.modal'));
                });
            });

            document.querySelectorAll('.denda-rusak-input').forEach(input => {
                input.addEventListener('input', function() {
                    hitungTotalDenda(this.closest('.modal'));
                });
            });
        });

        $(document).on('click', '.btn-konfirmasi-kembali', function() {
            const nama = $(this).data('nama-peminjam');
            const hp = $(this).data('nomor-hp');
            const modalEl = $(this).closest('.modal');
            const modalInstance = bootstrap.Modal.getInstance(modalEl[0]);
            const isEmailChecked = modalEl.find('.email-toggle').is(':checked');
            const isWaChecked = modalEl.find('input[role="switch"][id^="waStrukToggle"]').is(':checked');

            modalInstance.hide();
            modernSwal.fire({
                title: 'Selesaikan Transaksi?',
                text: `Buku dari ${nama} akan ditandai sudah kembali.`,
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: 'Ya, Selesaikan',
                cancelButtonText: 'Batal'
            }).then((result) => {
                if (result.isConfirmed) {
                    modernSwal.fire({
                        title: 'Menyimpan Data...',
                        timer: 800,
                        timerProgressBar: true,
                        didOpen: () => Swal.showLoading()
                    }).then(() => {
                        // Prepare Request Data
                        const returnsData = [];
                        const booksList = [];
                        const dendaOverdueTotal = parseInt(modalEl.find('.denda-keterlambatan-display').data('denda-keterlambatan'));
                        const dendaOverduePerBook = dendaOverdueTotal / modalEl.find('.book-return-item').length;

                        let totalDendaRusak = 0;
                        modalEl.find('.book-return-item').each(function() {
                            const bookId = $(this).data('book-id');
                            const judul = $(this).find('h6').text();
                            const condition = $(this).find('.radio-kondisi:checked').val();
                            const fineDamage = parseInt($(this).find('.denda-rusak-input').val()) || 0;
                            const notes = $(this).find('textarea').val();

                            totalDendaRusak += fineDamage;
                            booksList.push(judul);
                            returnsData.push({
                                book_id: bookId,
                                condition: condition,
                                fine_damage: fineDamage,
                                fine_overdue: Math.round(dendaOverduePerBook),
                                notes: notes
                            });
                        });

                        const userId = modalEl.find('.btn-konfirmasi-kembali').data('user-id');
                        const totalDenda = dendaOverdueTotal + totalDendaRusak;

                        // Construct WA Message
                        let waLink = null;
                        if (isWaChecked && hp && hp !== '-') {
                            let phone = hp;
                            if (phone.startsWith('0')) phone = '62' + phone.substring(1);

                            let message = `*BUKTI PENGEMBALIAN BUKU*\n\n`;
                            message += `Halo ${nama},\n`;
                            message += `Terima kasih telah mengembalikan buku:\n`;
                            booksList.forEach(b => message += `- ${b}\n`);
                            message += `\n*Status:* Berhasil Dikembalikan\n`;
                            if (totalDenda > 0) {
                                message += `*Total Denda:* Rp ${new Intl.NumberFormat('id-ID').format(totalDenda)}\n`;
                            } else {
                                message += `*Denda:* Bebas Denda\n`;
                            }
                            message += `\n_Simpan pesan ini sebagai bukti pengembalian._`;

                            waLink = `https://wa.me/${phone}?text=${encodeURIComponent(message)}`;
                        }

                        // Loading Kirim Email flow
                        if (isEmailChecked) {
                            const dummyEmail = nama.replace(/\s+/g, '.').toLowerCase() + '@sekolah.sch.id';
                            modernSwal.fire({
                                title: 'Mengirim Email...',
                                html: `Mengirim nota ke: <b>${dummyEmail}</b>`,
                                timer: 2000,
                                timerProgressBar: true,
                                didOpen: () => Swal.showLoading()
                            }).then(() => {
                                finishTransaction(returnsData, userId, waLink);
                            });
                        } else {
                            finishTransaction(returnsData, userId, waLink);
                        }
                    });
                } else {
                    modalInstance.show();
                }
            });

            function finishTransaction(returnsData, userId, waLink) {
                $.ajax({
                    url: '{{ route('
                    admin.peminjaman.kembali ') }}',
                    method: 'POST',
                    data: {
                        _token: '{{ csrf_token() }}',
                        user_id: userId,
                        returns: returnsData
                    },
                    success: function(response) {
                        if (response.status === 'success') {
                            if (waLink) {
                                window.open(waLink, '_blank');
                            }

                            Toast.fire({
                                icon: 'success',
                                title: 'Berhasil',
                                text: 'Buku berhasil dikembalikan.'
                            });
                            setTimeout(() => location.reload(), 1500);
                        } else {
                            modernSwal.fire('Gagal', response.message, 'error');
                        }
                    },
                    error: function(xhr) {
                        modernSwal.fire('Gagal', 'Terjadi kesalahan saat memproses data.', 'error');
                    }
                });
            }
        });
    </script>
    @endpush
</x-app-layout>