@extends('layouts.admin-simple')

@section('title', 'Indirect Goods Catalog')

@section('breadcrumb')
    <li class="breadcrumb-item">Warehouse</li>
    <li class="breadcrumb-item">Indirect Goods</li>
    <li class="breadcrumb-item active">Catalog</li>
@endsection

@section('page-title')
    <div class="d-flex justify-content-between align-items-center w-100">
        <div class="page-title-left">
            <h3 class="mb-1">Indirect Goods Catalog</h3>
            <p class="text-muted mb-0" style="font-size: 13px;">Manage indirect goods items and their details</p>
        </div>
        @can('warehouse.indirect-goods.create')
        <div class="page-actions-right d-flex align-items-center">
            <a href="{{ route('warehouse.indirect-goods.catalog.export') }}" class="btn btn-sm btn-success mr-2" title="Export to Excel">
                <i class="material-icons mr-1" style="font-size: 16px;">file_download</i>
                Export
            </a>
            <button onclick="showImportModal()" class="btn btn-sm btn-info mr-2" title="Import items">
                <i class="material-icons mr-1" style="font-size: 16px;">file_upload</i>
                Import
            </button>
            <button onclick="showAddModal()" class="btn btn-sm btn-primary" title="Add new indirect good">
                <i class="material-icons mr-1" style="font-size: 16px;">add</i>
                Add Indirect Good
            </button>
        </div>
        @endcan
    </div>
@endsection

@section('content')
    <!-- Filters Panel -->
    <div class="card mb-4">
        <div class="card-header">
            <h6 class="card-title mb-0">
                <i class="material-icons mr-2">filter_list</i>
                Filters
            </h6>
        </div>
        <div class="card-body">
            <div class="row align-items-center">
                <div class="col-md-3">
                    <div style="font-size: 12px; margin-bottom: 8px;">
                        @php
                            $categories = \App\Models\Warehouse\ItemCategory::where('status', 'active')->orderBy('category_name')->get();
                            $categoryOptions = [['value' => '', 'text' => 'All Categories']];
                            foreach($categories as $category) {
                                $categoryOptions[] = ['value' => $category->id, 'text' => $category->category_name];
                            }
                        @endphp
                        <x-warehouse.select2-dropdown
                            name="filter-category"
                            id="filter-category"
                            label="Category"
                            placeholder="All Categories"
                            :options="$categoryOptions"
                            class="form-control-sm"
                        />
                    </div>
                </div>
                <div class="col-md-3">
                    <div style="font-size: 12px; margin-bottom: 8px;">
                        <x-warehouse.select2-dropdown
                            name="filter-status"
                            id="filter-status"
                            label="Status"
                            placeholder="All Statuses"
                            :options="[
                                ['value' => '', 'text' => 'All Statuses'],
                                ['value' => 'active', 'text' => 'Active'],
                                ['value' => 'inactive', 'text' => 'Inactive']
                            ]"
                            class="form-control-sm"
                        />
                    </div>
                </div>
                <div class="col-md-6 d-flex align-items-end">
                    <div class="form-group mb-0 w-100">
                        <div class="d-flex flex-nowrap">
                            <button onclick="applyFilters()" class="btn btn-primary mr-2 flex-shrink-0">
                                <i class="material-icons mr-1" style="font-size: 16px;">search</i>
                                Apply Filters
                            </button>
                            <button onclick="clearFilters()" class="btn btn-outline-secondary flex-shrink-0">
                                <i class="material-icons mr-1" style="font-size: 16px;">clear</i>
                                Clear
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Items Table -->
    <div class="card">
        <div class="card-header warehouse-report-header">
            <h5 class="mb-0 warehouse-report-title">
                <i class="material-icons align-middle mr-2">category</i>
                Indirect Goods List
            </h5>
        </div>
        <div class="card-body p-0">
            <div class="warehouse-table-container">
                <!-- Loading Overlay -->
                <div class="warehouse-loading-overlay" id="tableLoadingOverlay" style="display: none;">
                    <div class="warehouse-loading-content">
                        <div class="text-center">
                            <div class="spinner-border text-primary" role="status">
                                <span class="sr-only">Loading...</span>
                            </div>
                            <div class="mt-2">Loading indirect goods...</div>
                        </div>
                    </div>
                </div>

                <!-- Table -->
                <div class="warehouse-table-wrapper">
                    <table id="ig-table" class="table table-hover mb-0 warehouse-table">
                        <thead class="thead-light">
                            <tr>
                                <th style="width: 40px;">#</th>
                                <th style="min-width: 120px;">IG Code</th>
                                <th style="min-width: 220px;">Description</th>
                                <th style="min-width: 120px;">Category</th>
                                <th style="min-width: 100px;">Unit</th>
                                <th style="min-width: 100px;">Stock Qty</th>
                                <th style="min-width: 100px;">Avg Price</th>
                                <th style="min-width: 80px;">Status</th>
                                <th style="min-width: 180px;">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <!-- Data will be populated by DataTables -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
