@section('page-title', 'Peminjaman Buku offline')
<x-app-layout>
    <div class="d-flex align-items-center">
        <a href="{{ route('peminjaman.ringkasan', $buku['id']) }}" class="btn btn-outline-secondary me-3">
            <i class="bi bi-arrow-left"></i>
        </a>
    </div>

    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card border-0 shadow-sm">
                <div class="card-body p-4 p-md-5">

                    <h1 class="h2 fw-semibold mb-5 text-center">Form Peminjaman Offline</h1>

                    <div class="card border-0 shadow-sm mb-4">
                        <div class="card-body p-4">
                            {{-- Header Section: Judul & Tombol Edit --}}
                            <div class="d-flex justify-content-between align-items-center mb-4 border-bottom pb-3">
                                <h5 class="fw-bold text-primary m-0">
                                    <i class="bi bi-person-lines-fill me-2"></i>Informasi Peminjam
                                </h5>
                                <a href="{{ route('profile.edit') }}" class="btn btn-sm btn-primary rounded-pill px-3">
                                    <i class="bi bi-pencil-square me-2"></i>Edit Profil
                                </a>
                            </div>

                            <div class="row g-3">
                                {{-- Nama Lengkap (Semua Role) --}}
                                <div class="col-md-6">
                                    <label class="form-label text-muted small text-uppercase fw-bold">Nama
                                        Lengkap</label>
                                    <p class="fw-semibold text-dark fs-5">{{ $user->nama_lengkap ?? $user->name }}</p>
                                </div>

                                {{-- KONDISI UNTUK GURU / PETUGAS --}}
                                @if(in_array($user->role, ['guru', 'penjaga perpus']))
                                <div class="col-md-6">
                                    <label class="form-label text-muted small text-uppercase fw-bold">NIP / NIK</label>
                                    <p class="fw-semibold text-dark">{{ $user->nip ?? '-' }}</p>
                                </div>
                                {{-- KONDISI UNTUK SISWA --}}
                                @else
                                <div class="col-md-6">
                                    <label class="form-label text-muted small text-uppercase fw-bold">NISN</label>
                                    <p class="fw-semibold text-dark">{{ $user->nisn ?? '-' }}</p>
                                </div>
                                @endif

                                {{-- Email (Semua Role) --}}
                                <div class="col-md-6">
                                    <label class="form-label text-muted small text-uppercase fw-bold">Email</label>
                                    <p class="fw-semibold text-dark">{{ $user->email }}</p>
                                </div>

                                {{-- Nomor HP (Semua Role) --}}
                                <div class="col-md-6">
                                    <label class="form-label text-muted small text-uppercase fw-bold">Nomor Handphone
                                        (WA)</label>
                                    <p class="fw-semibold text-dark">
                                        @if($user->no_hp)
                                        <span>{{ $user->no_hp
                                            }}</span>
                                        @else
                                        <span class="text-muted fst-italic">- Belum diatur -</span>
                                        @endif
                                    </p>
                                </div>

                                {{-- Info Tambahan Khusus Siswa --}}
                                @if($user->role == 'siswa')
                                <div class="col-md-6">
                                    <label class="form-label text-muted small text-uppercase fw-bold">Kelas</label>
                                    <p class="fw-semibold text-dark">{{ $user->kelas ?? '-' }}</p>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label text-muted small text-uppercase fw-bold">Golongan</label>
                                    <p class="fw-semibold text-dark">{{ $user->golongan ?? '-' }}</p>
                                </div>
                                @endif
                            </div>
                        </div>
                    </div>

                    {{-- Form untuk submit data --}}
                    <form action="{{ route('peminjaman.store') }}" method="POST" id="formPeminjaman"
                        data-semua-buku="{{ json_encode($semuaBuku->values()) }}"
                        data-buku-awal="{{ json_encode($buku) }}">
                        @csrf

                        {{-- Informasi Buku & Tanggal --}}
                        <div class="mb-5">
                            <div class="d-flex justify-content-between align-items-center border-bottom pb-2 mb-3">
                                <h5 class="fw-bold m-0">Buku yang Dipinjam</h5>
                                <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="modal"
                                    data-bs-target="#pilihBukuModal" id="btnTambahBuku">
                                    <i class="bi bi-plus-circle me-1"></i>Tambah Buku
                                </button>
                            </div>

                            {{-- Container untuk daftar buku yang dipinjam --}}
                            <div id="daftarBukuPinjam" class="mb-4">
                                <div class="book-item border rounded p-3 mb-3" data-book-id="{{ $buku['id'] }}">
                                    <div class="d-flex align-items-start">
                                        <img src="{{ asset($buku['cover']) }}" alt="Cover"
                                            class="rounded me-3 form-book-cover">
                                        <div class="flex-grow-1">
                                            <h6 class="fw-bold mb-1">{{ $buku['judul'] }}</h6>
                                            <p class="text-muted small mb-1">{{ $buku['penulis'] }}</p>
                                            <span class="badge bg-info">{{ $buku['kategori'] }}</span>
                                        </div>
                                        <span class="badge bg-success">Buku Utama</span>
                                    </div>
                                </div>
                            </div>

                            {{-- Hidden inputs untuk buku yang dipilih --}}
                            <div id="hiddenInputs">
                                <input type="hidden" name="buku_ids[]" value="{{ $buku['id'] }}">
                            </div>

                            {{-- Tanggal Peminjaman --}}
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <label for="tanggalPinjam" class="form-label text-muted">Tanggal Pinjam</label>
                                    <input type="text" id="tanggalPinjam" name="tanggal_pinjam" class="form-control"
                                        placeholder="Pilih tanggal pinjam"
                                        value="{{ \Carbon\Carbon::now()->format('d F Y') }}">
                                </div>
                                <div class="col-md-6">
                                    <label for="tanggalKembali" class="form-label text-muted">Tanggal Kembali</label>
                                    <input type="text" id="tanggalKembali" name="tanggal_kembali"
                                        placeholder="Pilih tanggal kembali" class="form-control"
                                        value="{{ \Carbon\Carbon::now()->addDays(7)->format('d F Y') }}">
                                </div>
                            </div>
                        </div>

                        {{-- Peraturan Peminjaman --}}
                        <div class="mb-4">
                            <h5 class="fw-bold border-bottom pb-2 mb-3">Peraturan Peminjaman</h5>
                            <div class="alert alert-info border-0 bg-info-subtle">
                                <ol class="mb-0 ps-3">
                                    <li>Perpustakaan buka pada jam operasional sekolah.</li>
                                    <li>Setiap siswa hanya dapat meminjam sebanyak 1-2 buku dalam satu waktu.</li>
                                    <li>Buku yang dipinjam harus dikembalikan dalam jangka waktu yang telah ditentukan.
                                    </li>
                                    <li>Jika buku tidak dikembalikan tepat waktu, akan dikenakan denda atau sanksi
                                        lainnya.</li>
                                    <li>Buku yang dikembalikan harus dalam kondisi baik, tanpa kerusakan atau hilang.
                                    </li>
                                    <li>Dilarang merusak atau mencoret-coret buku.</li>
                                    <li>Setiap siswa bertanggung jawab penuh terhadap buku yang dipinjam.</li>
                                </ol>
                            </div>
                        </div>

                        {{-- Tombol Kirim Form --}}
                        <div class="d-grid">
                            <button type="button" class="btn btn-primary" data-bs-toggle="modal"
                                data-bs-target="#konfirmasiModal">
                                Kirim Form
                            </button>
                        </div>
                    </form>

                </div>
            </div>
        </div>
    </div>

    {{-- Modal Pilih Buku --}}
    <div class="modal fade" id="pilihBukuModal" tabindex="-1" aria-labelledby="pilihBukuModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg modal-dialog-scrollable">
            <div class="modal-content border-0 shadow-lg rounded-3">

                <div class="modal-header bg-light">
                    <h5 class="modal-title fw-bold" id="pilihBukuModalLabel">
                        <i class="bi bi-book-half me-2 text-primary"></i>Pilih Buku Tambahan
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>

                <div class="modal-body">
                    <div class="alert alert-info border-0 bg-info-subtle mb-4 d-flex align-items-center">
                        <i class="bi bi-info-circle-fill me-2"></i>
                        <span>Anda dapat memilih maksimal <strong><span id="sisaSlot">1</span> buku</strong> lagi.
                            Total maksimal 2 buku.</span>
                    </div>

                    <div class="mb-3">
                        <div class="input-group shadow-sm">
                            <span class="input-group-text bg-white"><i class="bi bi-search"></i></span>
                            <input type="text" class="form-control border-start-0" id="searchBuku"
                                placeholder="Cari buku...">
                        </div>
                    </div>

                    <div id="daftarBukuModal" class="row g-3">
                        @foreach ($semuaBuku as $bukuItem)
                        @if ($bukuItem['status'] == 'Tersedia' || $bukuItem['id'] == $buku['id'])
                        <div class="col-12 book-option" data-book-id="{{ $bukuItem['id'] }}"
                            data-book-title="{{ strtolower($bukuItem['judul']) }}"
                            data-book-author="{{ strtolower($bukuItem['penulis']) }}">

                            <div class="card book-card h-100 border-0 shadow-sm hover-shadow transition"
                                onclick="toggleBookSelection({{ $bukuItem['id'] }})">

                                <div class="card-body p-3">
                                    <div class="d-flex align-items-start">

                                        <img src="{{ asset($bukuItem['cover']) }}" alt="Cover"
                                            class="rounded me-3 form-book-cover"
                                            style="width: 60px; height: 80px; object-fit: cover;">

                                        <div class="flex-grow-1">
                                            <h6 class="fw-bold mb-1">{{ $bukuItem['judul'] }}</h6>
                                            <p class="text-muted small mb-1">{{ $bukuItem['penulis'] }}</p>
                                            <div class="d-flex align-items-center flex-wrap gap-2">
                                                <span class="badge bg-info">{{ $bukuItem['kategori'] }}</span>
                                                <span class="badge bg-success"><i
                                                        class="bi bi-check-circle me-1"></i>Tersedia</span>
                                                @if ($bukuItem['id'] == $buku['id'])
                                                <span class="badge bg-primary"><i class="bi bi-star-fill me-1"></i>Buku
                                                    Utama</span>
                                                @endif
                                            </div>
                                        </div>

                                        {{-- PERBAIKAN: Checkbox tag dirapikan agar @if nya satu baris --}}
                                        <div class="form-check ms-2">
                                            <input class="form-check-input book-checkbox" type="checkbox"
                                                value="{{ $bukuItem['id'] }}" id="book{{ $bukuItem['id'] }}"
                                                @if($bukuItem['id']==$buku['id']) checked disabled @endif
                                                onclick="event.stopPropagation()">
                                        </div>

                                    </div>
                                </div>
                            </div>
                        </div>
                        @endif
                        @endforeach
                    </div>


                </div>
                <div class="p-3 bg-light">
                    <div class="d-flex justify-content-between align-items-center">
                        <span class="fw-semibold">
                            <i class="bi bi-collection me-2 text-primary"></i>Buku Terpilih:
                            <span id="counterBuku" class="text-dark">1</span>/2
                        </span>
                        <ul>
                            <li id="selectedBooks" class="text-muted small"></li>
                        </ul>
                    </div>
                </div>

                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">
                        <i class="bi bi-x-circle me-1"></i> Batal
                    </button>
                    <button type="button" class="btn btn-primary" id="konfirmasiBuku" onclick="konfirmasiPilihanBuku()">
                        <i class="bi bi-check2-circle me-1"></i> Konfirmasi Pilihan
                    </button>
                </div>
            </div>
        </div>
    </div>


    {{-- Modal Konfirmasi Kirim --}}
    <div class="modal fade" id="konfirmasiModal" tabindex="-1" aria-labelledby="konfirmasiModalLabel"
        aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content border-0 shadow-lg">
                <div class="modal-header border-0 text-center d-block">
                    <h5 class="modal-title fw-bold" id="konfirmasiModalLabel">Apakah Anda Yakin Ingin Mengirim Form?
                    </h5>
                </div>
                <div class="modal-body text-center">
                    <div class="text-muted mb-3">Pastikan data yang Anda kirim sudah benar.</div>
                    <div class="alert alert-info border-0 bg-info-subtle text-start">
                        <strong>Ringkasan Peminjaman:</strong>
                        <div id="ringkasanBuku" class="mt-2"></div>
                    </div>
                </div>
                <div class="alert alert-warning border-0 border-start border-4 border-warning shadow-sm mb-4"
                    role="alert">
                    <div class="d-flex">
                        <div class="fs-1 me-3 text-warning">
                            <i class="bi bi-exclamation-circle-fill"></i>
                        </div>
                        <div>
                            <h6 class="fw-bold text-dark mb-1">PENTING: Aturan Peminjaman!</h6>
                            <p class="mb-0 text-muted small">
                                Sesuai peraturan perpustakaan, durasi peminjaman buku maksimal adalah
                                <strong class="text-dark bg-warning-subtle px-2 py-1 rounded">2 HARI</strong>.
                                <br>
                                Mohon kembalikan tepat waktu untuk menghindari denda (Rp 1.000/hari).
                            </p>
                        </div>
                    </div>
                </div>
                <div class="modal-footer border-0 justify-content-center">
                    <button type="button" class="btn btn-secondary  px-4" data-bs-dismiss="modal">Batal</button>

                    {{-- Button Setuju jika sudah ada backend --}}
                    {{-- <button type="button" class="btn btn-primary   px-4" onclick="kirimForm()">Setuju</button> --}}

                    {{-- Button Setuju jika belum ada backend, akan ter direct ke peminjaman.index --}}
                    <button type="submit" form="formPeminjaman" class="btn btn-primary px-4">
                        Setuju
                    </button>
                </div>
            </div>
        </div>
    </div>
    <script>
        document.addEventListener("DOMContentLoaded", function() {

            // (Default Hari Ini + 2 Hari)
            const fpKembali = flatpickr("#tanggalKembali", {
                dateFormat: "d F Y",
                altInput: true,
                altFormat: "d F Y",
                defaultDate: new Date().fp_incr(2),
                locale: "id",
                minDate: new Date().fp_incr(1),
                maxDate: new Date().fp_incr(2)
            });

            // Inisialisasi Tanggal Pinjam
            flatpickr("#tanggalPinjam", {
                dateFormat: "d F Y",
                altInput: true,
                altFormat: "d F Y",
                defaultDate: "today",
                locale: "id",
                minDate: "today",

                onChange: function(selectedDates, dateStr) {
                    if (selectedDates.length > 0) {
                        const tglMulai = selectedDates[0];
                        const maxDateBaru = new Date(tglMulai).fp_incr(2);
                        const minDateBaru = new Date(tglMulai).fp_incr(1);

                        fpKembali.set("minDate", minDateBaru);
                        fpKembali.set("maxDate", maxDateBaru);
                        fpKembali.setDate(maxDateBaru);
                    }
                }
            });

            // Inisialisasi data dari data-attributes
            const form = document.getElementById('formPeminjaman');
            const arrayBuku = JSON.parse(form.dataset.semuaBuku);
            const bukuUtama = JSON.parse(form.dataset.bukuAwal);

            let selectedIds = [bukuUtama.id];
            const MAX_BOOKS = 2;

            // Global functions
            window.toggleBookSelection = function(id) {
                const index = selectedIds.indexOf(id);
                const checkbox = document.getElementById('book' + id);

                if (index > -1) {
                    if (id === bukuUtama.id) return;
                    selectedIds.splice(index, 1);
                    if (checkbox) checkbox.checked = false;
                } else {
                    if (selectedIds.length >= MAX_BOOKS) {
                        alert('Maksimal peminjaman adalah ' + MAX_BOOKS + ' buku.');
                        return;
                    }
                    selectedIds.push(id);
                    if (checkbox) checkbox.checked = true;
                }
                updateCounter();
            };

            window.konfirmasiPilihanBuku = function() {
                renderDaftarBuku();
                const modal = bootstrap.Modal.getInstance(document.getElementById('pilihBukuModal'));
                modal.hide();
            };

            function updateCounter() {
                const counterEl = document.getElementById('counterBuku');
                const sisaSlotEl = document.getElementById('sisaSlot');
                if (counterEl) counterEl.textContent = selectedIds.length;
                if (sisaSlotEl) sisaSlotEl.textContent = MAX_BOOKS - selectedIds.length;
            }

            function renderDaftarBuku() {
                const container = document.getElementById('daftarBukuPinjam');
                const hiddenInputs = document.getElementById('hiddenInputs');
                const ringkasan = document.getElementById('ringkasanBuku');

                if (!container || !hiddenInputs || !ringkasan) return;

                container.innerHTML = '';
                hiddenInputs.innerHTML = '';
                ringkasan.innerHTML = '<ul class="mb-0 text-start">';

                selectedIds.forEach(id => {
                    const buku = arrayBuku.find(b => b.id == id);
                    if (!buku) return;

                    const isUtama = id === (typeof bukuUtama.id === 'string' ? parseInt(bukuUtama.id) : bukuUtama.id);

                    const itemHtml = `
                        <div class="book-item border rounded p-3 mb-3" data-book-id="${buku.id}">
                            <div class="d-flex align-items-start text-start">
                                <img src="/${buku.cover}" alt="Cover" class="rounded me-3 form-book-cover" style="width: 50px; height: 70px; object-fit: cover;">
                                <div class="flex-grow-1">
                                    <h6 class="fw-bold mb-1">${buku.judul}</h6>
                                    <p class="text-muted small mb-1">${buku.penulis}</p>
                                    <span class="badge bg-info">${buku.kategori || 'Kategori'}</span>
                                </div>
                                ${isUtama ? '<span class="badge bg-success">Buku Utama</span>' : 
                                  '<button type="button" class="btn btn-sm btn-outline-danger" onclick="toggleSelectionAndRender(' + buku.id + ')"><i class="bi bi-trash"></i></button>'}
                            </div>
                        </div>
                    `;
                    container.insertAdjacentHTML('beforeend', itemHtml);

                    const input = document.createElement('input');
                    input.type = 'hidden';
                    input.name = 'buku_ids[]';
                    input.value = buku.id;
                    hiddenInputs.appendChild(input);

                    ringkasan.innerHTML += `<li>${buku.judul}</li>`;
                });

                ringkasan.innerHTML += '</ul>';
            }

            window.toggleSelectionAndRender = function(id) {
                window.toggleBookSelection(id);
                renderDaftarBuku();
            };

            document.getElementById('searchBuku').addEventListener('input', function(e) {
                const keyword = e.target.value.toLowerCase();
                document.querySelectorAll('.book-option').forEach(el => {
                    const title = el.dataset.bookTitle;
                    const author = el.dataset.bookAuthor;
                    if (title.includes(keyword) || author.includes(keyword)) {
                        el.style.display = 'block';
                    } else {
                        el.style.display = 'none';
                    }
                });
            });

            renderDaftarBuku();
            updateCounter();
        });
    </script>

</x-app-layout>