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

    <!-- Custom Styles for DataTables Modernization -->
    <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;
            }
        }
    </style>

    <link href="{{ asset('assets/css/jquery.dataTables.min.css') }}" rel="stylesheet">
    <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">
            <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 Suku Cadang</h3>
                        <a href="javascript:void(0)" id="createNewSparepart" 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 Suku Cadang</span>
                        </a>
                    </div>

                    <div class="rounded-lg border border-gray-100 p-2">
                        <table class="display nowrap" id="data-table" width="100%">
                            <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">Nama</th>
                                    <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Kode</th>
                                    <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Gambar</th>
                                    <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Stok</th>
                                    <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Lokasi</th>
                                    <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">QR Code</th>
                                    <th class="px-6 py-4 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">Aksi</th>
                                </tr>
                            </thead>
                            <tbody class="bg-white divide-y divide-gray-200">
                            </tbody>
                        </table>
                    </div>

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

    <!-- Modal Form -->
    <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-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
                <form id="sparepartForm" name="sparepartForm" 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"></h3>
                                <div class="mt-2 space-y-5">
                                    <input type="hidden" name="id" id="sparepart_id">

                                    <div>
                                        <label for="name" class="block text-sm font-medium text-gray-700 mb-1">Nama <span class="text-red-500">*</span></label>
                                        <input type="text" 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="name" name="name" placeholder="Masukkan Nama" required>
                                    </div>

                                    <div class="mt-4">
                                        <label for="code" class="block text-sm font-medium text-gray-700 mb-1">Kode (Kosongkan untuk auto-generate)</label>
                                        <input type="text" 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="code" name="code" placeholder="Contoh: SP-12345">
                                    </div>

                                    <div class="mt-4">
                                        <label for="stock" class="block text-sm font-medium text-gray-700 mb-1">Stok <span class="text-red-500">*</span></label>
                                        <input type="number" 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="stock" name="stock" min="0" value="0" required>
                                    </div>

                                    <div class="mt-4">
                                        <label for="location" class="block text-sm font-medium text-gray-700 mb-1">Lokasi</label>
                                        <input type="text" 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="location" name="location" placeholder="Masukkan Lokasi">
                                    </div>

                                    <div class="mt-4">
                                        <label for="description" class="block text-sm font-medium text-gray-700 mb-1">Deskripsi</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="description" name="description" placeholder="Masukkan Deskripsi"></textarea>
                                    </div>

                                    <div class="mt-4">
                                        <label for="image" class="block text-sm font-medium text-gray-700 mb-1">Gambar (Opsional)</label>
                                        <input type="file" 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" id="image" name="image" accept="image/*">
                                        <p class="mt-1 text-xs text-gray-500">Format: JPG, PNG, GIF (Max: 2MB)</p>
                                        <div id="image-preview" class="mt-2 hidden">
                                            <img id="preview-img" src="" alt="Preview" class="w-32 h-32 object-cover rounded-lg border">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="bg-gray-50 px-6 py-4 sm:flex sm:flex-row-reverse sm:gap-2 sm:items-center">
                        <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 Code Modal -->
    <div class="fixed z-50 inset-0 overflow-y-auto hidden" id="qrModal" aria-labelledby="modal-title" role="dialog" aria-modal="true">
        <div class="flex items-center 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="closeQrModalBg"></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-sm sm:w-full">
                <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                    <div class="sm:flex sm:items-start justify-center">
                        <div class="mt-3 text-center sm:mt-0 sm:text-left w-full">
                            <h3 class="text-lg leading-6 font-medium text-gray-900 text-center mb-4" id="modal-title">QR Code</h3>
                            <div class="mt-2 flex justify-center">
                                <img id="largeQrImage" src="" alt="Large QR Code" class="w-64 h-64 object-contain border rounded-lg shadow-sm">
                            </div>
                            <p class="text-sm text-gray-500 mt-4 text-center" id="qrCodeText"></p>
                        </div>
                    </div>
                </div>
                <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse justify-center gap-2">
                    <button type="button" style="background-color: #22c55e; color: white; border-radius: 8px;" class="w-full inline-flex justify-center rounded-lg border border-transparent shadow px-4 py-2 bg-green-500 text-base font-semibold text-white hover:bg-green-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 sm:w-auto sm:text-sm transition duration-150 ease-in-out" id="downloadQrBtn">
                        <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"></path></svg>
                        Download QR
                    </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-gray-500 sm:mt-0 sm:w-auto sm:text-sm" id="closeQrModal">
                        Tutup
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Product Image Zoom Modal -->
    <div class="fixed z-50 inset-0 overflow-y-auto hidden" id="imageModal" aria-labelledby="modal-title" role="dialog" aria-modal="true">
        <div class="flex items-center 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="closeImageModalBg"></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-sm sm:w-full">
                <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                    <div class="sm:flex sm:items-start justify-center">
                        <div class="mt-3 text-center sm:mt-0 sm:text-left w-full">
                            <h3 class="text-lg leading-6 font-medium text-gray-900 text-center mb-4">Foto Produk</h3>
                            <div class="mt-2 flex justify-center">
                                <img id="largeProductImage" src="" alt="Large Product Image" class="w-64 h-64 object-contain border rounded-lg shadow-sm">
                            </div>
                            <p class="text-sm text-gray-500 mt-4 text-center" id="imageNameText"></p>
                        </div>
                    </div>
                </div>
                <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse justify-center gap-2">
                    <button type="button" style="background-color: #22c55e; color: white; border-radius: 8px;" class="w-full inline-flex justify-center rounded-lg border border-transparent shadow px-4 py-2 bg-green-500 text-base font-semibold text-white hover:bg-green-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 sm:w-auto sm:text-sm transition duration-150 ease-in-out" id="downloadImageBtn">
                        <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"></path></svg>
                        Download
                    </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-gray-500 sm:mt-0 sm:w-auto sm:text-sm" id="closeImageModalBtn">
                        Tutup
                    </button>
                </div>
            </div>
        </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 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)
                }
            });

            $.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: "{{ route('spareparts.index') }}",
                columnDefs: [
                    { responsivePriority: 1, targets: 0 }, // No
                    { responsivePriority: 2, targets: 1 }, // Name
                    { responsivePriority: 3, targets: -1 }, // Action (Last Column)
                ],
                columns: [
                    {data: 'DT_RowIndex', name: 'DT_RowIndex', orderable: false, searchable: false},
                    {data: 'name', name: 'name'},
                    {data: 'code', name: 'code'},
                    {data: 'image_display', name: 'image_display', orderable: false, searchable: false},
                    {data: 'stock', name: 'stock'},
                    {data: 'location', name: 'location'},
                    {data: 'qr_code', name: 'qr_code', orderable: false, searchable: false,
                        render: function(data, type, row) {
                            // Extract just the URL from the img tag provided by backend controller
                            // Or better yet, we construct the image tag here to add the click handler wrapper
                            // The backend returns: <img src="..." alt="QR">
                            // We will wrap it in a div that triggers the modal

                            // Let's parse the URL from the string data returned by controller
                            var parser = new DOMParser();
                            var doc = parser.parseFromString(data, 'text/html');
                            var img = doc.querySelector('img');
                            var src = img ? img.src : '';

                            return `<div class="cursor-pointer hover:opacity-80 transition qr-trigger" data-code="${row.code}" data-src="${src}">
                                        ${data}
                                        <span class="text-xs text-blue-500 block">Klik untuk perbesar</span>
                                    </div>`;
                        }
                    },
                    {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"
                    }
                }
            });

            // QR Code Modal Logic
            $('body').on('click', '.qr-trigger', function() {
                var src = $(this).data('src');
                var code = $(this).data('code');

                // Increase the size parameter in the URL for the large modal
                var largeSrc = src.replace('size=50x50', 'size=300x300');

                $('#largeQrImage').attr('src', largeSrc);
                $('#qrCodeText').text('Kode: ' + code);
                $('#qrModal').removeClass('hidden');
            });

            $('body').on('click', '#closeQrModal, #closeQrModalBg', function() {
                $('#qrModal').addClass('hidden');
            });

            // Download QR Code Handler
            $('#downloadQrBtn').click(function() {
                var imgSrc = $('#largeQrImage').attr('src');
                var codeText = $('#qrCodeText').text().replace('Kode: ', '');

                fetch(imgSrc)
                    .then(response => response.blob())
                    .then(blob => {
                        var url = window.URL.createObjectURL(blob);
                        var a = document.createElement('a');
                        a.href = url;
                        a.download = 'QR-' + codeText + '.png';
                        document.body.appendChild(a);
                        a.click();
                        window.URL.revokeObjectURL(url);
                        document.body.removeChild(a);
                    })
                    .catch(e => console.error('Download failed:', e));
            });

            // Product Image Zoom Logic
            $('body').on('click', '.image-trigger', function() {
                var src = $(this).data('src');
                $('#largeProductImage').attr('src', src);
                $('#imageModal').removeClass('hidden');
            });

            $('body').on('click', '#closeImageModalBtn, #closeImageModalBg', function() {
                $('#imageModal').addClass('hidden');
            });

            // Download Image Handler
            $('#downloadImageBtn').click(function() {
                var imgSrc = $('#largeProductImage').attr('src');
                // Create a temporary link to trigger download
                var a = document.createElement('a');
                a.href = imgSrc;
                // Extract filename from URL or default
                var filename = imgSrc.substring(imgSrc.lastIndexOf('/')+1);
                a.download = filename;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
            });

            // Image Preview Handler
            $('#image').change(function() {
                var file = this.files[0];
                if (file) {
                    var reader = new FileReader();
                    reader.onload = function(e) {
                        $('#preview-img').attr('src', e.target.result);
                        $('#image-preview').removeClass('hidden');
                    }
                    reader.readAsDataURL(file);
                } else {
                    $('#image-preview').addClass('hidden');
                }
            });

            $('#createNewSparepart').click(function () {
                $('#saveBtn').val("create-sparepart");
                $('#saveBtn').html("Simpan");
                $('#sparepart_id').val('');
                $('#sparepartForm').trigger("reset");
                $('#code').prop('readonly', false).removeClass('bg-gray-100 cursor-not-allowed'); // Enable code input
                $('#image-preview').addClass('hidden');
                $('#modelHeading').html("Tambah Suku Cadang Baru");
                $('#ajaxModel').removeClass('hidden');
            });

            $('body').on('click', '.edit', function () {
                var id = $(this).data('id');
                $.get("{{ route('spareparts.index') }}" +'/' + id +'/edit', function (data) {
                    $('#modelHeading').html("Edit Suku Cadang");
                    $('#saveBtn').val("edit-sparepart");
                    $('#saveBtn').html("Update Data");
                    $('#ajaxModel').removeClass('hidden');
                    $('#sparepart_id').val(data.id);
                    $('#name').val(data.name);
                    $('#code').val(data.code).prop('readonly', true).addClass('bg-gray-100 cursor-not-allowed'); // Disable code input
                    $('#stock').val(data.stock);
                    $('#location').val(data.location);
                    $('#description').val(data.description);

                    // Show existing image if available
                    if (data.image) {
                        $('#preview-img').attr('src', '{{ asset("storage") }}/' + data.image);
                        $('#image-preview').removeClass('hidden');
                    } else {
                        $('#image-preview').addClass('hidden');
                    }
                })
            });

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

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

                $(this).html('Mengirim...');
                var id = $('#sparepart_id').val();
                var url = id ? "{{ route('spareparts.index') }}" + '/' + id : "{{ route('spareparts.store') }}";
                var type = id ? "PUT" : "POST";

                // Use FormData for file upload
                var formData = new FormData($('#sparepartForm')[0]);

                // For PUT requests, Laravel needs _method field
                if (type === "PUT") {
                    formData.append('_method', 'PUT');
                }

                $.ajax({
                    data: formData,
                    url: url,
                    type: "POST", // Always POST when using FormData
                    dataType: 'json',
                    processData: false,
                    contentType: false,
                    success: function (data) {
                        $('#sparepartForm').trigger("reset");
                        $('#image-preview').addClass('hidden');
                        $('#ajaxModel').addClass('hidden');
                        table.draw();
                        $('#saveBtn').html('Simpan');

                        // Success Toast
                        Toast.fire({
                           icon: 'success',
                           title: 'Berhasil',
                           text: data.success
                        });
                    },
                    error: function (data) {
                        console.log('Error:', data);
                        $('#saveBtn').html('Simpan');

                        // Error Toast
                        Toast.fire({
                            icon: 'error',
                            title: 'Terjadi kesalahan. Silakan coba lagi.'
                        });
                    }
                });
            });

            $('body').on('click', '.delete', function () {
                var id = $(this).data("id");
                Swal.fire({
                    title: 'Delete this sparepart?',
                    text: "Action cannot be undone!",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#ef4444',
                    cancelButtonColor: '#6b7280',
                    confirmButtonText: 'Yes, delete it!'
                }).then((result) => {
                    if (result.isConfirmed) {
                        $.ajax({
                            type: "DELETE",
                            url: "{{ route('spareparts.store') }}"+'/'+id,
                            success: function (data) {
                                table.draw();
                                // Success Toast for Delete
                                Toast.fire({
                                    icon: 'success',
                                    title: 'Sparepart has been deleted.'
                                });
                            },
                            error: function (data) {
                                console.log('Error:', data);
                                // Error Toast for Delete
                                Toast.fire({
                                    icon: 'error',
                                    title: 'Something went wrong.'
                                });
                            }
                        });
                    }
                })
            });

            $('body').on('click', '#closeModal', function() {
                $('#ajaxModel').addClass('hidden');
            });
        });
    </script>
</x-app-layout>
