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

    // Initialize Select2 for filters
    $('.select2').select2({
        allowClear: true
    });

    // Initialize DataTable
    const table = $('#productsTable').DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: pageData.urls.datatable,
            data: function (d) {
                d.category_id = $('#filterCategory').val();
                d.warehouse_id = $('#filterWarehouse').val();
            }
        },
        columns: [
            {
                data: 'image',
                name: 'image',
                orderable: false,
                searchable: false,
                render: function (data) {
                    return data || '-';
                }
            },
            { data: 'product_code', name: 'product_code' },
            { data: 'sku', name: 'sku' },
            { data: 'name', name: 'name' },
            { data: 'category', name: 'category' },
            { data: 'stock', name: 'stock', orderable: false, searchable: false },
            { data: 'base_price', name: 'base_price' },
            { data: 'selling_price', name: 'selling_price' },
            { data: 'status', name: 'status' },
            { data: 'actions', name: 'actions', orderable: false, searchable: false }
        ],
        order: [[1, 'desc']],
        language: {
            search: '',
            searchPlaceholder: pageData.labels.searchPlaceholder || 'Search...',
            processing: pageData.labels.processing || 'Processing...',
            lengthMenu: pageData.labels.lengthMenu || 'Show _MENU_ entries',
            info: pageData.labels.info || 'Showing _START_ to _END_ of _TOTAL_ entries',
            infoEmpty: pageData.labels.infoEmpty || 'No entries to show',
            infoFiltered: pageData.labels.infoFiltered || '(filtered from _MAX_ total entries)',
            emptyTable: pageData.labels.emptyTable || 'No data available',
            zeroRecords: pageData.labels.zeroRecords || 'No matching records found',
            paginate: {
                first: pageData.labels.paginate?.first || 'First',
                last: pageData.labels.paginate?.last || 'Last',
                next: '<i class="bx bx-chevron-right"></i>',
                previous: '<i class="bx bx-chevron-left"></i>'
            }
        }
    });

    // Filter change handlers
    $('#filterCategory, #filterWarehouse').on('change', function () {
        table.ajax.reload();
    });

    // Delete product function
    window.deleteProduct = function(id) {
        Swal.fire({
            title: pageData.labels.confirmDelete,
            text: pageData.labels.deleteWarning,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: pageData.labels.yesDelete,
            cancelButtonText: pageData.labels.cancel,
            customClass: {
                confirmButton: 'btn btn-danger me-3',
                cancelButton: 'btn btn-label-secondary'
            },
            buttonsStyling: false
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: pageData.urls.destroy(id),
                    type: 'DELETE',
                    success: function(response) {
                        Swal.fire({
                            title: pageData.labels.success,
                            text: pageData.labels.deleteSuccess,
                            icon: 'success',
                            customClass: {
                                confirmButton: 'btn btn-success'
                            },
                            buttonsStyling: false
                        });
                        table.ajax.reload();
                    },
                    error: function(xhr) {
                        const msg = xhr.responseJSON?.message || pageData.labels.deleteError;
                        Swal.fire({
                            title: pageData.labels.error,
                            text: msg,
                            icon: 'error',
                            customClass: {
                                confirmButton: 'btn btn-danger'
                            },
                            buttonsStyling: false
                        });
                    }
                });
            }
        });
    };
});