@endsection

@section('modals')
<!-- Add Indirect Good Modal -->
<div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="addModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addModalLabel">
                    <i class="material-icons mr-2">category</i>
                    Add New Indirect Good
                </h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="addForm">
                    @csrf
                    <div class="row">
                        <div class="col-md-12">
                            <div class="form-group">
                                <label for="ig_description">Description <span class="text-danger">*</span></label>
                                <input type="text" name="ig_description" id="ig_description" class="form-control" required placeholder="Enter indirect good description">
                                <div class="invalid-feedback"></div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            @php
                                $modalCategoryOptions = [['value' => '', 'text' => 'Select Category']];
                                foreach($categories as $cat) {
                                    $modalCategoryOptions[] = ['value' => $cat->id, 'text' => $cat->category_name];
                                }
                            @endphp
                            <x-warehouse.select2-dropdown
                                name="category_id"
                                id="add_category_id"
                                label="Category"
                                placeholder="Select Category"
                                :options="$modalCategoryOptions"
                                required="true"
                            />
                        </div>
                        <div class="col-md-6">
                            @php
                                $units = \App\Models\Warehouse\Unit::active()->orderBy('unit_name')->get();
                                $unitOptions = [['value' => '', 'text' => 'Select Unit']];
                                foreach($units as $unit) {
                                    $unitOptions[] = ['value' => $unit->id, 'text' => $unit->unit_name . ' (' . $unit->unit_symbol . ')'];
                                }
                            @endphp
                            <x-warehouse.select2-dropdown
                                name="unit_id"
                                id="add_unit_id"
                                label="Unit of Measure"
                                placeholder="Select Unit"
                                :options="$unitOptions"
                                required="true"
                            />
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-4">
                            <div class="form-group">
                                <label for="min_stock_level">Min Stock Level</label>
                                <input type="number" name="min_stock_level" id="min_stock_level" class="form-control" min="0" step="0.01" placeholder="0">
                                <div class="invalid-feedback"></div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label for="max_stock_level">Max Stock Level</label>
                                <input type="number" name="max_stock_level" id="max_stock_level" class="form-control" min="0" step="0.01" placeholder="0">
                                <div class="invalid-feedback"></div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label for="reorder_point">Reorder Point</label>
                                <input type="number" name="reorder_point" id="reorder_point" class="form-control" min="0" step="0.01" placeholder="0">
                                <div class="invalid-feedback"></div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <x-warehouse.select2-dropdown
                                name="status"
                                id="add_status"
                                label="Status"
                                placeholder="Select Status"
                                :options="[
                                    ['value' => 'active', 'text' => 'Active'],
                                    ['value' => 'inactive', 'text' => 'Inactive']
                                ]"
                                selected="active"
                                required="true"
                            />
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-12">
                            <div class="form-group">
                                <label for="notes">Notes</label>
                                <textarea name="notes" id="notes" class="form-control" rows="3" placeholder="Optional notes about this item"></textarea>
                                <div class="invalid-feedback"></div>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <button type="button" onclick="saveItem()" class="btn btn-primary" id="saveBtn">
                    <i class="material-icons mr-1" style="font-size: 16px;">save</i>
                    Save
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Import Modal -->
<div class="modal fade" id="importModal" tabindex="-1" role="dialog" aria-labelledby="importModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="importModalLabel">
                    <i class="material-icons mr-2">file_upload</i>
                    Import Indirect Goods
                </h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <!-- Step 1: Download Template -->
                <div class="card mb-3">
                    <div class="card-body py-3">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <h6 class="mb-0">Step 1: Download Template</h6>
                            <a href="{{ route('warehouse.indirect-goods.catalog.template') }}" class="btn btn-sm btn-outline-info">
                                <i class="material-icons mr-1" style="font-size: 16px;">file_download</i>
                                Download Template
                            </a>
                        </div>
                        <small class="text-muted">Download the Excel template with the correct column format.</small>
                    </div>
                </div>

                <hr>

                <!-- Step 2: Upload File -->
                <form id="importForm" enctype="multipart/form-data">
                    @csrf
                    <div class="form-group">
                        <h6 class="mb-3">Step 2: Upload Your File</h6>
                        <div class="custom-file">
                            <input type="file" name="file" class="custom-file-input" id="importFile" accept=".xlsx,.xls,.csv" required>
                            <label class="custom-file-label" for="importFile">Choose file...</label>
                        </div>
                        <small class="form-text text-muted mt-2">
                            <i class="material-icons" style="font-size: 14px;">info</i>
                            Supported formats: Excel (.xlsx, .xls) or CSV files. Maximum size: 10MB.
                        </small>
                    </div>

                    <!-- Progress Bar -->
                    <div class="progress mb-3" id="uploadProgress" style="display: none;">
                        <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 0%"></div>
                    </div>

                    <!-- Import Results -->
                    <div id="importResults" style="display: none;">
                        <div class="alert alert-info">
                            <h6><i class="material-icons mr-1">assessment</i> Import Results</h6>
                            <div id="importSummary"></div>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <button type="button" onclick="importItems()" class="btn btn-primary" id="importBtn">
                    <i class="material-icons mr-1" style="font-size: 16px;">cloud_upload</i>
                    Import Items
                </button>
            </div>
        </div>
    </div>
