$(function () {
    let dt_table = $('#customers-table');

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

    // Initialize Select2
    $('.form-select').select2({
        allowClear: true
    });

    // DataTable
    let dt = dt_table.DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: pageData.urls.datatable,
            data: function (d) {
                d.company_id = $('#filter-company').val();
                d.customer_type = $('#filter-customer-type').val();
                d.status = $('#filter-status').val();
            }
        },
        columns: [
            { data: 'customer_name' },
            { data: 'contact_info' },
            { data: 'customer_type_badge' },
            { data: 'company_name' },
            { data: 'credit_limit_formatted' },
            { data: 'status_column' },
            { data: 'actions', orderable: false, searchable: false }
        ],
        order: [[0, 'asc']],
        drawCallback: function() {
            loadStatistics();
        }
    });

    // Filter change
    $('#filter-company, #filter-customer-type, #filter-status').on('change', function() {
        dt.ajax.reload();
    });

    // Load statistics
    function loadStatistics() {
        $.get(pageData.urls.statistics, function(response) {
            if (response.status === 'success') {
                $('#stat-total').text(response.data.total_customers.toLocaleString());
                $('#stat-active').text(response.data.active_customers.toLocaleString());
                $('#stat-new').text(response.data.new_customers_this_month.toLocaleString());
                $('#stat-b2b').text(response.data.b2b_customers.toLocaleString());
                $('#stat-b2c').text(response.data.b2c_customers.toLocaleString());
                $('#stat-with-company').text(response.data.customers_with_company.toLocaleString());
            }
        });
    }

    // View customer
    window.viewCustomer = function(id) {
        window.location.href = pageData.urls.show.replace(':id', id);
    }

    // Edit customer
    window.editCustomer = function(id) {
        window.location.href = pageData.urls.edit.replace(':id', id);
    }

    // Toggle active status
    window.toggleActive = function(id) {
        Swal.fire({
            title: pageData.labels.confirmToggle,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: pageData.labels.yes,
            cancelButtonText: pageData.labels.cancel,
            customClass: {
                confirmButton: 'btn btn-primary me-2',
                cancelButton: 'btn btn-label-secondary'
            },
            buttonsStyling: false
        }).then(function(result) {
            if (result.isConfirmed) {
                $.ajax({
                    url: pageData.urls.toggleActive.replace(':id', id),
                    type: 'POST',
                    success: function(response) {
                        if (response.status === 'success') {
                            Swal.fire({
                                text: response.data.message || pageData.labels.statusUpdated,
                                icon: 'success',
                                customClass: {
                                    confirmButton: 'btn btn-success'
                                },
                                buttonsStyling: false
                            });
                            dt.ajax.reload();
                        }
                    },
                    error: function(xhr) {
                        let response = xhr.responseJSON;
                        Swal.fire({
                            text: response.data || pageData.labels.errorOccurred,
                            icon: 'error',
                            customClass: {
                                confirmButton: 'btn btn-danger'
                            },
                            buttonsStyling: false
                        });
                    }
                });
            }
        });
    }

    // Delete customer
    window.deleteCustomer = function(id) {
        Swal.fire({
            title: pageData.labels.confirmDelete,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: pageData.labels.delete,
            cancelButtonText: pageData.labels.cancel,
            customClass: {
                confirmButton: 'btn btn-danger me-2',
                cancelButton: 'btn btn-label-secondary'
            },
            buttonsStyling: false
        }).then(function(result) {
            if (result.isConfirmed) {
                $.ajax({
                    url: pageData.urls.destroy.replace(':id', id),
                    type: 'DELETE',
                    success: function(response) {
                        if (response.status === 'success') {
                            Swal.fire({
                                text: response.data.message || pageData.labels.deleted,
                                icon: 'success',
                                customClass: {
                                    confirmButton: 'btn btn-success'
                                },
                                buttonsStyling: false
                            });
                            dt.ajax.reload();
                        }
                    },
                    error: function(xhr) {
                        let response = xhr.responseJSON;
                        Swal.fire({
                            text: response.data || pageData.labels.errorOccurred,
                            icon: 'error',
                            customClass: {
                                confirmButton: 'btn btn-danger'
                            },
                            buttonsStyling: false
                        });
                    }
                });
            }
        });
    }

    // Reset filters
    window.resetFilters = function() {
        $('#filter-company').val('').trigger('change');
        $('#filter-customer-type').val('').trigger('change');
        $('#filter-status').val('').trigger('change');
        dt.ajax.reload();
    }

    // Initial load
    loadStatistics();
});
