<x-app-layout>
    @section('title', 'Peminjaman')
    <x-slot name="header">
        <h2 class="font-semibold text-xl text-gray-800 leading-tight">
            {{ __('Loans & Transactions') }}
        </h2>
    </x-slot>

    <!-- Select2 CSS -->
    <link href="{{ asset('assets/css/select2.min.css') }}" rel="stylesheet" />


    <!-- Custom Styles for DataTables Modernization & Select2 -->
    <style>
        /* Force rounded corners for the 'Show entries' dropdown */
        .dataTables_wrapper .dataTables_length select {
            border-radius: 0.5rem !important; /* rounded-lg */
            border: 1px solid #d1d5db !important;
            padding: 0.375rem 2.25rem 0.375rem 0.75rem !important;
            background-position: right 0.5rem center !important;
        }

        /* Force rounded corners for the 'Search' input */
        .dataTables_wrapper .dataTables_filter input {
            border-radius: 0.5rem !important; /* rounded-lg */
            border: 1px solid #d1d5db !important;
            padding: 0.375rem 0.75rem !important;
            margin-left: 0.5rem !important;
        }

        /* Pagination buttons styling */
        .dataTables_wrapper .dataTables_paginate .paginate_button {
            border-radius: 0.375rem !important; /* rounded-md */
            border: 1px solid #e5e7eb !important;
            background: white !important;
            color: #374151 !important;
            margin: 0 0.125rem !important;
        }
        .dataTables_wrapper .dataTables_paginate .paginate_button.current {
            background: #eff6ff !important; /* blue-50 */
            border-color: #3b82f6 !important; /* blue-500 */
            color: #1d4ed8 !important; /* blue-700 */
            font-weight: 600 !important;
        }
        .dataTables_wrapper .dataTables_paginate .paginate_button:hover {
            background: #f3f4f6 !important; /* gray-100 */
            border-color: #d1d5db !important;
            color: #111827 !important;
        }

        /* Table header styling */
        table.dataTable thead th {
             border-bottom: 2px solid #e5e7eb !important;
             color: #4b5563;
             font-weight: 600;
             text-transform: uppercase;
             font-size: 0.75rem;
             letter-spacing: 0.05em;
        }

        /* Responsive styling tweaks */
        @media (max-width: 640px) {
            .dataTables_wrapper .dataTables_length,
            .dataTables_wrapper .dataTables_filter {
                text-align: left !important;
                margin-bottom: 0.5rem;
            }
            .dataTables_wrapper .dataTables_filter input {
                width: 100% !important;
                margin-left: 0 !important;
                margin-top: 0.25rem;
            }
        }

        /* Select2 Custom Styling to Match Tailwind */
        .select2-container .select2-selection--single {
            height: 42px !important;
            border-radius: 0.5rem !important;
            border-color: #d1d5db !important;
        }
        .select2-container--default .select2-selection--single .select2-selection__rendered {
            line-height: 42px !important;
            padding-left: 0.75rem !important;
            color: #111827 !important;
        }
        .select2-container--default .select2-selection--single .select2-selection__arrow {
            height: 40px !important;
            right: 8px !important;
        }
        .select2-dropdown {
            border-radius: 0.5rem !important;
            border-color: #d1d5db !important;
        }
        .select2-search__field {
            border-radius: 0.375rem !important;
        }
    </style>

    <link href="{{ asset('assets/css/responsive.dataTables.min.css') }}" rel="stylesheet">


    <div class="py-12">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">

            <!-- Filter Section -->
            <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg mb-6">
                <div class="p-6 text-gray-900">
                    <button id="toggleFilterBtn" class="flex justify-between items-center w-full focus:outline-none group">
                        <div class="flex items-center gap-2">
                             <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-blue-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z" />
                            </svg>
                            <h3 class="text-lg font-bold text-gray-800 group-hover:text-blue-600 transition-colors">Filter Data Peminjaman</h3>
                        </div>
                        <svg id="chevronIcon" class="w-5 h-5 text-gray-500 transform transition-transform duration-200" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
                        </svg>
                    </button>

                    <div id="filterContent" class="hidden mt-4 border-t pt-4">
                         <div class="grid grid-cols-1 md:grid-cols-4 gap-4 items-end">
                            <div>
                                <label for="start_date" class="block text-sm font-medium text-gray-700 mb-1">Tanggal Awal</label>
                                <input type="date" id="start_date" value="{{ $startDate }}" class="h-10 w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm">
                            </div>
                            <div>
                                <label for="end_date" class="block text-sm font-medium text-gray-700 mb-1">Tanggal Akhir</label>
                                <input type="date" id="end_date" value="{{ $endDate }}" class="h-10 w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm">
                            </div>
                            <div>
                                <label for="filter_status" class="block text-sm font-medium text-gray-700 mb-1">Status</label>
                                <select id="filter_status" class="h-10 w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm">
                                    <option value="all">Semua Status</option>
                                    <option value="borrowed" {{ $status == 'borrowed' ? 'selected' : '' }}>Dipinjam</option>
                                    <option value="returned" {{ $status == 'returned' ? 'selected' : '' }}>Dikembalikan</option>
                                </select>
                            </div>
                            <div class="flex gap-2">
                                <button id="filterBtn" style="background-color: #3b82f6; color: white; border-radius: 8px;" class="h-10 w-full bg-blue-500 hover:bg-blue-600 text-white font-semibold px-4 rounded-lg shadow transition duration-150 ease-in-out">
                                    Terapkan Filter
                                </button>
                                <button id="resetFilterBtn" style="background-color: white; color: #374151; border: 1px solid #d1d5db; border-radius: 8px;" class="h-10 w-auto bg-white hover:bg-gray-50 text-gray-700 font-semibold px-4 rounded-lg shadow-sm transition duration-150 ease-in-out">
                                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                                    </svg>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="bg-white overflow-hidden shadow-lg sm:rounded-xl"> <!-- rounded-xl and shadow-lg -->
                <div class="p-6 text-gray-900">

                    <div class="flex flex-col sm:flex-row justify-between items-center mb-6 gap-4">
                        <h3 class="text-xl font-bold text-gray-800 self-start sm:self-center">Riwayat Peminjaman</h3>
                        <a href="javascript:void(0)" id="createLoan" style="background-color: #3b82f6; color: white; border-radius: 8px;" class="w-full sm:w-auto bg-blue-500 hover:bg-blue-600 text-white font-semibold py-2 px-4 rounded-lg shadow transition duration-150 ease-in-out flex items-center justify-center gap-2">
                            <span>+ Peminjaman Baru</span>
                        </a>
                        <button type="button" id="scanReturnBtn" style="background-color: #10b981; color: white; border-radius: 8px;" class="w-full sm:w-auto bg-green-500 hover:bg-green-600 text-white font-semibold py-2 px-4 rounded-lg shadow transition duration-150 ease-in-out flex items-center justify-center gap-2">
                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v1m6 11h2m-6 0h-2v4m0-11v3m0 0h.01M12 12h4.01M16 20h4M4 12h4m12 0h.01M5 8h2a1 1 0 001-1V5a1 1 0 00-1-1H5a1 1 0 00-1 1v2a1 1 0 001 1zm12 0h2a1 1 0 001-1V5a1 1 0 00-1-1h-2a1 1 0 00-1 1v2a1 1 0 001 1zM5 20h2a1 1 0 001-1v-2a1 1 0 00-1-1H5a1 1 0 00-1 1v2a1 1 0 001 1z"></path></svg>
                            <span>Scan Kembali</span>
                        </button>
                    </div>

                    <div class="overflow-hidden rounded-lg border border-gray-100">
                        <table class="min-w-full divide-y divide-gray-200 w-full" id="data-table">
                            <thead class="bg-gray-50">
                                <tr>
                                    <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">No</th>
                                    <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Karyawan</th>
                                    <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Suku Cadang</th>
                                    <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Tanggal Pinjam</th>
                                    <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Tanggal Kembali</th>
                                    <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                                    <th class="px-6 py-4 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">Aksi</th> <!-- Centered header -->
                                </tr>
                            </thead>
                            <tbody class="bg-white divide-y divide-gray-200">
                            </tbody>
                        </table>
                    </div>

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

    <!-- Create Loan Modal -->
    <div class="fixed z-50 inset-0 overflow-y-auto hidden" id="ajaxModel" aria-labelledby="modal-title" role="dialog" aria-modal="true">
        <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 backdrop-filter backdrop-blur-sm" aria-hidden="true"></div>
            <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
            <div class="inline-block align-bottom bg-white rounded-2xl text-left overflow-visible shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full"> <!-- overflow-visible for select2 dropdown -->
                <form id="loanForm" name="loanForm" class="form-horizontal">
                    <div class="bg-white px-6 pt-6 pb-6 sm:p-8">
                        <div class="sm:flex sm:items-start">
                            <div class="mt-3 text-center sm:mt-0 sm:text-left w-full">
                                <h3 class="text-xl leading-6 font-bold text-gray-900 border-b pb-3 mb-4" id="modelHeading">Buat Peminjaman Baru</h3>
                                <div class="mt-2 space-y-5">

                                    <div>
                                        <label for="employee_id" class="block text-sm font-medium text-gray-700 mb-1">Pilih Karyawan <span class="text-red-500">*</span></label>
                                        <select name="employee_id" id="employee_id" class="block w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm" style="width: 100%;" required>
                                            <option value="">-- Pilih Karyawan --</option>
                                            @foreach($employees as $employee)
                                                <option value="{{ $employee->id }}">{{ $employee->name }} ({{ $employee->nik ?? '-' }})</option>
                                            @endforeach
                                        </select>
                                    </div>

                                    <div class="mt-4">
                                        <label for="sparepart_id" class="block text-sm font-medium text-gray-700 mb-1">Pilih Suku Cadang <span class="text-red-500">*</span></label>
                                        <div class="flex gap-2">
                                            <select name="sparepart_id" id="sparepart_id" class="block w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm" style="width: 100%;" required>
                                                <option value="">-- Pilih Suku Cadang (Stok Tersedia) --</option>
                                                @foreach($spareparts as $sparepart)
                                                    <option value="{{ $sparepart->id }}" data-code="{{ $sparepart->code }}">{{ $sparepart->name }} (Stok: {{ $sparepart->stock }})</option>
                                                @endforeach
                                            </select>
                                            <button type="button" id="scanQrBtn" class="inline-flex items-center px-4 py-2 border border-gray-300 rounded-lg shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                                                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v1m6 11h2m-6 0h-2v4m0-11v3m0 0h.01M12 12h4.01M16 20h4M4 12h4m12 0h.01M5 8h2a1 1 0 001-1V5a1 1 0 00-1-1H5a1 1 0 00-1 1v2a1 1 0 001 1zm12 0h2a1 1 0 001-1V5a1 1 0 00-1-1h-2a1 1 0 00-1 1v2a1 1 0 001 1zM5 20h2a1 1 0 001-1v-2a1 1 0 00-1-1H5a1 1 0 00-1 1v2a1 1 0 001 1z"></path>
                                                </svg>
                                            </button>
                                        </div>
                                    </div>

                                    <div class="mt-4">
                                        <label for="borrowed_at" class="block text-sm font-medium text-gray-700 mb-1">Tanggal & Jam Pinjam <span class="text-xs text-gray-500">(Opsional, Default: Sekarang)</span></label>
                                        <input type="datetime-local" id="borrowed_at" name="borrowed_at" class="block w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm px-3 py-2">
                                    </div>

                                    <div class="mt-4">
                                        <label for="notes" class="block text-sm font-medium text-gray-700 mb-1">Catatan (Opsional)</label>
                                        <textarea class="block w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm px-3 py-2" id="notes" name="notes" placeholder="Masukkan catatan tambahan..."></textarea>
                                    </div>

                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="bg-gray-50 px-6 py-4 sm:flex sm:flex-row-reverse sm:gap-2 rounded-b-2xl">
                        <button type="submit" style="background-color: #2563eb; color: white; border-radius: 8px;" class="w-full inline-flex justify-center rounded-lg border border-transparent shadow px-4 py-2 bg-blue-600 text-base font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:w-auto sm:text-sm" id="saveBtn" value="create">Simpan</button>
                        <button type="button" style="background-color: white; color: #374151; border: 1px solid #d1d5db; border-radius: 8px;" class="mt-3 w-full inline-flex justify-center rounded-lg border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:mt-0 sm:w-auto sm:text-sm" id="closeModal">Batal</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- QR Scanner Modal -->
    <div class="fixed z-50 inset-0 overflow-y-auto hidden" id="qrScannerModal" aria-labelledby="modal-title" role="dialog" aria-modal="true">
        <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 backdrop-filter backdrop-blur-sm" aria-hidden="true" id="closeQrScannerBg"></div>
            <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
            <div class="inline-block align-bottom bg-white rounded-2xl text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
                <div class="bg-white px-6 pt-6 pb-6 sm:p-8">
                    <div class="sm:flex sm:items-start">
                        <div class="mt-3 text-center sm:mt-0 sm:text-left w-full">
                            <h3 class="text-xl leading-6 font-bold text-gray-900 border-b pb-3 mb-4">Scan QR Code Suku Cadang</h3>
                            <div class="mt-4">
                                <div id="qr-reader" style="width: 100%;"></div>
                                <div class="mt-4 text-center">
                                    <p class="text-sm text-gray-600 mb-2">Atau upload gambar QR Code:</p>
                                    <input type="file" id="qr-input-file" accept="image/*" class="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100">
                                </div>
                                <div id="qr-scan-result" class="mt-4 hidden">
                                    <div class="bg-green-50 border border-green-200 rounded-lg p-3">
                                        <p class="text-sm text-green-800 font-medium">✓ QR Code terdeteksi!</p>
                                        <p class="text-xs text-green-600 mt-1" id="qr-result-text"></p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="bg-gray-50 px-6 py-4 sm:flex sm:flex-row-reverse sm:gap-2 rounded-b-2xl">
                    <button type="button" id="closeQrScanner" class="w-full inline-flex justify-center rounded-lg border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:w-auto sm:text-sm">Tutup</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Return Loan Modal -->
    <div class="fixed z-50 inset-0 overflow-y-auto hidden" id="returnModal" aria-labelledby="modal-title" role="dialog" aria-modal="true">
        <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 backdrop-filter backdrop-blur-sm" aria-hidden="true"></div>
            <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
            <div class="inline-block align-bottom bg-white rounded-2xl text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-md sm:w-full">
                <div class="bg-white px-6 pt-6 pb-6 sm:p-8">
                    <div class="sm:flex sm:items-start">
                        <div class="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-green-100 sm:mx-0 sm:h-10 sm:w-10">
                            <!-- Icon Check -->
                            <svg class="h-6 w-6 text-green-600" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
                            </svg>
                        </div>
                        <div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left">
                            <h3 class="text-xl leading-6 font-bold text-gray-900" id="modal-title">Konfirmasi Pengembalian</h3>
                            <div class="mt-2">
                                <p class="text-sm text-gray-500">
                                    Apakah Anda yakin ingin menyelesaikan peminjaman ini? Stok barang akan dikembalikan.
                                </p>
                                <input type="hidden" id="return_loan_id">
                                <div class="mt-4">
                                     <label for="returned_at" class="block text-sm font-medium text-gray-700 mb-1">Tanggal & Jam Kembali <span class="text-xs text-gray-500">(Opsional, Default: Sekarang)</span></label>
                                     <input type="datetime-local" id="returned_at" name="returned_at" class="block w-full rounded-lg border-gray-300 shadow-sm focus:border-green-500 focus:ring-green-500 sm:text-sm px-3 py-2">
                                </div>
                                <div class="mt-4">
                                     <label for="return_notes" class="block text-sm font-medium text-gray-700 mb-1">Catatan Pengembalian (Opsional)</label>
                                     <textarea class="block w-full rounded-lg border-gray-300 shadow-sm focus:border-green-500 focus:ring-green-500 sm:text-sm px-3 py-2" id="return_notes" name="return_notes" placeholder="Contoh: Barang kembali dalam kondisi baik..."></textarea>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="bg-gray-50 px-6 py-4 flex flex-row-reverse gap-2">
                    <button type="button" id="confirmReturn" style="background-color: #10b981; color: white; border-radius: 8px;" class="w-full inline-flex justify-center rounded-lg border border-transparent shadow px-4 py-2 bg-green-600 text-base font-medium text-white hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 sm:w-auto sm:text-sm">
                        Kembalikan Barang
                    </button>
                    <button type="button" id="cancelReturn" style="background-color: white; color: #374151; border: 1px solid #d1d5db; border-radius: 8px;" class="mt-3 w-full inline-flex justify-center rounded-lg border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 sm:mt-0 sm:w-auto sm:text-sm">
                        Batal
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Loan Selection Modal (For Multiple Active Loans) -->
    <div class="fixed z-50 inset-0 overflow-y-auto hidden" id="selectionModal" aria-labelledby="modal-title" role="dialog" aria-modal="true">
        <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 backdrop-filter backdrop-blur-sm" aria-hidden="true"></div>
            <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
            <div class="inline-block align-bottom bg-white rounded-2xl text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
                <div class="bg-white px-6 pt-6 pb-6 sm:p-8">
                    <h3 class="text-xl leading-6 font-bold text-gray-900 border-b pb-3 mb-4">Pilih Peminjaman untuk Dikembalikan</h3>
                    <p class="text-sm text-gray-500 mb-4">Ditemukan beberapa peminjaman aktif untuk barang ini. Silakan pilih karyawan:</p>
                    <div id="loanSelectionList" class="space-y-2 max-h-60 overflow-y-auto">
                        <!-- List populated by JS -->
                    </div>
                </div>
                <div class="bg-gray-50 px-6 py-4 sm:flex sm:flex-row-reverse sm:gap-2 rounded-b-2xl">
                    <button type="button" id="closeSelectionModal" class="w-full inline-flex justify-center rounded-lg border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:w-auto sm:text-sm">Batal</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Scripts -->
    <link href="{{ asset('assets/css/jquery.dataTables.min.css') }}" rel="stylesheet">
    <link href="{{ asset('assets/css/responsive.dataTables.min.css') }}" rel="stylesheet">
    <script src="{{ asset('assets/js/jquery.min.js') }}"></script>
    <script src="{{ asset('assets/js/jquery.dataTables.min.js') }}"></script>
    <script src="{{ asset('assets/js/dataTables.responsive.min.js') }}"></script>
    <script src="{{ asset('assets/js/sweetalert2.all.min.js') }}"></script>
    <!-- Select2 JS -->
    <script src="{{ asset('assets/js/select2.min.js') }}"></script>
    <!-- HTML5 QR Code Scanner -->
    <script src="https://unpkg.com/html5-qrcode@2.3.8/html5-qrcode.min.js"></script>

    <script type="text/javascript">
        $(function () {
            // SweetAlert2 Toast Configuration
             const Toast = Swal.mixin({
                toast: true,
                position: 'top-end',
                showConfirmButton: false,
                timer: 3000,
                timerProgressBar: true,
                didOpen: (toast) => {
                    toast.addEventListener('mouseenter', Swal.stopTimer)
                    toast.addEventListener('mouseleave', Swal.resumeTimer)
                }
            });

            // AJAX CSRF Setup
            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });

            var table = $('#data-table').DataTable({
                processing: true,
                serverSide: true,
                responsive: true,
                autoWidth: false,
                ajax: {
                    url: "{{ route('loans.index') }}",
                    data: function (d) {
                        d.start_date = $('#start_date').val();
                        d.end_date = $('#end_date').val();
                        d.status = $('#filter_status').val();
                    }
                },
                columns: [
                    {data: 'DT_RowIndex', name: 'DT_RowIndex', orderable: false, searchable: false},
                    {data: 'employee.name', name: 'employee.name'},
                    {data: 'sparepart.name', name: 'sparepart.name'},
                    {data: 'borrowed_at', name: 'borrowed_at'},
                    {data: 'returned_at', name: 'returned_at'},
                    {data: 'status', name: 'status'},
                    {data: 'action', name: 'action', orderable: false, searchable: false, className: "text-center"},
                ],
                // Add language customization for better UX
                language: {
                    "sEmptyTable":   "Tidak ada data yang tersedia pada tabel ini",
                    "sProcessing":   "Sedang memproses...",
                    "sLengthMenu":   "Tampilkan _MENU_ entri",
                    "sZeroRecords":  "Tidak ditemukan data yang sesuai",
                    "sInfo":         "Menampilkan _START_ sampai _END_ dari _TOTAL_ entri",
                    "sInfoEmpty":    "Menampilkan 0 sampai 0 dari 0 entri",
                    "sInfoFiltered": "(disaring dari _MAX_ entri keseluruhan)",
                    "sInfoPostFix":  "",
                    "sSearch":       "Cari:",
                    "sUrl":          "",
                    "oPaginate": {
                        "sFirst":    "Pertama",
                        "sPrevious": "Sebelumnya",
                        "sNext":     "Selanjutnya",
                        "sLast":     "Terakhir"
                    }
                }
            });

            // Toggle Filter Logic with Animation
            $('#toggleFilterBtn').click(function() {
                $('#filterContent').slideToggle(200);
                $('#chevronIcon').toggleClass('rotate-180');
            });

            // Filter Button Logic
            $('#filterBtn').click(function() {
                table.draw();
            });

            // Reset Filter Logic
            $('#resetFilterBtn').click(function() {
                // Determine today's date and 30 days ago
                const now = new Date();
                const year = now.getFullYear();
                const month = String(now.getMonth() + 1).padStart(2, '0');
                const day = String(now.getDate()).padStart(2, '0');
                const today = `${year}-${month}-${day}`;

                const past = new Date();
                past.setDate(past.getDate() - 30);
                const pastYear = past.getFullYear();
                const pastMonth = String(past.getMonth() + 1).padStart(2, '0');
                const pastDay = String(past.getDate()).padStart(2, '0');
                const pastDate = `${pastYear}-${pastMonth}-${pastDay}`;

                // Reset inputs
                $('#start_date').val(pastDate);
                $('#end_date').val(today);
                $('#filter_status').val('borrowed'); // Default to 'borrowed' or 'all' based on preference, controller defaults to borrowed usually if not all

                table.draw();

                Toast.fire({
                    icon: 'info',
                    title: 'Filter Direset'
                });
            });

            // Initialize Select2
            $('#employee_id').select2({
                placeholder: "-- Pilih Karyawan --",
                allowClear: true,
                dropdownParent: $('#ajaxModel')
            });

            $('#sparepart_id').select2({
                placeholder: "-- Pilih Suku Cadang --",
                allowClear: true,
                dropdownParent: $('#ajaxModel')
            });

            // Helper to get current datetime-local string (YYYY-MM-DDTHH:MM)
            function getCurrentDateTimeLocal() {
                const now = new Date();
                const year = now.getFullYear();
                const month = String(now.getMonth() + 1).padStart(2, '0');
                const day = String(now.getDate()).padStart(2, '0');
                const hours = String(now.getHours()).padStart(2, '0');
                const minutes = String(now.getMinutes()).padStart(2, '0');
                return `${year}-${month}-${day}T${hours}:${minutes}`;
            }

            $('#createLoan').click(function () {
                $('#saveBtn').val("create-loan");
                $('#saveBtn').html("Simpan");
                $('#loanForm').trigger("reset");
                $('#borrowed_at').val(getCurrentDateTimeLocal()); // Set default time
                $('#modelHeading').html("Buat Peminjaman Baru");
                $('#ajaxModel').removeClass('hidden');
            });

            $('body').on('click', '#saveBtn', function (e) {
                e.preventDefault();

                // Validation Check
                if (!$('#loanForm')[0].checkValidity()) {
                    $('#loanForm')[0].reportValidity();
                    return;
                }

                $(this).html('Mengirim...');

                $.ajax({
                    data: $('#loanForm').serialize(),
                    url: "{{ route('loans.store') }}",
                    type: "POST",
                    dataType: 'json',
                    success: function (data) {
                        if(data.success) {
                            $('#loanForm').trigger("reset");
                            $('#employee_id').val(null).trigger('change');
                            $('#sparepart_id').val(null).trigger('change');
                            $('#borrowed_at').val(getCurrentDateTimeLocal()); // Reset time
                            $('#ajaxModel').addClass('hidden');
                            table.draw();
                            $('#saveBtn').html('Simpan');

                            Toast.fire({
                                icon: 'success',
                                title: 'Berhasil',
                                text: data.message
                            });
                        } else {
                             $('#saveBtn').html('Simpan');
                             Toast.fire({
                                icon: 'error',
                                title: 'Gagal',
                                text: data.message || 'Terjadi kesalahan'
                            });
                        }
                    },
                    error: function (data) {
                        console.log('Error:', data);
                        $('#saveBtn').html('Simpan');

                         // Handle Validation Errors
                        let errorMessage = 'Terjadi kesalahan. Silakan coba lagi.';
                        if (data.status === 422) {
                             let errors = data.responseJSON.errors;
                             errorMessage = '';
                             $.each(errors, function(key, value) {
                                 errorMessage += value[0] + '<br>';
                             });
                        }

                        Toast.fire({
                            icon: 'error',
                            title: 'Gagal',
                            html: errorMessage
                        });
                    }
                });
            });

            $('body').on('click', '#closeModal', function() {
                $('#ajaxModel').addClass('hidden');
            });

            // Return Modal Logic
            $('body').on('click', '.return-loan', function () {
                var loanId = $(this).data('id');
                $('#return_loan_id').val(loanId);
                $('#return_notes').val(''); // Reset notes
                $('#returned_at').val(getCurrentDateTimeLocal()); // Set default time
                $('#returnModal').removeClass('hidden');
            });

            $('body').on('click', '#cancelReturn', function () {
                $('#returnModal').addClass('hidden');
            });

            $('#confirmReturn').click(function () {
                $(this).html('Memproses...');
                var loanId = $('#return_loan_id').val();
                var notes = $('#return_notes').val();
                var returned_at = $('#returned_at').val();

                $.ajax({
                    url: "{{ route('loans.index') }}" +'/' + loanId,
                    type: "PUT",
                    data: {
                        notes: notes,
                        returned_at: returned_at, // Pass the date
                        _token: "{{ csrf_token() }}"
                    },
                    dataType: 'json',
                    success: function (data) {
                        $('#confirmReturn').html('Kembalikan Barang');
                        $('#returnModal').addClass('hidden');

                        if(data.success) {
                            table.draw();
                            Toast.fire({
                                icon: 'success',
                                title: 'Berhasil',
                                text: data.message
                            });
                        } else {
                             Toast.fire({
                                icon: 'error',
                                title: 'Gagal',
                                text: data.message
                            });
                        }
                    },
                    error: function (data) {
                         $('#confirmReturn').html('Kembalikan Barang');
                         console.log('Error:', data);
                         Toast.fire({
                            icon: 'error',
                            title: 'Gagal',
                            text: 'Terjadi kesalahan saat memproses data.'
                        });
                    }
                });
            });

            // Delete Loan Logic
            $('body').on('click', '.delete-loan', function () {
                var loanId = $(this).data('id');

                Swal.fire({
                    title: 'Hapus Peminjaman?',
                    text: "Stok barang akan dikembalikan. Tindakan ini tidak dapat dibatalkan!",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#ef4444',
                    cancelButtonColor: '#6b7280',
                    confirmButtonText: 'Ya, Hapus!',
                    cancelButtonText: 'Batal'
                }).then((result) => {
                    if (result.isConfirmed) {
                        $.ajax({
                            type: "DELETE",
                            url: "{{ route('loans.index') }}" + '/' + loanId,
                            success: function (data) {
                                table.draw();
                                Toast.fire({
                                    icon: 'success',
                                    title: data.success
                                });
                            },
                            error: function (data) {
                                console.log('Error:', data);
                                Toast.fire({
                                    icon: 'error',
                                    title: 'Gagal menghapus data'
                                });
                            }
                        });
                    }
                });
            });

            // QR Scanner Logic
            let html5QrCode;
            let scannerMode = 'create'; // 'create' or 'return'

            $('#scanQrBtn').click(function() {
                scannerMode = 'create';
                $('#qrScannerModal').removeClass('hidden');
                $('#qr-scan-result').addClass('hidden');
                startScanner();
            });

            $('#scanReturnBtn').click(function() {
                scannerMode = 'return';
                $('#qrScannerModal').removeClass('hidden');
                $('#qr-scan-result').addClass('hidden');
                startScanner();
            });

            function startScanner() {
                // Initialize scanner
                html5QrCode = new Html5Qrcode("qr-reader");

                // Start camera scanning
                html5QrCode.start(
                    { facingMode: "environment" }, // Use back camera on mobile
                    {
                        fps: 10,
                        qrbox: { width: 250, height: 250 }
                    },
                    (decodedText, decodedResult) => {
                        // QR Code detected
                        handleQrCodeDetected(decodedText);
                    },
                    (errorMessage) => {
                        // Scan error (can be ignored)
                    }
                ).catch((err) => {
                    console.log('Camera error:', err);

                    let title = 'Kamera Tidak Dapat Diakses';
                    let message = 'Pastikan Anda telah memberikan izin kamera.';
                    let icon = 'error';

                     // Check for Insecure Context (HTTP vs HTTPS)
                    if (location.protocol !== 'https:' && location.hostname !== 'localhost' && location.hostname !== '127.0.0.1') {
                         title = 'Koneksi Tidak Aman (HTTP)';
                         message = 'Browser memblokir akses kamera pada koneksi HTTP. Gunakan HTTPS atau localhost.';
                         icon = 'warning';
                    } else if (err.name === 'NotAllowedError' || err.name === 'PermissionDeniedError') {
                         title = 'Izin Ditolak';
                         message = 'Akses kamera ditolak. Silakan <strong>reset izin</strong> di browser (klik ikon gembok di URL bar) lalu muat ulang halaman.';
                         icon = 'warning';
                    } else if (err.name === 'NotFoundError') {
                         title = 'Kamera Tidak Ditemukan';
                         message = 'Tidak ada perangkat kamera yang terdeteksi.';
                    }

                    // Show Modal with Retry instructions (instead of Toast)
                    Swal.fire({
                        icon: icon,
                        title: title,
                        html: message + '<br><br><button onclick="location.reload()" class="bg-blue-500 text-white px-4 py-2 rounded">Muat Ulang Halaman</button>',
                        showConfirmButton: false
                    });
                });
            }

            // Handle file upload
            $('#qr-input-file').change(function(e) {
                const file = e.target.files[0];
                if (file) {
                    html5QrCode.scanFile(file, true)
                        .then(decodedText => {
                            handleQrCodeDetected(decodedText);
                        })
                        .catch(err => {
                            Toast.fire({
                                icon: 'error',
                                title: 'QR Code tidak terdeteksi di gambar'
                            });
                        });
                }
            });

            function handleQrCodeDetected(qrCode) {
                if (scannerMode === 'create') {
                    // Find sparepart by code
                    const option = $('#sparepart_id option').filter(function() {
                        return $(this).data('code') === qrCode;
                    });

                    if (option.length > 0) {
                        // Set the select value
                        $('#sparepart_id').val(option.val()).trigger('change');

                        // Show success message
                        $('#qr-result-text').text('Suku Cadang: ' + option.text());
                        $('#qr-scan-result').removeClass('hidden');

                        // Close modal after 1.5 seconds
                        setTimeout(() => {
                            closeQrScanner();
                            Toast.fire({
                                icon: 'success',
                                title: 'Suku Cadang berhasil dipilih!'
                            });
                        }, 1500);
                    } else {
                        Toast.fire({
                            icon: 'error',
                            title: 'Suku Cadang tidak ditemukan',
                            text: 'QR Code: ' + qrCode
                        });
                    }
                } else if (scannerMode === 'return') {
                     // Fetch active loans by QR code
                     $.ajax({
                        url: "{{ url('/loans/active-by-code') }}" + '/' + qrCode,
                        type: "GET",
                        success: function (data) {
                            closeQrScanner();

                            if (data.count === 0) {
                                Toast.fire({
                                    icon: 'info',
                                    title: 'Tidak ada peminjaman aktif',
                                    text: 'Suku cadang ' + data.sparepart_name + ' tidak sedang dipinjam.'
                                });
                            } else if (data.count === 1) {
                                // Directly open return modal
                                let loan = data.loans[0];
                                $('#return_loan_id').val(loan.id);
                                $('#return_notes').val('');
                                $('#returned_at').val(getCurrentDateTimeLocal()); // Set default time
                                $('#returnModal').removeClass('hidden');
                                Toast.fire({
                                    icon: 'success',
                                    title: 'Suku Cadang Terdeteksi',
                                    text: 'Peminjam: ' + loan.employee_name
                                });
                            } else {
                                // Open selection modal
                                let listHtml = '';
                                $.each(data.loans, function(index, loan) {
                                    listHtml += `
                                        <div class="p-3 border rounded-lg hover:bg-gray-50 cursor-pointer flex justify-between items-center" onclick="selectLoanForReturn(${loan.id})">
                                            <div>
                                                <p class="font-bold text-gray-800">${loan.employee_name}</p>
                                                <p class="text-xs text-gray-500">${loan.borrowed_at_formatted} (${loan.duration})</p>
                                            </div>
                                            <button class="bg-blue-100 text-blue-600 px-3 py-1 rounded-full text-xs font-bold">Pilih</button>
                                        </div>
                                    `;
                                });
                                $('#loanSelectionList').html(listHtml);
                                $('#selectionModal').removeClass('hidden');
                            }
                        },
                        error: function (xhr) {
                            closeQrScanner();
                            let msg = 'Gagal memproses QR Code.';
                            if (xhr.status === 404) {
                                msg = 'Suku cadang tidak ditemukan.';
                            }
                            Toast.fire({
                                icon: 'error',
                                title: 'Error',
                                text: msg
                            });
                        }
                    });
                }
            }

            // Expose function to global scope for onclick event
            window.selectLoanForReturn = function(loanId) {
                $('#selectionModal').addClass('hidden');
                $('#return_loan_id').val(loanId);
                $('#return_notes').val('');
                $('#returned_at').val(getCurrentDateTimeLocal()); // Set default time
                $('#returnModal').removeClass('hidden');
            };

            $('#closeSelectionModal').click(function() {
                $('#selectionModal').addClass('hidden');
            });

            function closeQrScanner() {
                if (html5QrCode && html5QrCode.isScanning) {
                    html5QrCode.stop().then(() => {
                        html5QrCode.clear();
                        $('#qrScannerModal').addClass('hidden');
                        html5QrCode = null;
                    }).catch(err => {
                        console.log('Stop error:', err);
                        $('#qrScannerModal').addClass('hidden');
                        html5QrCode = null;
                    });
                } else {
                    $('#qrScannerModal').addClass('hidden');
                    if (html5QrCode) {
                        html5QrCode.clear();
                        html5QrCode = null;
                    }
                }
                $('#qr-input-file').val('');
                $('#qr-scan-result').addClass('hidden');
            }

            $('#closeQrScanner, #closeQrScannerBg').click(function() {
                closeQrScanner();
            });
        });
    </script>
</x-app-layout>
