/**
 * Prince VIP System - Main JavaScript
 * نظام برنس VIP - ملف جافاسكريبت الرئيسي
 */

$(document).ready(function() {
    // ======= SIDEBAR TOGGLE =======
    $('.sidebar-toggle').on('click', function() {
        $('.sidebar').toggleClass('show');
        $('.sidebar-overlay').toggleClass('show');
    });
    
    $('.sidebar-overlay').on('click', function() {
        $('.sidebar').removeClass('show');
        $(this).removeClass('show');
    });
    
    // ======= NOTIFICATION TOGGLE =======
    $('.notification-btn').on('click', function(e) {
        e.stopPropagation();
        $('.notification-dropdown').toggleClass('show');
    });
    
    $(document).on('click', function() {
        $('.notification-dropdown').removeClass('show');
    });
    
    // ======= GLOBAL SEARCH =======
    let searchTimer;
    $('#globalSearch').on('input', function() {
        clearTimeout(searchTimer);
        const query = $(this).val();
        if (query.length < 2) {
            $('#searchResults').hide();
            return;
        }
        searchTimer = setTimeout(function() {
            $.ajax({
                url: 'ajax/search.php',
                method: 'POST',
                data: { query: query },
                dataType: 'json',
                success: function(data) {
                    displaySearchResults(data);
                }
            });
        }, 300);
    });
    
    // ======= TOOLTIPS =======
    $('[data-bs-toggle="tooltip"]').tooltip();
});

// ======= AJAX HELPER =======
function ajaxRequest(url, data, callback, method = 'POST') {
    $.ajax({
        url: url,
        method: method,
        data: data,
        dataType: 'json',
        beforeSend: function() {
            showLoading();
        },
        success: function(response) {
            hideLoading();
            if (callback) callback(response);
        },
        error: function(xhr) {
            hideLoading();
            showAlert('حدث خطأ في الاتصال بالخادم', 'danger');
            console.error(xhr.responseText);
        }
    });
}

// ======= FILE UPLOAD AJAX =======
function ajaxUpload(url, formData, callback) {
    $.ajax({
        url: url,
        method: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        dataType: 'json',
        beforeSend: function() {
            showLoading();
        },
        success: function(response) {
            hideLoading();
            if (callback) callback(response);
        },
        error: function(xhr) {
            hideLoading();
            showAlert('حدث خطأ في رفع الملف', 'danger');
            console.error(xhr.responseText);
        }
    });
}

// ======= LOADING =======
function showLoading() {
    if (!$('#loadingOverlay').length) {
        $('body').append('<div id="loadingOverlay" class="loading-overlay"><div class="spinner-gold"></div></div>');
    }
    $('#loadingOverlay').fadeIn(200);
}

function hideLoading() {
    $('#loadingOverlay').fadeOut(200);
}

// ======= ALERTS =======
function showAlert(message, type = 'success', duration = 4000) {
    const icons = {
        success: 'fas fa-check-circle',
        danger: 'fas fa-exclamation-circle',
        warning: 'fas fa-exclamation-triangle',
        info: 'fas fa-info-circle'
    };
    
    const alertHtml = `
        <div class="alert alert-${type} alert-custom alert-dismissible fade show position-fixed" 
             style="top:80px;left:50%;transform:translateX(-50%);z-index:9999;min-width:350px;max-width:500px;animation:fadeIn 0.3s ease;"
             role="alert">
            <i class="${icons[type]} me-2"></i>
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `;
    
    $('body').append(alertHtml);
    
    if (duration > 0) {
        setTimeout(function() {
            $('.alert-custom').fadeOut(300, function() { $(this).remove(); });
        }, duration);
    }
}

// ======= CONFIRM DIALOG =======
function confirmAction(message, callback) {
    if ($('#confirmModal').length === 0) {
        $('body').append(`
            <div class="modal fade" id="confirmModal" tabindex="-1">
                <div class="modal-dialog modal-dialog-centered modal-sm">
                    <div class="modal-content">
                        <div class="modal-body text-center p-4">
                            <i class="fas fa-question-circle text-warning" style="font-size:3rem;margin-bottom:15px;"></i>
                            <p class="confirm-message mb-0" style="font-weight:600;font-size:1rem;"></p>
                        </div>
                        <div class="modal-footer justify-content-center border-0 pt-0">
                            <button type="button" class="btn btn-secondary px-4" data-bs-dismiss="modal">إلغاء</button>
                            <button type="button" class="btn btn-gold px-4" id="confirmYes">نعم، تأكيد</button>
                        </div>
                    </div>
                </div>
            </div>
        `);
    }
    
    $('#confirmModal .confirm-message').text(message);
    const modal = new bootstrap.Modal('#confirmModal');
    modal.show();
    
    $('#confirmYes').off('click').on('click', function() {
        modal.hide();
        if (callback) callback();
    });
}

// ======= FORMAT DATE =======
function formatDate(dateStr) {
    if (!dateStr) return '-';
    const date = new Date(dateStr);
    return date.toLocaleDateString('ar-PS', { year: 'numeric', month: '2-digit', day: '2-digit' });
}

// ======= FORMAT CURRENCY =======
function formatCurrency(amount) {
    return parseFloat(amount || 0).toLocaleString('ar-PS', { minimumFractionDigits: 2 });
}

// ======= FILE PREVIEW =======
function previewFile(url) {
    const ext = url.split('.').pop().toLowerCase();
    if (['jpg', 'jpeg', 'png', 'gif'].includes(ext)) {
        window.open(url, '_blank');
    } else if (ext === 'pdf') {
        window.open(url, '_blank');
    }
}

// ======= PRINT ELEMENT =======
function printElement(elementId) {
    const content = document.getElementById(elementId).innerHTML;
    const printWindow = window.open('', '_blank');
    printWindow.document.write(`
        <html dir="rtl" lang="ar">
        <head>
            <meta charset="UTF-8">
            <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700;800&display=swap" rel="stylesheet">
            <style>
                body { font-family: 'Tajawal', sans-serif; direction: rtl; padding: 20px; }
                table { width: 100%; border-collapse: collapse; }
                th, td { border: 1px solid #ddd; padding: 8px; text-align: right; }
                th { background: #f0f0f0; }
            </style>
        </head>
        <body>${content}</body>
        </html>
    `);
    printWindow.document.close();
    printWindow.print();
}

// ======= DEBOUNCE =======
function debounce(func, wait) {
    let timeout;
    return function(...args) {
        clearTimeout(timeout);
        timeout = setTimeout(() => func.apply(this, args), wait);
    };
}

// ======= SEARCH RESULTS =======
function displaySearchResults(data) {
    // يتم تنفيذها حسب الحاجة
}
