/**
 * SalonPro X - Core Application Module
 * Application-wide utilities and common functions
 */

$(function() {
    'use strict';

    // Initialize all data-tables with sorting
    initDataTables();

    // Initialize all forms with AJAX submission
    initAjaxForms();

    // Initialize number formatting on input
    initNumberInputs();

    // Initialize file inputs with preview
    initFileInputs();
});

/**
 * Initialize data table sorting and searching
 */
function initDataTables() {
    $('.data-table').each(function() {
        const $table = $(this);
        const options = {
            pageLength: parseInt($table.data('page-length') || 20),
            ordering: true,
            searching: true,
            language: {
                search: '',
                searchPlaceholder: 'Search...',
                lengthMenu: 'Show _MENU_ entries',
                info: 'Showing _START_ to _END_ of _TOTAL_ entries',
                infoEmpty: 'No entries',
                infoFiltered: '(filtered from _MAX_ total entries)',
                zeroRecords: 'No matching records found'
            }
        };

        // Only apply if table has enough rows
        if ($table.find('tbody tr').length > 10) {
            try {
                $table.DataTable(options);
            } catch (e) {
                // DataTable not available, skip
            }
        }
    });
}

/**
 * Initialize forms that submit via AJAX
 */
function initAjaxForms() {
    $(document).on('submit', '.ajax-form', function(e) {
        e.preventDefault();
        const $form = $(this);
        const $submitBtn = $form.find('[type="submit"]');
        const originalText = $submitBtn.html();

        // Disable button
        $submitBtn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Processing...');

        $.ajax({
            url: $form.attr('action'),
            method: $form.attr('method') || 'POST',
            data: new FormData(this),
            processData: false,
            contentType: false,
            success: function(response) {
                if (response.success) {
                    if (response.message) {
                        showToast('success', response.message);
                    }
                    if (response.redirect) {
                        setTimeout(function() {
                            window.location.href = response.redirect;
                        }, 500);
                    }
                    if (response.reset) {
                        $form[0].reset();
                    }
                    $form.trigger('ajax:success', response);
                } else {
                    if (response.errors) {
                        displayFormErrors($form, response.errors);
                    }
                    if (response.message) {
                        showToast('error', response.message);
                    }
                    $form.trigger('ajax:error', response);
                }
            },
            error: function(xhr) {
                let message = 'An error occurred. Please try again.';
                if (xhr.responseJSON && xhr.responseJSON.message) {
                    message = xhr.responseJSON.message;
                }
                showToast('error', message);
                $form.trigger('ajax:error', xhr);
            },
            complete: function() {
                $submitBtn.prop('disabled', false).html(originalText);
            }
        });
    });
}

/**
 * Display form validation errors
 */
function displayFormErrors($form, errors) {
    $form.find('.is-invalid').removeClass('is-invalid');
    $form.find('.invalid-feedback').remove();

    $.each(errors, function(field, messages) {
        const $input = $form.find('[name="' + field + '"]');
        if ($input.length) {
            $input.addClass('is-invalid');
            const $feedback = $('<div class="invalid-feedback">' + messages[0] + '</div>');
            $input.after($feedback);
        }
    });
}

/**
 * Initialize number format inputs
 */
function initNumberInputs() {
    $(document).on('input', '.input-number', function() {
        const $el = $(this);
        let val = $el.val().replace(/[^0-9.]/g, '');
        $el.val(val);
    });
}

/**
 * Initialize file inputs with preview
 */
function initFileInputs() {
    $(document).on('change', '.input-file-preview', function() {
        const $el = $(this);
        const $preview = $($el.data('preview') || '#' + $el.attr('id') + '_preview');
        const file = this.files[0];

        if (file && $preview.length) {
            const reader = new FileReader();
            reader.onload = function(e) {
                $preview.attr('src', e.target.result).show();
            };
            reader.readAsDataURL(file);
        }
    });
}

/**
 * Show toast notification
 */
function showToast(type, message) {
    const iconMap = {
        success: 'fa-check-circle',
        error: 'fa-exclamation-circle',
        warning: 'fa-exclamation-triangle',
        info: 'fa-info-circle'
    };
    const icon = iconMap[type] || 'fa-info-circle';
    const bgClass = 'alert-' + (type === 'error' ? 'danger' : type);

    const toastHtml = '<div class="alert ' + bgClass + ' alert-dismissible fade show glass-alert animate-slide-down" style="position:fixed;top:80px;right:20px;z-index:9999;min-width:300px;max-width:400px;">' +
        '<i class="fas ' + icon + ' me-2"></i>' + message +
        '<button type="button" class="btn-close" data-bs-dismiss="alert"></button>' +
        '</div>';

    const $toast = $(toastHtml);
    $('body').append($toast);

    setTimeout(function() {
        $toast.fadeOut(300, function() { $(this).remove(); });
    }, 4000);
}

/**
 * Load content into a modal
 */
function loadModal(url, title, size) {
    SalonPro.showLoading('Loading...');

    $.ajax({
        url: url,
        method: 'GET',
        success: function(response) {
            let content = '';
            if (typeof response === 'object' && response.html) {
                content = response.html;
            } else if (typeof response === 'string') {
                content = response;
            }

            const modalId = 'dynamicModal';
            let $modal = $('#' + modalId);

            if (!$modal.length) {
                $modal = $('<div class="modal fade" id="' + modalId + '" tabindex="-1"></div>');
                $('body').append($modal);
            }

            $modal.html(
                '<div class="modal-dialog ' + (size ? 'modal-' + size : '') + '">' +
                '<div class="modal-content glass-card">' +
                '<div class="modal-header">' +
                '<h5 class="modal-title">' + (title || '') + '</h5>' +
                '<button type="button" class="btn-close" data-bs-dismiss="modal"></button>' +
                '</div>' +
                '<div class="modal-body">' + content + '</div>' +
                '</div></div>'
            );

            const modal = new bootstrap.Modal($modal[0]);
            modal.show();
            SalonPro.hideLoading();
        },
        error: function() {
            SalonPro.hideLoading();
            showToast('error', 'Failed to load content');
        }
    });
}

/**
 * Print window
 */
function printWindow(title) {
    const originalTitle = document.title;
    if (title) document.title = title;
    window.print();
    document.title = originalTitle;
}
