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

// Loader
window.Loader = {
    show() { $('#global-loader').show(); },
    hide() { $('#global-loader').hide(); }
};

$(document).ready(function () {
    $('#global-loader').hide();
});

$(document).ajaxStart(() => Loader.show());
$(document).ajaxStop(() => Loader.hide());

// DataTable helper
window.initDataTable = function (selector, options) {
    return $(selector).DataTable({
        processing: true,
        serverSide: true,
        responsive: true,
        ...options
    });
};

// SweetAlert helpers (dark theme styled)
window.Alert = {
    success(msg, onOk = null) {
        Swal.fire({
            icon: 'success',
            title: 'Success',
            text: msg,
            confirmButtonText: 'OK',
            background: '#1e2030',
            color: '#e2e8f0',
            confirmButtonColor: '#2dd4bf',
            iconColor: '#2dd4bf'
        }).then(() => {
            if (typeof onOk === 'function') onOk();
        });
    },
    error(msg) {
        Swal.fire({
            icon: 'error',
            title: 'Error',
            text: msg,
            background: '#1e2030',
            color: '#e2e8f0',
            confirmButtonColor: '#2dd4bf',
            iconColor: '#f87171'
        });
    },
    confirm(msg, onYes) {
        Swal.fire({
            icon: 'warning',
            title: 'Confirm',
            text: msg,
            showCancelButton: true,
            confirmButtonText: 'Yes',
            cancelButtonText: 'No',
            background: '#1e2030',
            color: '#e2e8f0',
            confirmButtonColor: '#dc2626',
            cancelButtonColor: '#374151',
            iconColor: '#ca8a04'
        }).then(res => res.isConfirmed && onYes());
    },
    validation(errors) {
        let html = '';
        $.each(errors, function (_, msgs) {
            msgs.forEach(m => html += `<div style="color:#f87171;text-align:left">• ${m}</div>`);
        });
        Swal.fire({
            icon: 'error',
            title: 'Validation Error',
            html,
            background: '#1e2030',
            color: '#e2e8f0',
            confirmButtonColor: '#2dd4bf'
        });
    }
};

/*
 * ============================================
 *  CRUD Modal Manager
 *  Usage in blade:
 *    <script>
 *    $(document).ready(function () {
 *        CrudModal.init({
 *            modalId: 'crudModal',
 *            formId: 'crudForm',
 *            tableId: 'dataTable',
 *            storeUrl: '/core/currencies',
 *            updateUrl: '/core/currencies/{id}',
 *            defaultChecked: ['status']   // checkboxes checked by default on reset
 *        });
 *    });
 *    </script>
 * ============================================
 */
window.CrudModal = {
    init(config) {
        const modal = bootstrap.Modal.getOrCreateInstance($('#' + config.modalId));
        let currentId = null;
        let table = null;

        if (config.tableId) {
            table = $('#' + config.tableId).DataTable();
        }

        // CREATE button
        $(document).on('click', '#btn-create-' + config.modalId, function () {
            currentId = null;
            $('#' + config.modalId + ' .modal-title').text($(this).data('title') || 'Create');
            $('#' + config.modalId + ' .btn-save').text('Save');
            resetForm();
            modal.show();
        });

        // EDIT button (data-record is JSON of the row)
        $(document).on('click', '.btn-edit-' + config.modalId, function () {
            currentId = $(this).data('id');
            const record = $(this).data('record');
            $('#' + config.modalId + ' .modal-title').text($(this).data('title') || 'Edit');
            $('#' + config.modalId + ' .btn-save').text('Update');

            if (record) {
                const obj = typeof record === 'string' ? JSON.parse(record) : record;
                $.each(obj, function (key, val) {
                    const el = $('#' + config.formId + ' [name="' + key + '"]');
                    if (el.is('input[type="checkbox"]')) {
                        el.prop('checked', val == 1 || val === true || val === '1');
                    } else if (el.length) {
                        el.val(val !== null && val !== undefined ? val : '');
                    }
                });
            }
            modal.show();
        });

        // Form submit (Create or Update)
        $('#' + config.formId).on('submit', function (e) {
            e.preventDefault();
            const btn = $('#' + config.modalId + ' .btn-save');
            if (btn.prop('disabled')) return; // double-submit prevention
            btn.prop('disabled', true).addClass('opacity-50');

            const url = currentId
                ? config.updateUrl.replace('{id}', currentId)
                : config.storeUrl;
            const method = currentId ? 'PUT' : 'POST';

            $.ajax({
                url: url,
                type: method,
                data: $(this).serialize(),
                success: function (res) {
                    btn.prop('disabled', false).removeClass('opacity-50');
                    Alert.success(res.message || 'Saved successfully', function () {
                        modal.hide();
                        if (table) table.ajax.reload();
                    });
                },
                error: function (xhr) {
                    btn.prop('disabled', false).removeClass('opacity-50');
                    if (xhr.status === 422) {
                        Alert.validation(xhr.responseJSON.errors);
                    } else {
                        Alert.error(xhr.responseJSON?.message || 'Something went wrong');
                    }
                }
            });
        });

        // DELETE button
        $(document).on('click', '.btn-delete-' + config.modalId, function () {
            const id = $(this).data('id');
            const url = config.updateUrl.replace('{id}', id);

            Alert.confirm('Are you sure? This action cannot be undone.', function () {
                $.ajax({
                    url: url,
                    type: 'DELETE',
                    success: function (res) {
                        Alert.success(res.message || 'Deleted successfully', function () {
                            if (table) table.ajax.reload();
                        });
                    },
                    error: function (xhr) {
                        Alert.error(xhr.responseJSON?.message || 'Error deleting record');
                    }
                });
            });
        });

        // Reset form when modal closes
        $('#' + config.modalId).on('hidden.bs.modal', function () {
            resetForm();
        });

        function resetForm() {
            $('#' + config.formId)[0].reset();
            // Re-check default checkboxes (e.g. status)
            if (config.defaultChecked) {
                config.defaultChecked.forEach(function (field) {
                    $('#' + config.formId + ' [name="' + field + '"]').prop('checked', true);
                });
            }
        }
    }
};