</div>
@endsection

@push('styles')
    <link rel="stylesheet" href="{{ asset('admin-assets/css/warehouse-reports.css') }}">
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.7/css/dataTables.bootstrap4.min.css">
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet" />
    <style>
        .btn-sm {
            padding: 6px 12px;
            font-size: 12px;
            line-height: 1.5;
            border-radius: 4px;
        }

        .btn-sm .material-icons {
            font-size: 16px !important;
        }

        .table th {
            border-top: none;
            font-weight: 600;
            color: #495057;
            background-color: #f8f9fa;
        }

        .table-responsive {
            border-radius: 0.375rem;
        }

        .status-badge {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 11px;
            font-weight: 600;
            text-transform: uppercase;
        }

        .status-active {
            background-color: #d4edda;
            color: #155724;
        }

        .status-inactive {
            background-color: #e2e3e5;
            color: #383d41;
        }

        .stock-out {
            color: #dc3545;
            font-weight: 700;
        }

        .stock-low {
            color: #ffc107;
            font-weight: 700;
        }

        .stock-ok {
            color: #28a745;
            font-weight: 600;
        }

        /* Modal z-index fix for Select2 */
        .modal,
        #addModal,
        #importModal {
            z-index: 1050 !important;
            position: fixed !important;
        }

        .modal-backdrop {
            z-index: 1040 !important;
            position: fixed !important;
        }

        .modal-dialog {
            z-index: 1050 !important;
            position: relative !important;
        }

        .modal.show,
        .modal.fade.show {
            display: block !important;
            z-index: 1050 !important;
            opacity: 1 !important;
        }

        body.modal-open {
            overflow: hidden !important;
        }

        .select2-container--open .select2-dropdown {
            z-index: 1060 !important;
        }

        .select2-dropdown {
            z-index: 1060 !important;
        }

        #addModal .modal-body,
        #importModal .modal-body {
            overflow: visible !important;
        }

        #addModal .modal-content,
        #importModal .modal-content {
            overflow: visible !important;
        }

        #addModal .modal-dialog,
        #importModal .modal-dialog {
            overflow: visible !important;
        }

        #addModal,
        #importModal {
            overflow: visible !important;
        }

        /* DataTables search and entries padding */
        .dataTables_wrapper .dataTables_length {
            padding: 15px 20px;
        }

        .dataTables_wrapper .dataTables_filter {
            padding: 15px 20px 15px 0;
        }

        .dataTables_wrapper .dataTables_filter input {
            padding: 8px 15px;
            min-width: 300px;
        }

        /* Filter buttons styling */
        .card-body .btn-primary,
        .card-body .btn-outline-secondary {
            height: 32px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            padding: 0 12px;
            font-size: 13px;
        }

        .card-body .btn-primary .material-icons,
        .card-body .btn-outline-secondary .material-icons {
            font-size: 15px !important;
        }
    </style>
