// Global utility functions
const NIS = {
    // Format date to DD/MM/YYYY
    formatDate: function(dateString) {
        if (!dateString) return '';
        const date = new Date(dateString);
        return date.toLocaleDateString('en-GB');
    },
    
    // Format datetime
    formatDateTime: function(dateTimeString) {
        if (!dateTimeString) return '';
        const date = new Date(dateTimeString);
        return date.toLocaleString('en-GB');
    },
    
    // Show loading spinner
    showLoading: function(selector) {
        $(selector).html('<div class="text-center"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">Loading...</span></div></div>');
    },
    
    // Show success message
    showSuccess: function(message) {
        const alert = `
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <i class="fas fa-check-circle me-2"></i>
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        `;
        $('#content').prepend(alert);
        setTimeout(() => $('.alert').fadeOut(), 5000);
    },
    
    // Show error message
    showError: function(message) {
        const alert = `
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="fas fa-exclamation-circle me-2"></i>
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        `;
        $('#content').prepend(alert);
    },
    
    // Confirm action
    confirm: function(message, callback) {
        if (confirm(message)) {
            callback();
        }
    },
    
    // Validate email
    validateEmail: function(email) {
        const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return re.test(email);
    },
    
    // Validate phone (Nigerian format)
    validatePhone: function(phone) {
        const re = /^(\+234|0)[789][01]\d{8}$/;
        return re.test(phone);
    },
    
    // Format currency
    formatCurrency: function(amount) {
        return '₦' + parseFloat(amount).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
    },
    
    // Generate random string
    randomString: function(length = 10) {
        return Math.random().toString(36).substring(2, 2 + length);
    },
    
    // Copy to clipboard
    copyToClipboard: function(text) {
        navigator.clipboard.writeText(text).then(() => {
            this.showSuccess('Copied to clipboard');
        });
    },
    
    // Export table to CSV
    exportTableToCSV: function(tableId, filename) {
        const rows = document.querySelectorAll('#' + tableId + ' tr');
        const csv = [];
        
        for (const row of rows) {
            const cells = row.querySelectorAll('td, th');
            const rowData = [];
            for (const cell of cells) {
                rowData.push('"' + cell.innerText.replace(/"/g, '""') + '"');
            }
            csv.push(rowData.join(','));
        }
        
        const csvContent = csv.join('\n');
        const blob = new Blob([csvContent], { type: 'text/csv' });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = filename + '.csv';
        a.click();
    },
    
    // Print element
    printElement: function(elementId) {
        const printContent = document.getElementById(elementId).innerHTML;
        const originalContent = document.body.innerHTML;
        
        document.body.innerHTML = printContent;
        window.print();
        document.body.innerHTML = originalContent;
        location.reload();
    }
};

// Initialize tooltips
document.addEventListener('DOMContentLoaded', function() {
    // Enable Bootstrap tooltips
    const tooltips = document.querySelectorAll('[data-bs-toggle="tooltip"]');
    tooltips.forEach(tooltip => new bootstrap.Tooltip(tooltip));
    
    // Enable Bootstrap popovers
    const popovers = document.querySelectorAll('[data-bs-toggle="popover"]');
    popovers.forEach(popover => new bootstrap.Popover(popover));
});

// Handle AJAX errors globally
$(document).ajaxError(function(event, jqxhr, settings, error) {
    if (jqxhr.status === 401) {
        window.location.href = '/nis-migrant-ereg/login';
    } else if (jqxhr.status === 403) {
        NIS.showError('You do not have permission to perform this action');
    } else if (jqxhr.status === 404) {
        NIS.showError('Resource not found');
    } else if (jqxhr.status === 500) {
        NIS.showError('Server error occurred');
    } else {
        NIS.showError('An error occurred: ' + error);
    }
});

// Prevent double form submission
$('form').on('submit', function() {
    $(this).find('button[type="submit"]').prop('disabled', true);
});

// Auto-dismiss alerts
setTimeout(function() {
    $('.alert').fadeOut('slow');
}, 5000);