@section('page-title', $pageTitle)
<x-app-layout>
    <div class="card border-0 shadow-sm">
        <div class="card-header bg-white py-3">
            <h5 class="mb-0 fw-bold">{{ $pageTitle }}</h5>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table id="riwayatOfflineTable" class="table table-striped dt-responsive nowrap" style="width:100%">
                    <thead>
                        <tr>
                            <th>NO</th>
                            <th>ID PEMINJAMAN</th>
                            <th>KODE BUKU</th>
                            <th>JUDUL BUKU</th>
                            <th>TANGGAL PINJAM</th>
                            <th>TANGGAL KEMBALI</th>
                            <th>STATUS</th>
                            <th>AKSI</th>
                        </tr>
                    </thead>
                    <tbody>
                        @php $counter = 1; @endphp
                        @if (count($riwayatOffline) > 0)
                            @foreach ($riwayatOffline as $transaksi)
                                @foreach ($transaksi['books'] as $buku)
                                    @php
                                        try {
                                            $tglKembali = \Carbon\Carbon::createFromFormat(
                                                'd/m/Y',
                                                $transaksi['tanggal_kembali'],
                                            )->startOfDay();
                                        } catch (\Exception $e) {
                                            $tglKembali = \Carbon\Carbon::parse(
                                                $transaksi['tanggal_kembali'],
                                            )->startOfDay();
                                        }

                                        $today = now()->startOfDay();
                                        $isTelat = $today->gt($tglKembali) && $transaksi['status'] == 'Dipinjam';

                                        $hariTelat = 0;
                                        $denda = 0;

                                        if ($isTelat) {
                                            $hariTelat = $tglKembali->diffInDays($today);
                                            $denda = $hariTelat * 1000;
                                        }
                                    @endphp

                                    <tr>
                                        <td>{{ $counter++ }}</td>
                                        <td>{{ $transaksi['id_peminjaman'] }}</td>
                                        <td>{{ $buku['kode_buku'] }}</td>
                                        <td>{{ $buku['judul'] }}</td>
                                        <td>{{ $transaksi['tanggal_pinjam'] }}</td>
                                        <td>{{ $transaksi['tanggal_kembali'] }}</td>
                                        <td>
                                            @if ($transaksi['status'] == 'Dikembalikan')
                                                <span
                                                    class="badge rounded-pill bg-success-subtle text-success-emphasis">Dikembalikan</span>
                                            @elseif($isTelat)
                                                {{-- LOGIC BADGE STATUS DI TABEL --}}
                                                @if (Auth::user()->role == 'guru')
                                                    <span
                                                        class="badge rounded-pill bg-success-subtle text-success-emphasis">Bebas
                                                        Denda</span>
                                                @else
                                                    <span
                                                        class="badge rounded-pill bg-danger text-white">Terlambat</span>
                                                @endif
                                            @else
                                                <span
                                                    class="badge rounded-pill bg-warning-subtle text-warning-emphasis">Dipinjam</span>
                                            @endif
                                        </td>
                                        <td>
                                            <button class="btn btn-primary btn-sm text-white" data-bs-toggle="modal"
                                                data-bs-target="#detailModal" data-transaksi-id="{{ $transaksi['id'] }}"
                                                data-buku-id="{{ $buku['id'] }}"
                                                data-is-telat="{{ $isTelat ? 'true' : 'false' }}"
                                                data-hari-telat="{{ $hariTelat }}"
                                                data-denda="{{ number_format($denda, 0, ',', '.') }}">
                                                Detail
                                            </button>
                                        </td>
                                    </tr>
                                @endforeach
                            @endforeach
                        @endif
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    {{-- MODAL DETAIL --}}
    <div class="modal fade" id="detailModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg modal-dialog-centered">
            <div class="modal-content border-0 shadow-lg">
                <div class="modal-header bg-light">
                    <h5 class="modal-title fw-bold"><i class="bi bi-book-half me-2 text-primary"></i>Detail Riwayat</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body p-4">
                    <div id="modal-content-placeholder" class="text-center">Loading...</div>
                </div>
            </div>
        </div>
    </div>

    @push('scripts')
        <script>
            const riwayatOfflineData = @json($riwayatOffline);

            const currentUserRole = "{{ Auth::user()->role }}";

            $(document).ready(function() {
                $('#riwayatOfflineTable').DataTable({
                    responsive: true,
                    searching: false,
                    pageLength: 10,
                    order: [
                        [0, 'asc']
                    ],

                    language: {
                        emptyTable: `
                            <div class="text-center py-5 text-muted">
                                <i class="bi bi-inbox fs-1 d-block mb-2 opacity-50"></i>
                                Belum ada riwayat peminjaman.
                            </div>
                        `,
                        zeroRecords: "Tidak ada data yang cocok"
                    },

                    columnDefs: [{
                            responsivePriority: 1,
                            targets: 3
                        },
                        {
                            responsivePriority: 2,
                            targets: 6
                        },
                        {
                            responsivePriority: 3,
                            targets: 0
                        },
                    ]
                });
            });

            // Modal Logic 
            const detailModal = document.getElementById('detailModal');
            detailModal.addEventListener('show.bs.modal', event => {
                const button = event.relatedTarget;
                const transaksiId = button.getAttribute('data-transaksi-id');
                const bukuId = button.getAttribute('data-buku-id');
                const isTelat = button.getAttribute('data-is-telat') === 'true';
                const hariTelat = button.getAttribute('data-hari-telat');
                const denda = button.getAttribute('data-denda');

                const modalBody = detailModal.querySelector('#modal-content-placeholder');
                const transaksiItem = riwayatOfflineData.find(item => item.id == transaksiId);
                if (!transaksiItem) return;
                const buku = transaksiItem.books.find(b => b.id == bukuId);
                if (!buku) return;

                let dendaHtml = '';

                if (isTelat) {
                    if (currentUserRole === 'guru') {
                        // JIKA GURU: Tampilkan Label Bebas Denda (Hijau)
                        dendaHtml = `
                        <div class="card border-0 border-start border-4 border-success bg-success-subtle mb-3 shadow-sm">
                            <div class="card-body p-3 d-flex align-items-center">
                                <div class="flex-shrink-0 me-3">
                                    <i class="bi bi-check-circle-fill text-success fs-1"></i>
                                </div>
                                <div class="text-start">
                                    <h6 class="fw-bold text-success mb-1">Bebas Denda</h6>
                                    <p class="mb-0 small text-success-emphasis">
                                        Sebagai Guru, Anda dibebaskan dari denda keterlambatan buku.
                                    </p>
                                </div>
                            </div>
                        </div>`;
                    } else {
                        // JIKA SISWA: Tampilkan Label Denda (Merah)
                        dendaHtml = `
                        <div class="card border-0 border-start border-4 border-danger bg-danger-subtle mb-3 shadow-sm">
                            <div class="card-body p-3 d-flex align-items-center">
                                <div class="flex-shrink-0 me-3">
                                    <i class="bi bi-exclamation-octagon-fill text-danger fs-1"></i>
                                </div>
                                <div class="text-start">
                                    <h6 class="fw-bold text-danger mb-1">Terlambat Pengembalian!</h6>
                                    <p class="mb-0 small text-danger-emphasis">
                                        Anda terlambat <span class="badge bg-danger text-white">${hariTelat} Hari</span>. 
                                        Denda yang harus dibayar: 
                                        <span class="fw-bold fs-6 d-block mt-1">Rp ${denda}</span>
                                    </p>
                                </div>
                            </div>
                        </div>`;
                    }
                }

                const keteranganHtml = buku.keterangan ? `
                <div class="card border-0 border-start border-4 border-warning bg-warning-subtle mb-4 shadow-sm">
                    <div class="card-body p-3 d-flex align-items-start">
                        <div class="flex-shrink-0 me-3">
                            <i class="bi bi-journal-bookmark-fill text-warning-emphasis fs-3"></i>
                        </div>
                        <div class="text-start">
                            <h6 class="fw-bold text-warning-emphasis mb-1">Catatan Petugas</h6>
                            <p class="mb-0 small text-dark opacity-75 fst-italic">
                                "${buku.keterangan}"
                            </p>
                        </div>
                    </div>
                </div>` : '';

                // RENDER HTML 
                modalBody.innerHTML = `
                <div class="text-center mb-4">
                    <img src="{{ asset('') }}${buku.cover}" class="img-fluid rounded shadow-sm" style="max-width: 140px;">
                </div>
                
                <h5 class="fw-bold text-center mb-1">${buku.judul}</h5>
                <p class="text-muted text-center small mb-4">${buku.deskripsi}</p>
                
                ${dendaHtml}
                ${keteranganHtml}
                
                <div class="card bg-light border-0 rounded-3 p-3">
                    <table class="table table-borderless table-sm mb-0">
                        <tbody>
                            <tr>
                                <td class="fw-bold text-start" style="width: 35%;">ID Peminjaman</td>
                                <td style="width: 1%;">:</td>
                                <td class="text-start">${transaksiItem.id_peminjaman}</td>
                            </tr>
                            <tr>
                                <td class="fw-bold text-start">Kode Buku</td>
                                <td>:</td>
                                <td class="text-start fw-medium">${buku.kode_buku}</td>
                            </tr>
                            <tr>
                                <td class="fw-bold text-start align-middle">Kategori</td>
                                <td class="align-middle">:</td>
                                <td class="text-start">
                                    <span class="badge bg-primary-subtle text-primary-emphasis rounded-pill px-3 py-2">
                                        ${buku.kategori}
                                    </span>
                                </td>
                            </tr>
                            <tr>
                                <td class="fw-bold text-start">Tahun Terbit</td>
                                <td>:</td>
                                <td class="text-start">${buku.tahun}</td>
                            </tr>
                            <tr>
                                <td class="fw-bold text-start">Tgl Pinjam</td>
                                <td>:</td>
                                <td class="text-start">${transaksiItem.tanggal_pinjam}</td>
                            </tr>
                            <tr>
                                <td class="fw-bold text-start">Tenggat</td>
                                <td>:</td>
                                <td class="text-start">${transaksiItem.tanggal_kembali}</td>
                            </tr>
                        </tbody>
                    </table>
                </div>`;
            });
        </script>
    @endpush
</x-app-layout>