@endpush

@push('scripts')
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="{{ asset('admin-assets/js/warehouse-reports.js') }}"></script>
    <script src="https://cdn.datatables.net/1.13.7/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.7/js/dataTables.bootstrap4.min.js"></script>

    <script>
        let igTable;

        $(document).ready(function() {
            // Fix Select2 search in modals
            $(document).on('select2:open', function() {
                setTimeout(function() {
                    const searchField = document.querySelector('.select2-container--open .select2-search__field');
                    if (searchField) {
                        searchField.focus();
                    }
                }, 0);
            });

            if ($.fn.modal && $.fn.modal.Constructor) {
                $.fn.modal.Constructor.prototype._enforceFocus = function() {};
            }

            $(document).off('click', '.warehouse-pagination a, .pagination a');
            $('#tableLoadingOverlay').hide();

            initializeDataTable();

            // File input label update
            $('#importFile').on('change', function() {
                var fileName = $(this).val().split('\\').pop();
                $(this).next('.custom-file-label').html(fileName || 'Choose file...');
            });

            // Auto-open Add modal when navigated with ?action=add
            var urlParams = new URLSearchParams(window.location.search);
            if (urlParams.get('action') === 'add') {
                showAddModal();
            }
        });

        function initializeDataTable() {
            $('#tableLoadingOverlay').hide();

            igTable = $('#ig-table').DataTable({
                processing: true,
                serverSide: true,
                ajax: {
                    url: '{{ route("warehouse.indirect-goods.catalog.index") }}',
                    type: 'GET',
                    data: function(d) {
                        d.category_id = $('#filter-category').val();
                        d.status = $('#filter-status').val();
                    },
                    complete: function() {
                        $('#tableLoadingOverlay').hide();
                    },
                    error: function(xhr, error, thrown) {
                        console.error('DataTable AJAX error:', error, thrown);
                        $('#tableLoadingOverlay').hide();
                        showAlert('Error loading data. Please refresh the page.', 'error');
                    }
                },
                columns: [
                    {
                        data: null,
                        orderable: false,
                        searchable: false,
                        render: function(data, type, row, meta) {
                            return meta.row + meta.settings._iDisplayStart + 1;
                        }
                    },
                    {
                        data: 'ig_code',
                        name: 'ig_code',
                        render: function(data) {
                            return '<code>' + data + '</code>';
                        }
                    },
                    {
                        data: 'ig_description',
                        name: 'ig_description',
                        render: function(data, type, row) {
                            return '<div class="font-weight-medium">' + data + '</div>';
                        }
                    },
                    {
                        data: 'category_name',
                        name: 'category_name',
                        render: function(data) {
                            return '<span class="badge badge-secondary">' + (data || 'No Category') + '</span>';
                        }
                    },
                    {
                        data: 'unit_of_measure',
                        name: 'unit_of_measure',
                        render: function(data) {
                            return '<span class="badge badge-light">' + (data || 'N/A') + '</span>';
                        }
                    },
                    {
                        data: 'total_quantity',
                        name: 'total_quantity',
                        render: function(data, type, row) {
                            var qty = parseFloat(data) || 0;
                            var cls = 'stock-ok';
                            if (row.is_out_of_stock) {
                                cls = 'stock-out';
                            } else if (row.below_reorder_point) {
                                cls = 'stock-low';
                            }
                            return '<span class="' + cls + '">' + qty.toFixed(2) + '</span>';
                        }
                    },
                    {
                        data: 'average_unit_price',
                        name: 'average_unit_price',
                        render: function(data) {
                            var price = parseFloat(data) || 0;
                            return 'AED ' + price.toFixed(2);
                        }
                    },
                    {
                        data: 'status',
                        name: 'status',
                        render: function(data) {
                            var statusClasses = {
                                'active': 'status-active',
                                'inactive': 'status-inactive'
                            };
                            var status = data || 'inactive';
                            return '<span class="status-badge ' + (statusClasses[status] || 'status-inactive') + '">' + status.charAt(0).toUpperCase() + status.slice(1) + '</span>';
                        }
                    },
                    {
                        data: null,
                        name: 'actions',
                        orderable: false,
                        searchable: false,
                        render: function(data, type, row) {
                            var actions = '<div class="d-flex align-items-center" style="white-space: nowrap;">';

                            actions += '<a href="{{ url("warehouse/indirect-goods/catalog") }}/' + row.id + '" class="btn btn-sm btn-info mr-1" title="View">';
                            actions += '<i class="material-icons mr-1" style="font-size: 14px;">visibility</i>View</a>';

                            @can('warehouse.indirect-goods.edit')
                            actions += '<a href="{{ url("warehouse/indirect-goods/catalog") }}/' + row.id + '/edit" class="btn btn-sm btn-warning mr-1" title="Edit">';
                            actions += '<i class="material-icons mr-1" style="font-size: 14px;">edit</i>Edit</a>';
                            @endcan

                            @can('warehouse.indirect-goods.delete')
                            actions += '<button onclick="deleteItem(' + row.id + ', \'' + row.ig_description.replace(/'/g, "\\'") + '\')" class="btn btn-sm btn-danger" title="Delete">';
                            actions += '<i class="material-icons mr-1" style="font-size: 14px;">delete</i>Delete</button>';
                            @endcan

                            actions += '</div>';
                            return actions;
                        }
                    }
                ],
                order: [[1, 'asc']],
                pageLength: 25,
                lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, 'All']],
                language: {
                    processing: '<div class="spinner-border text-primary" role="status"><span class="sr-only">Loading...</span></div>',
                    emptyTable: 'No indirect goods found.',
                    zeroRecords: 'No matching records found.'
                },
                dom: '<"row"<"col-sm-6"l><"col-sm-6"f>>rtip'
            });
        }

        function applyFilters() {
            if (igTable) {
                igTable.ajax.reload();
            }
        }

        function clearFilters() {
            $('#filter-category').val('').trigger('change');
            $('#filter-status').val('').trigger('change');
            if (igTable) {
                igTable.ajax.reload();
            }
        }

        function showAddModal() {
            $('#addForm')[0].reset();
            $('#add_category_id').val('').trigger('change');
            $('#add_unit_id').val('').trigger('change');
            $('#add_status').val('active').trigger('change');
            $('#addForm .is-invalid').removeClass('is-invalid');
            $('#addModal').modal('show');
        }

        function saveItem() {
            var form = $('#addForm');
            var formData = form.serialize();
            var btn = $('#saveBtn');

            // Clear previous errors
            form.find('.is-invalid').removeClass('is-invalid');
            form.find('.invalid-feedback').text('');

            btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm mr-1"></span> Saving...');

            $.ajax({
                url: '{{ route("warehouse.indirect-goods.catalog.store") }}',
                type: 'POST',
                data: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'Accept': 'application/json'
                },
                success: function(response) {
                    if (response.success) {
                        $('#addModal').modal('hide');
                        showAlert('Indirect good created successfully.', 'success');
                        if (igTable) {
                            igTable.ajax.reload(null, false);
                        }
                    } else {
                        showAlert(response.message || 'An error occurred.', 'error');
                    }
                },
                error: function(xhr) {
                    if (xhr.status === 422) {
                        var errors = xhr.responseJSON.errors;
                        if (errors) {
                            $.each(errors, function(field, messages) {
                                var input = form.find('[name="' + field + '"]');
                                input.addClass('is-invalid');
                                input.siblings('.invalid-feedback').text(messages[0]);
                            });
                        }
                    } else {
                        var msg = xhr.responseJSON ? xhr.responseJSON.message : 'An error occurred while saving.';
                        showAlert(msg, 'error');
                    }
                },
                complete: function() {
                    btn.prop('disabled', false).html('<i class="material-icons mr-1" style="font-size: 16px;">save</i> Save');
                }
            });
        }

        function deleteItem(id, description) {
            Swal.fire({
                title: 'Delete Indirect Good?',
                html: 'Are you sure you want to delete <strong>' + description + '</strong>?<br><small class="text-muted">This action cannot be undone.</small>',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#dc3545',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Yes, Delete',
                cancelButtonText: 'Cancel'
            }).then(function(result) {
                if (result.isConfirmed) {
                    $.ajax({
                        url: '{{ url("warehouse/indirect-goods/catalog") }}/' + id,
                        type: 'DELETE',
                        headers: {
                            'X-CSRF-TOKEN': '{{ csrf_token() }}',
                            'Accept': 'application/json'
                        },
                        success: function(response) {
                            if (response.success) {
                                showAlert('Indirect good deleted successfully.', 'success');
                                if (igTable) {
                                    igTable.ajax.reload(null, false);
                                }
                            } else {
                                showAlert(response.message || 'Failed to delete.', 'error');
                            }
                        },
                        error: function(xhr) {
                            var msg = xhr.responseJSON ? xhr.responseJSON.message : 'An error occurred while deleting.';
                            showAlert(msg, 'error');
                        }
                    });
                }
            });
        }

        function showImportModal() {
            $('#importForm')[0].reset();
            $('.custom-file-label').html('Choose file...');
            $('#uploadProgress').hide();
            $('#importResults').hide();
            $('#importModal').modal('show');
        }

        function importItems() {
            var fileInput = $('#importFile')[0];
            if (!fileInput.files || !fileInput.files.length) {
                showAlert('Please select a file to import.', 'warning');
                return;
            }

            var formData = new FormData($('#importForm')[0]);
            var btn = $('#importBtn');

            btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm mr-1"></span> Importing...');
            $('#uploadProgress').show();
            $('#importResults').hide();

            $.ajax({
                url: '{{ route("warehouse.indirect-goods.catalog.import") }}',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'Accept': 'application/json'
                },
                xhr: function() {
                    var xhr = new window.XMLHttpRequest();
                    xhr.upload.addEventListener('progress', function(e) {
                        if (e.lengthComputable) {
                            var pct = Math.round((e.loaded / e.total) * 100);
                            $('#uploadProgress .progress-bar').css('width', pct + '%').text(pct + '%');
                        }
                    });
                    return xhr;
                },
                success: function(response) {
                    $('#uploadProgress .progress-bar').css('width', '100%').text('100%');
                    $('#importResults').show();

                    var summary = '<p><strong>Imported:</strong> ' + (response.imported || 0) + ' items</p>';
                    summary += '<p><strong>Skipped:</strong> ' + (response.skipped || 0) + ' items</p>';

                    if (response.data && response.data.errors && response.data.errors.length > 0) {
                        summary += '<div class="mt-2"><strong>Errors:</strong><ul class="mb-0">';
                        response.data.errors.forEach(function(err) {
                            summary += '<li class="text-danger">' + err + '</li>';
                        });
                        summary += '</ul></div>';
                    }

                    $('#importSummary').html(summary);

                    if (response.success) {
                        showAlert(response.message || 'Import completed.', 'success');
                        if (igTable) {
                            igTable.ajax.reload(null, false);
                        }
                    }
                },
                error: function(xhr) {
                    $('#uploadProgress').hide();
                    var msg = xhr.responseJSON ? xhr.responseJSON.message : 'Import failed. Please try again.';
                    showAlert(msg, 'error');
                },
                complete: function() {
                    btn.prop('disabled', false).html('<i class="material-icons mr-1" style="font-size: 16px;">cloud_upload</i> Import Items');
                }
            });
        }

        function showAlert(message, type) {
            var iconType = type || 'info';
            if (typeof Swal !== 'undefined') {
                Swal.fire({
                    icon: iconType,
                    title: iconType === 'success' ? 'Success' : (iconType === 'error' ? 'Error' : 'Notice'),
                    text: message,
                    timer: iconType === 'success' ? 2000 : undefined,
                    showConfirmButton: iconType !== 'success'
                });
            } else {
                alert(message);
            }
        }
    </script>
@endpush
