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

    <!-- Select2 CSS -->
    <!-- Select2 CSS -->
    <link href="{{ asset('assets/css/select2.min.css') }}" rel="stylesheet" />
    <link href="{{ asset('assets/css/jquery.dataTables.min.css') }}" rel="stylesheet">
    <link href="{{ asset('assets/css/responsive.dataTables.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>

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

            <!-- Filter Section (Matched with Loans) -->
            <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 Transaksi</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" 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" 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_type" class="block text-sm font-medium text-gray-700 mb-1">Jenis Transaksi</label>
                                <select id="filter_type" 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 Jenis</option>
                                    <option value="in">Barang Masuk</option>
                                    <option value="out">Barang Keluar</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">
                <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">Daftar Transaksi</h3>
                        <button id="createTransactionBtn" 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>+ Tambah Transaksi</span>
                        </button>
                    </div>

                    <div class="overflow-hidden rounded-lg border border-gray-100">
                        <table id="transactionsTable" class="min-w-full divide-y divide-gray-200 w-full">
                            <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">Tanggal</th>
                                    <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Sparepart</th>
                                    <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Jenis</th>
                                    <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Jumlah</th>
                                    <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Penerima (Karyawan)</th>
                                    <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">User</th>
                                    <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Aksi</th>
                                </tr>
                            </thead>
                            <tbody class="bg-white divide-y divide-gray-200">
                                <!-- DataTables -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal Form (Create/Edit) -->
    <div id="transactionModal" class="fixed z-50 inset-0 overflow-y-auto hidden" 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">
                <form id="transactionForm" name="transactionForm" 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 id="modalTitle" class="text-xl leading-6 font-bold text-gray-900 border-b pb-3 mb-4">Tambah Transaksi</h3>

                                <input type="hidden" id="transaction_id" name="id">

                                <div class="mt-2 space-y-5">
                                    <!-- Date -->
                                    <div>
                                        <label for="date" class="block text-sm font-medium text-gray-700 mb-1">Tanggal</label>
                                        <input type="date" id="date" name="date" 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" required>
                                    </div>

                                    <!-- Sparepart Select -->
                                    <div>
                                        <label for="sparepart_id" class="block text-sm font-medium text-gray-700 mb-1">Pilih Sparepart <span class="text-red-500">*</span></label>
                                        <div class="flex gap-2">
                                            <select id="sparepart_id" name="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 Sparepart --</option>
                                                @foreach($spareparts as $part)
                                                    <option value="{{ $part->id }}" data-code="{{ $part->code }}" data-stock="{{ $part->stock }}">
                                                        {{ $part->name }} ({{ $part->code }}) - Stok: {{ $part->stock }}
                                                    </option>
                                                @endforeach
                                            </select>
                                            <button type="button" id="startQrScan" 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" title="Scan QR Code">
                                                <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>

                                    <!-- Type -->
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 mb-1">Jenis Transaksi</label>
                                        <div class="flex gap-4 mt-2 p-3 bg-gray-50 rounded-lg border border-gray-200 justify-center">
                                            <label class="inline-flex items-center cursor-pointer">
                                                <input type="radio" class="form-radio text-green-600 focus:ring-green-500 h-4 w-4" name="type" value="in" checked>
                                                <span class="ml-2 font-bold text-gray-700">Barang Masuk (+)</span>
                                            </label>
                                            <label class="inline-flex items-center cursor-pointer">
                                                <input type="radio" class="form-radio text-red-600 focus:ring-red-500 h-4 w-4" name="type" value="out">
                                                <span class="ml-2 font-bold text-gray-700">Barang Keluar (-)</span>
                                            </label>
                                        </div>
                                    </div>

                                    <!-- Employee Select (For Stock Out Only) -->
                                    <div id="employeeField" class="hidden">
                                        <label for="employee_id" class="block text-sm font-medium text-gray-700 mb-1">Karyawan (Penerima) <span class="text-red-500">*</span></label>
                                        <select id="employee_id" name="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%">
                                            <option value="">-- Pilih Karyawan --</option>
                                            @foreach($employees as $emp)
                                                <option value="{{ $emp->id }}">{{ $emp->name }} ({{ $emp->nik }})</option>
                                            @endforeach
                                        </select>
                                    </div>



                                    <!-- Quantity -->
                                    <div>
                                        <label for="quantity" class="block text-sm font-medium text-gray-700 mb-1">Jumlah</label>
                                        <input type="number" id="quantity" name="quantity" 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" min="1" required>
                                    </div>

                                    <!-- Note -->
                                    <div>
                                        <label for="note" class="block text-sm font-medium text-gray-700 mb-1">Catatan (Optional)</label>
                                        <textarea id="note" name="note" rows="3" 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" placeholder="Keterangan transaksi..."></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" id="saveBtn" 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 transition duration-150">
                            Simpan
                        </button>
                        <button type="button" id="cancelBtn" 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 transition duration-150">
                            Batal
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- QR Scanner Modal -->
    <div id="qrScannerModal" class="fixed inset-0 z-[60] flex items-center justify-center bg-gray-900 bg-opacity-75 hidden">
        <div class="relative bg-white rounded-lg shadow-xl w-full max-w-md mx-4 overflow-hidden">
            <div class="px-4 py-3 border-b border-gray-200 flex justify-between items-center bg-gray-50">
                <h3 class="text-lg font-bold text-gray-800">Scan QR Code</h3>
                <button id="closeQrScanner" class="text-gray-400 hover:text-gray-600">
                    <svg class="h-6 w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
                </button>
            </div>
            <div class="p-4">
                <div id="reader" class="w-full" style="min-height: 250px; background-color: #000;"></div>
                <div class="mt-4 text-center">
                    <p class="text-sm text-gray-500 mb-2">Atau upload gambar QR</p>
                    <input type="file" id="qr-input-file" accept="image/*" class="text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100">
                </div>
            </div>
        </div>
        <div id="closeQrScannerBg" class="absolute inset-0 z-[-1]"></div>
    </div>

    <!-- Scripts -->
    <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>
    <script src="{{ asset('assets/js/select2.min.js') }}"></script>
    <script src="https://unpkg.com/html5-qrcode" type="text/javascript"></script>

    <script>
        $(document).ready(function() {
            // Setup CSRF
            $.ajaxSetup({
                headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
            });

            // Init Select2
            $('#sparepart_id').select2({
                placeholder: "-- Pilih Sparepart --",
                allowClear: true,
                dropdownParent: $('#transactionModal') // Fix Select2 in Modal
            });

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

            // Init DataTable
            var table = $('#transactionsTable').DataTable({
                responsive: true,
                processing: true,
                serverSide: true,
                autoWidth: false,
                ajax: {
                    url: "{{ route('sparepart-transactions.index') }}",
                    data: function(d) {
                         d.start_date = $('#start_date').val();
                         d.end_date = $('#end_date').val();
                         d.type = $('#filter_type').val();
                    }
                },
                columns: [
                    {data: 'DT_RowIndex', name: 'DT_RowIndex', orderable: false, searchable: false},
                    {data: 'date', name: 'date'},
                    {data: 'sparepart_name', name: 'sparepart.name'},
                    {data: 'type', name: 'type'},
                    {data: 'quantity', name: 'quantity'},
                    {data: 'employee_name', name: 'employee.name', defaultContent: '-'},
                    {data: 'user_name', name: 'user.name'},
                    {data: 'action', name: 'action', orderable: false, searchable: false, className: "text-center"},
                ],
                order: [[1, 'desc']], // Order by Date desc
                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() {
                $('#start_date').val(''); // Or 30 days ago
                $('#end_date').val('');   // Or Today
                $('#filter_type').val('all');
                table.draw();
                Swal.fire({
                    icon: 'info',
                    text: 'Filter Direset',
                    toast: true,
                    position: 'top-end',
                    showConfirmButton: false,
                    timer: 2000
                });
            });

            // Toast
            const Toast = Swal.mixin({
                toast: true,
                position: 'top-end',
                showConfirmButton: false,
                timer: 3000,
                timerProgressBar: true
            });

            // Modal Controls
            function openModal(title) {
                $('#modalTitle').text(title);
                $('#transactionModal').removeClass('hidden');
                $('#saveBtn').text('Simpan').prop('disabled', false); // Ensure button is enabled
            }
            function closeModal() {
                $('#transactionModal').addClass('hidden');
                $('#transactionForm')[0].reset();
                $('#transaction_id').val('');
                $('#sparepart_id').val('').trigger('change');
                $('#employee_id').val('').trigger('change');

                // Reset Readonly/Disabled State
                $('#sparepart_id').prop('disabled', false);
                $('input[name="type"]').prop('disabled', false);
                $('#employee_id').prop('disabled', false);

                // Explicitly Reset UI State to "In" (Default)
                $('#employeeField').addClass('hidden');
                $('#employee_id').prop('required', false);
                $('input[name="type"][value="in"]').prop('checked', true);

                $('#startQrScan').show();
            }

            $('#createTransactionBtn').click(function() {
                openModal('Tambah Transaksi');
                $('#date').val(new Date().toISOString().substring(0, 10));
            });

            $('#closeModal, #cancelBtn').click(closeModal);

            // Edit
            $('body').on('click', '.edit-btn', function() {
                var id = $(this).data('id');
                $.get("{{ route('sparepart-transactions.index') }}" + '/' + id + '/edit', function(data) {
                    openModal('Edit Transaksi');
                    $('#transaction_id').val(data.id);
                    $('#date').val(data.date);

                    // Set Values
                    $('#sparepart_id').val(data.sparepart_id).trigger('change');
                    $('input[name="type"][value="' + data.type + '"]').prop('checked', true);
                    $('#quantity').val(data.quantity);
                    $('#note').val(data.note);

                    // Disable Immutable Fields
                    $('#sparepart_id').prop('disabled', true);
                    $('input[name="type"]').prop('disabled', true);
                    $('#startQrScan').hide(); // Hide QR button in edit

                    // Handle Employee Field based on Type
                    if (data.type === 'out') {
                        $('#employeeField').removeClass('hidden');
                        $('#employee_id').val(data.employee_id).trigger('change').prop('required', true);
                         // Disable Employee field in Edit too?
                         // User said: "edit cuman tanggal dan stok". So employee should be disabled if present.
                         $('#employee_id').prop('disabled', true);
                    } else {
                        $('#employeeField').addClass('hidden');
                        $('#employee_id').val('').trigger('change').prop('required', false);
                    }
                });
            });

            // Handle Type Change (Radio Buttons)
            $('input[name="type"]').change(function() {
                var type = $(this).val();
                if (type === 'out') {
                    $('#employeeField').removeClass('hidden');
                    $('#employee_id').prop('required', true).val('').trigger('change');
                } else {
                    $('#employeeField').addClass('hidden');
                    $('#employee_id').prop('required', false).val('').trigger('change');
                }
            });

            // Save
            $('#transactionForm').submit(function(e) {
                e.preventDefault();
                $('#saveBtn').html('<i class="fas fa-spinner fa-spin"></i>').prop('disabled', true);

                // Client-side Validation
                var qty = parseInt($('#quantity').val());
                var type = $('input[name="type"]:checked').val();
                var sparepartId = $('#sparepart_id').val();

                // 1. Min Qty Validation > 1 (Per user request: "harus > 1")
                // Assuming >= 1 is technical constraint, but user emphasized validation.
                if (qty < 1) {
                    Swal.fire('Error', 'Jumlah harus minimal 1.', 'error');
                    $('#saveBtn').html('Simpan').prop('disabled', false);
                    return;
                }

                // 2. Stock Sufficiency Validation (Create Mode Only)
                // For Edit mode, calculation is complex (diff based), so we rely on backend.
                var isEdit = $('#transaction_id').val() !== '';
                if (!isEdit && type === 'out') {
                    var selectedOption = $('#sparepart_id').find(':selected');
                    var currentStock = parseInt(selectedOption.data('stock'));

                    if (qty > currentStock) {
                        Swal.fire({
                            icon: 'error',
                            title: 'Stok Tidak Cukup',
                            text: 'Sisa stok saat ini hanya ' + currentStock + '. Anda tidak bisa mengeluarkan ' + qty + ' barang.'
                        });
                        $('#saveBtn').html('Simpan').prop('disabled', false);
                        return;
                    }
                }

                // If Edit Mode, warn user about complexity (Optional, or just let backend handle it)
                // We rely on backend for Edit validations as implemented in Controller.

                var id = $('#transaction_id').val();
                var url = id ? "{{ route('sparepart-transactions.index') }}" + '/' + id : "{{ route('sparepart-transactions.store') }}";
                var typeMethod = id ? 'PUT' : 'POST';

                $.ajax({
                    data: $(this).serialize(),
                    url: url,
                    type: typeMethod,
                    success: function() {
                        closeModal();
                        table.draw();
                        Toast.fire({ icon: 'success', title: 'Berhasil disimpan' });
                        $('#saveBtn').html('Simpan').prop('disabled', false);
                    },
                    error: function(xhr) {
                        $('#saveBtn').html('Simpan').prop('disabled', false);
                        var msg = 'Terjadi kesalahan.';
                        if (xhr.responseJSON && xhr.responseJSON.error) {
                            msg = xhr.responseJSON.error;
                        } else if (xhr.responseJSON && xhr.responseJSON.message) {
                             msg = xhr.responseJSON.message;
                        }
                        Swal.fire('Error', msg, 'error');
                    }
                });
            });

            // Delete
            $('body').on('click', '.delete-btn', function() {
                var id = $(this).data('id');
                Swal.fire({
                    title: 'Yakin ingin menghapus?',
                    text: "Stok akan dikembalikan seperti semula!",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#d33',
                    cancelButtonColor: '#3085d6',
                    confirmButtonText: 'Ya, hapus!',
                    cancelButtonText: 'Batal'
                }).then((result) => {
                    if (result.isConfirmed) {
                        $.ajax({
                            type: "DELETE",
                            url: "{{ route('sparepart-transactions.index') }}" + '/' + id,
                            success: function() {
                                table.draw();
                                Toast.fire({ icon: 'success', title: 'Data dihapus' });
                            },
                            error: function(arr) {
                                Swal.fire('Error', arr.responseJSON.error, 'error');
                            }
                        });
                    }
                });
            });

            // QR Scanner Logic
            let html5QrCode;

            $('#startQrScan').click(function() {
                $('#qrScannerModal').removeClass('hidden');

                if (!html5QrCode) {
                    html5QrCode = new Html5Qrcode("reader");
                }

                html5QrCode.start(
                    { facingMode: "environment" },
                    { fps: 10, qrbox: { width: 250, height: 250 } },
                    (decodedText, decodedResult) => {
                         // On Success
                         handleQrCode(decodedText);
                    },
                    (errorMessage) => {
                        // ignore errors
                    }
                ).catch((err) => {
                    console.log('Scanner error:', err);
                    Swal.fire({
                         icon: 'error',
                         title: 'Tidak dapat mengakses kamera',
                         text: 'Pastikan izin kamera diberikan atau gunakan upload file.'
                    });
                });
            });

            function closeQrScanner() {
                if (html5QrCode && html5QrCode.isScanning) {
                    html5QrCode.stop().then(() => {
                        html5QrCode.clear();
                        $('#qrScannerModal').addClass('hidden');
                    }).catch(err => $('#qrScannerModal').addClass('hidden'));
                } else {
                     $('#qrScannerModal').addClass('hidden');
                }
            }

            $('#closeQrScanner, #closeQrScannerBg').click(closeQrScanner);

            function handleQrCode(code) {
                // Find option with data-code == code
                let found = false;
                $('#sparepart_id option').each(function() {
                    if ($(this).data('code') === code) {
                        $('#sparepart_id').val($(this).val()).trigger('change');
                        found = true;
                        return false; // break
                    }
                });

                closeQrScanner();

                if (found) {
                    Toast.fire({ icon: 'success', title: 'Sparepart ditemukan!' });
                } else {
                    Swal.fire('Not Found', 'Sparepart dengan kode QR tersebut tidak ditemukan.', 'warning');
                }
            }

            // File Upload QR
            $('#qr-input-file').change(function(e) {
                const file = e.target.files[0];
                if (!file) return;

                const html5QrCodeFile = new Html5Qrcode("reader");
                html5QrCodeFile.scanFile(file, true)
                .then(decodedText => {
                    handleQrCode(decodedText);
                })
                .catch(err => {
                     Swal.fire('Error', 'QR Code tidak terdeteksi pada gambar.', 'error');
                });
            });
        });
    </script>
</x-app-layout>
