// public/assets/js/toast-handler.js

// Function to show toast
function showToast(title, message, type = 'success') {
    // Determine icon and color
    let iconClass = 'fe fe-check-circle';
    let headerClass = 'text-success';

    if (type === 'error') {
        iconClass = 'fe fe-alert-circle';
        headerClass = 'text-danger';
    } else if (type === 'info') {
        iconClass = 'fe fe-info';
        headerClass = 'text-primary';
    }

    // Create Toast Container if not exists
    let container = document.getElementById('toast-container');
    if (!container) {
        container = document.createElement('div');
        container.id = 'toast-container';
        container.className = 'toast-container position-fixed bottom-0 end-0 p-3';
        container.style.zIndex = '9999'; // High z-index to ensure visibility
        document.body.appendChild(container);
    }

    // Create Toast HTML
    let toastId = 'toast-' + Date.now();
    let toastHtml = `
        <div id="${toastId}" class="toast bg-white" role="alert" aria-live="assertive" aria-atomic="true">
            <div class="toast-header ${headerClass}">
                <i class="${iconClass} me-2"></i>
                <strong class="me-auto">${title}</strong>
                <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
            </div>
            <div class="toast-body text-dark">
                ${message}
            </div>
        </div>
    `;

    // Append to container
    let tempDiv = document.createElement('div');
    tempDiv.innerHTML = toastHtml;
    let toastElement = tempDiv.firstElementChild;
    container.appendChild(toastElement);

    // Initialize and Show
    if (typeof bootstrap !== 'undefined' && bootstrap.Toast) {
        let toast = new bootstrap.Toast(toastElement, { delay: 5000 });
        toast.show();
    } else {
        // Fallback or manual show
        toastElement.classList.add('show');
        setTimeout(() => toastElement.remove(), 5000);
    }

    // Clean up after hidden
    toastElement.addEventListener('hidden.bs.toast', function () {
        toastElement.remove();
    });
}

// Global AJAX Form Handler for Send SMS
$(document).ready(function () {
    $(document).on('submit', '#sendSmsForm', function (e) {
        e.preventDefault();

        let form = $(this);
        let submitBtn = form.find('button[type="submit"]');
        let originalBtnText = submitBtn.text();

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

        $.ajax({
            url: form.attr('action'),
            type: 'POST',
            data: form.serialize(),
            dataType: 'json',
            success: function (response) {
                if (response.status === 'success') {
                    showToast('Success', response.message, 'success');
                    form[0].reset();

                    // If inside a modal, close it
                    let modal = form.closest('.modal');
                    if (modal.length) {
                        try {
                            let bsModal = bootstrap.Modal.getInstance(modal[0]);
                            if (bsModal) {
                                bsModal.hide();
                            } else {
                                modal.modal('hide');
                            }
                        } catch (err) {
                            modal.modal('hide'); // Fallback
                        }
                    }
                } else {
                    showToast('Error', response.message, 'error');
                }
            },
            error: function (xhr, status, error) {
                let msg = 'An error occurred.';
                if (xhr.responseJSON && xhr.responseJSON.message) {
                    msg = xhr.responseJSON.message;
                }
                showToast('System Error', msg, 'error');
            },
            complete: function () {
                // Reset button
                submitBtn.prop('disabled', false).text(originalBtnText);
            }
        });
    });
});
