<?php
/**
 * modals.php - نظام المودالات المتقدم
 * @version 2.0.0
 */

// منع الوصول المباشر للملف
if (!defined('checkAdminAuth')) {
    exit('الوصول المباشر غير مسموح');
}
?>

<!-- ============================================ -->
<!-- نظام المودالات المتقدم مع حل مشكلة التمرير -->
<!-- ============================================ -->

<!-- مودال النجاح -->
<div class="modal fade" id="successModal" tabindex="-1" aria-labelledby="successModalLabel" aria-hidden="true" data-bs-backdrop="static">
    <div class="modal-dialog modal-dialog-centered modal-sm modal-dialog-scrollable">
        <div class="modal-content border-0 shadow-lg">
            <div class="modal-body text-center p-4">
                <div class="success-animation mb-3">
                    <div class="success-circle">
                        <i class="bi bi-check-circle-fill text-success" style="font-size: 4rem;"></i>
                    </div>
                </div>
                <h5 class="mb-3 fw-bold" id="successModalTitle">تم بنجاح!</h5>
                <p class="text-muted mb-4" id="successModalMessage" style="word-break: break-word;">تمت العملية بنجاح</p>
                <button type="button" class="btn btn-primary w-100 py-2" data-bs-dismiss="modal">
                    <i class="bi bi-check-lg me-2"></i>حسناً
                </button>
            </div>
        </div>
    </div>
</div>

<!-- مودال الخطأ -->
<div class="modal fade" id="errorModal" tabindex="-1" aria-labelledby="errorModalLabel" aria-hidden="true" data-bs-backdrop="static">
    <div class="modal-dialog modal-dialog-centered modal-sm modal-dialog-scrollable">
        <div class="modal-content border-0 shadow-lg">
            <div class="modal-body text-center p-4">
                <div class="error-animation mb-3">
                    <div class="error-circle">
                        <i class="bi bi-exclamation-triangle-fill text-danger" style="font-size: 4rem;"></i>
                    </div>
                </div>
                <h5 class="mb-3 fw-bold text-danger" id="errorModalTitle">خطأ!</h5>
                <p class="text-muted mb-4" id="errorModalMessage" style="word-break: break-word;">حدث خطأ غير متوقع</p>
                <button type="button" class="btn btn-danger w-100 py-2" data-bs-dismiss="modal">
                    <i class="bi bi-x-lg me-2"></i>إغلاق
                </button>
            </div>
        </div>
    </div>
</div>

<!-- مودال التحذير -->
<div class="modal fade" id="warningModal" tabindex="-1" aria-labelledby="warningModalLabel" aria-hidden="true" data-bs-backdrop="static">
    <div class="modal-dialog modal-dialog-centered modal-sm modal-dialog-scrollable">
        <div class="modal-content border-0 shadow-lg">
            <div class="modal-body text-center p-4">
                <div class="warning-animation mb-3">
                    <div class="warning-circle">
                        <i class="bi bi-exclamation-circle-fill text-warning" style="font-size: 4rem;"></i>
                    </div>
                </div>
                <h5 class="mb-3 fw-bold text-warning" id="warningModalTitle">تحذير!</h5>
                <p class="text-muted mb-4" id="warningModalMessage" style="word-break: break-word;">يرجى التحقق من البيانات</p>
                <button type="button" class="btn btn-warning w-100 py-2" data-bs-dismiss="modal">
                    <i class="bi bi-check-lg me-2"></i>موافق
                </button>
            </div>
        </div>
    </div>
</div>

<!-- مودال التأكيد -->
<div class="modal fade" id="confirmModal" tabindex="-1" aria-labelledby="confirmModalLabel" aria-hidden="true" data-bs-backdrop="static">
    <div class="modal-dialog modal-dialog-centered modal-sm modal-dialog-scrollable">
        <div class="modal-content border-0 shadow-lg">
            <div class="modal-body text-center p-4">
                <div class="confirm-animation mb-3">
                    <div class="confirm-circle">
                        <i class="bi bi-question-circle-fill text-primary" style="font-size: 4rem;"></i>
                    </div>
                </div>
                <h5 class="mb-3 fw-bold" id="confirmModalTitle">تأكيد العملية</h5>
                <p class="text-muted mb-4" id="confirmModalMessage" style="word-break: break-word;">هل أنت متأكد من العملية؟</p>
                <div class="d-flex gap-2">
                    <button type="button" class="btn btn-outline-secondary flex-fill py-2" data-bs-dismiss="modal">
                        <i class="bi bi-x-lg me-2"></i>إلغاء
                    </button>
                    <button type="button" class="btn btn-primary flex-fill py-2" id="confirmModalBtn">
                        <i class="bi bi-check-lg me-2"></i>تأكيد
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- مودال التحميل (بدون خلفية) -->
<div class="modal fade" id="loadingModal" tabindex="-1" aria-labelledby="loadingModalLabel" aria-hidden="true" data-bs-backdrop="static" data-bs-keyboard="false">
    <div class="modal-dialog modal-dialog-centered modal-sm">
        <div class="modal-content border-0 bg-transparent shadow-none">
            <div class="modal-body text-center">
                <div class="loading-spinner-custom">
                    <div class="spinner-border text-primary" style="width: 3.5rem; height: 3.5rem;" role="status">
                        <span class="visually-hidden">جاري التحميل...</span>
                    </div>
                </div>
                <p class="text-white mt-3 fw-bold" id="loadingModalMessage" style="text-shadow: 0 2px 4px rgba(0,0,0,0.3);">جاري التحميل...</p>
            </div>
        </div>
    </div>
</div>

<!-- مودال المعلومات -->
<div class="modal fade" id="infoModal" tabindex="-1" aria-labelledby="infoModalLabel" aria-hidden="true" data-bs-backdrop="static">
    <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
        <div class="modal-content border-0 shadow-lg">
            <div class="modal-header bg-info text-white">
                <h5 class="modal-title" id="infoModalLabel">
                    <i class="bi bi-info-circle-fill me-2"></i>
                    <span id="infoModalTitle">معلومات</span>
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-4">
                <p id="infoModalMessage" style="word-break: break-word;">محتوى المعلومات</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-info text-white" data-bs-dismiss="modal">حسناً</button>
            </div>
        </div>
    </div>
</div>

<!-- نظام التوست (إشعارات سريعة) -->
<div class="toast-container position-fixed top-0 start-50 translate-middle-x p-3" style="z-index: 9999; pointer-events: none;">
    <div id="liveToast" class="toast" role="alert" aria-live="assertive" aria-atomic="true" style="pointer-events: auto; min-width: 300px; max-width: 90%;">
        <div class="toast-header border-0" id="toastHeader">
            <i class="bi me-2" id="toastIcon"></i>
            <strong class="me-auto" id="toastTitle">إشعار</strong>
            <small>الآن</small>
            <button type="button" class="btn-close" data-bs-dismiss="toast"></button>
        </div>
        <div class="toast-body" id="toastMessage">
            رسالة الإشعار
        </div>
    </div>
</div>

<!-- ============================================ -->
<!-- CSS إضافي لحل مشاكل التمرير -->
<!-- ============================================ -->
<style>
/* ===== حل مشكلة التمرير في المودالات ===== */
.modal {
    overflow-y: auto !important;
    -webkit-overflow-scrolling: touch !important;
}

.modal-open {
    overflow: hidden !important;
    padding-right: 0 !important;
}

.modal-dialog {
    margin: 1.75rem auto !important;
    max-height: calc(100vh - 3.5rem) !important;
    display: flex !important;
    align-items: center;
}

.modal-dialog-scrollable {
    display: flex !important;
    max-height: calc(100vh - 3.5rem) !important;
}

.modal-dialog-scrollable .modal-content {
    max-height: calc(100vh - 3.5rem) !important;
    overflow: hidden !important;
}

.modal-dialog-scrollable .modal-body {
    overflow-y: auto !important;
    -webkit-overflow-scrolling: touch !important;
    max-height: 60vh !important;
}

.modal-content {
    border: none !important;
    border-radius: 20px !important;
    box-shadow: 0 20px 40px rgba(0,0,0,0.2) !important;
}

/* تحسينات للجوال */
@media (max-width: 576px) {
    .modal-dialog {
        margin: 0.5rem !important;
        min-height: calc(100vh - 1rem) !important;
        max-height: calc(100vh - 1rem) !important;
    }
    
    .modal-dialog-scrollable {
        max-height: calc(100vh - 1rem) !important;
    }
    
    .modal-dialog-scrollable .modal-content {
        max-height: calc(100vh - 1rem) !important;
    }
    
    .modal-dialog-scrollable .modal-body {
        max-height: 70vh !important;
    }
    
    .modal-content {
        border-radius: 15px !important;
    }
}

/* تحسينات للشاشات الصغيرة جداً */
@media (max-width: 360px) {
    .modal-dialog {
        margin: 0.25rem !important;
    }
    
    .modal-body {
        padding: 1rem !important;
    }
}

/* ===== أنيميشنات ===== */
@keyframes successPulse {
    0% { transform: scale(0.8); opacity: 0; }
    50% { transform: scale(1.1); }
    100% { transform: scale(1); opacity: 1; }
}

@keyframes errorShake {
    0%, 100% { transform: translateX(0); }
    25% { transform: translateX(-10px); }
    75% { transform: translateX(10px); }
}

@keyframes warningPulse {
    0% { transform: scale(1); }
    50% { transform: scale(1.1); }
    100% { transform: scale(1); }
}

.success-animation i {
    animation: successPulse 0.5s ease forwards;
}

.error-animation i {
    animation: errorShake 0.5s ease;
}

.warning-animation i {
    animation: warningPulse 1s infinite;
}

/* ===== تحسينات إضافية ===== */
.toast {
    backdrop-filter: blur(10px);
    -webkit-backdrop-filter: blur(10px);
    border: none !important;
    box-shadow: 0 10px 30px rgba(0,0,0,0.15) !important;
    border-radius: 15px !important;
}

.toast-header {
    border-radius: 15px 15px 0 0 !important;
    background: rgba(255,255,255,0.95) !important;
}

.toast-body {
    border-radius: 0 0 15px 15px !important;
    background: rgba(255,255,255,0.95) !important;
}

.loading-spinner-custom {
    display: inline-block;
    background: rgba(255,255,255,0.9);
    padding: 1.5rem;
    border-radius: 50%;
    box-shadow: 0 10px 30px rgba(0,0,0,0.2);
}

/* منع التمرير الخلفي */
body.modal-open {
    overflow: hidden;
    position: fixed;
    width: 100%;
}

/* تحسين التركيز */
.modal:focus {
    outline: none;
}

/* تحسين شريط التمرير */
.modal-body::-webkit-scrollbar {
    width: 5px;
}

.modal-body::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 10px;
}

.modal-body::-webkit-scrollbar-thumb {
    background: var(--primary);
    border-radius: 10px;
}

.modal-body::-webkit-scrollbar-thumb:hover {
    background: var(--primary-dark);
}
</style>

<!-- ============================================ -->
<!-- نظام المودالات المتقدم - JavaScript -->
<!-- ============================================ -->
<script>
/**
 * نظام المودالات المتقدم
 * حل مشاكل التمرير وتحسين الأداء
 */
const ModalSystem = (function() {
    
    // العناصر
    const elements = {
        successModal: document.getElementById('successModal'),
        errorModal: document.getElementById('errorModal'),
        warningModal: document.getElementById('warningModal'),
        confirmModal: document.getElementById('confirmModal'),
        loadingModal: document.getElementById('loadingModal'),
        infoModal: document.getElementById('infoModal')
    };
    
    // التأكد من وجود Bootstrap
    if (typeof bootstrap === 'undefined') {
        console.error('Bootstrap is not loaded!');
        return;
    }
    
    // إنشاء نسخ المودالات
    const modals = {
        success: elements.successModal ? new bootstrap.Modal(elements.successModal, { backdrop: 'static' }) : null,
        error: elements.errorModal ? new bootstrap.Modal(elements.errorModal, { backdrop: 'static' }) : null,
        warning: elements.warningModal ? new bootstrap.Modal(elements.warningModal, { backdrop: 'static' }) : null,
        confirm: elements.confirmModal ? new bootstrap.Modal(elements.confirmModal, { backdrop: 'static' }) : null,
        loading: elements.loadingModal ? new bootstrap.Modal(elements.loadingModal, { backdrop: 'static', keyboard: false }) : null,
        info: elements.infoModal ? new bootstrap.Modal(elements.infoModal, { backdrop: 'static' }) : null
    };
    
    // ========================================
    // دوال مساعدة للتحكم في التمرير
    // ========================================
    
    /**
     * منع تمرير الخلفية
     */
    function preventBodyScroll() {
        document.body.style.overflow = 'hidden';
        document.body.style.position = 'fixed';
        document.body.style.width = '100%';
        document.body.style.top = `-${window.scrollY}px`;
    }
    
    /**
     * السماح بتمرير الخلفية
     */
    function allowBodyScroll() {
        const scrollY = document.body.style.top;
        document.body.style.overflow = '';
        document.body.style.position = '';
        document.body.style.width = '';
        document.body.style.top = '';
        if (scrollY) {
            window.scrollTo(0, parseInt(scrollY || '0') * -1);
        }
    }
    
    /**
     * إظهار مودال مع التحكم في التمرير
     */
    function showModal(modal, options = {}) {
        if (!modal) return;
        
        // منع تمرير الخلفية
        preventBodyScroll();
        
        // إظهار المودال
        modal.show();
        
        // إضافة مستمع لإغلاق المودال
        const modalElement = modal._element;
        
        const onHidden = function() {
            allowBodyScroll();
            modalElement.removeEventListener('hidden.bs.modal', onHidden);
        };
        
        modalElement.addEventListener('hidden.bs.modal', onHidden);
        
        // تحسين التمرير داخل المودال
        const modalBody = modalElement.querySelector('.modal-body');
        if (modalBody) {
            modalBody.style.overflowY = 'auto';
            modalBody.style.maxHeight = '60vh';
        }
    }
    
    // ========================================
    // API عام
    // ========================================
    
    return {
        /**
         * إظهار مودال نجاح
         */
        success: function(message, title = 'تم بنجاح!') {
            if (!elements.successModal || !modals.success) return;
            
            document.getElementById('successModalTitle').textContent = title;
            document.getElementById('successModalMessage').textContent = message;
            
            showModal(modals.success);
            
            // إخفاء تلقائي بعد 3 ثواني
            setTimeout(() => {
                if (elements.successModal.classList.contains('show')) {
                    modals.success.hide();
                }
            }, 3000);
        },
        
        /**
         * إظهار مودال خطأ
         */
        error: function(message, title = 'خطأ!') {
            if (!elements.errorModal || !modals.error) return;
            
            document.getElementById('errorModalTitle').textContent = title;
            document.getElementById('errorModalMessage').textContent = message;
            
            showModal(modals.error);
        },
        
        /**
         * إظهار مودال تحذير
         */
        warning: function(message, title = 'تحذير!') {
            if (!elements.warningModal || !modals.warning) return;
            
            document.getElementById('warningModalTitle').textContent = title;
            document.getElementById('warningModalMessage').textContent = message;
            
            showModal(modals.warning);
        },
        
        /**
         * إظهار مودال تأكيد
         */
        confirm: function(message, callback, title = 'تأكيد العملية') {
            if (!elements.confirmModal || !modals.confirm) return;
            
            document.getElementById('confirmModalTitle').textContent = title;
            document.getElementById('confirmModalMessage').textContent = message;
            
            const confirmBtn = document.getElementById('confirmModalBtn');
            
            // إزالة المستمعين السابقين
            const newConfirmBtn = confirmBtn.cloneNode(true);
            confirmBtn.parentNode.replaceChild(newConfirmBtn, confirmBtn);
            
            // إضافة المستمع الجديد
            newConfirmBtn.addEventListener('click', function() {
                modals.confirm.hide();
                if (typeof callback === 'function') {
                    callback();
                }
            });
            
            showModal(modals.confirm);
        },
        
        /**
         * إظهار مودال تحميل
         */
        loading: function(message = 'جاري التحميل...') {
            if (!elements.loadingModal || !modals.loading) return;
            
            document.getElementById('loadingModalMessage').textContent = message;
            
            showModal(modals.loading);
            
            return modals.loading;
        },
        
        /**
         * إخفاء مودال تحميل
         */
        hideLoading: function() {
            if (modals.loading && elements.loadingModal.classList.contains('show')) {
                modals.loading.hide();
                allowBodyScroll();
            }
        },
        
        /**
         * إظهار مودال معلومات
         */
        info: function(message, title = 'معلومات') {
            if (!elements.infoModal || !modals.info) return;
            
            document.getElementById('infoModalTitle').textContent = title;
            document.getElementById('infoModalMessage').textContent = message;
            
            showModal(modals.info);
        },
        
        /**
         * إظهار توست
         */
        toast: function(message, title = 'إشعار', type = 'info', duration = 3000) {
            const toastEl = document.getElementById('liveToast');
            if (!toastEl) return;
            
            const toast = new bootstrap.Toast(toastEl, { delay: duration });
            
            document.getElementById('toastTitle').textContent = title;
            document.getElementById('toastMessage').textContent = message;
            
            const toastIcon = document.getElementById('toastIcon');
            const toastHeader = document.getElementById('toastHeader');
            
            // تعيين الأيقونة واللون حسب النوع
            switch(type) {
                case 'success':
                    toastIcon.className = 'bi bi-check-circle-fill text-success me-2';
                    toastHeader.className = 'toast-header bg-success text-white border-0';
                    break;
                case 'error':
                case 'danger':
                    toastIcon.className = 'bi bi-exclamation-triangle-fill text-danger me-2';
                    toastHeader.className = 'toast-header bg-danger text-white border-0';
                    break;
                case 'warning':
                    toastIcon.className = 'bi bi-exclamation-circle-fill text-warning me-2';
                    toastHeader.className = 'toast-header bg-warning text-white border-0';
                    break;
                default:
                    toastIcon.className = 'bi bi-info-circle-fill text-info me-2';
                    toastHeader.className = 'toast-header bg-info text-white border-0';
            }
            
            toast.show();
        },
        
        /**
         * إغلاق جميع المودالات
         */
        closeAll: function() {
            Object.values(modals).forEach(modal => {
                if (modal && modal._element.classList.contains('show')) {
                    modal.hide();
                }
            });
            allowBodyScroll();
        }
    };
})();

// ========================================
// اعتراض الدوال الأصلية
// ========================================

// اعتراض alert
const originalAlert = window.alert;
window.alert = function(message) {
    ModalSystem.warning(message);
};

// اعتراض confirm
const originalConfirm = window.confirm;
window.confirm = function(message) {
    return new Promise((resolve) => {
        ModalSystem.confirm(message, () => resolve(true));
    });
};

// ========================================
// إظهار رسائل الجلسة
// ========================================
document.addEventListener('DOMContentLoaded', function() {
    <?php if (isset($_SESSION['success_message'])): ?>
        ModalSystem.success('<?php echo addslashes($_SESSION['success_message']); ?>');
        <?php unset($_SESSION['success_message']); ?>
    <?php endif; ?>
    
    <?php if (isset($_SESSION['error_message'])): ?>
        ModalSystem.error('<?php echo addslashes($_SESSION['error_message']); ?>');
        <?php unset($_SESSION['error_message']); ?>
    <?php endif; ?>
    
    <?php if (isset($_SESSION['warning_message'])): ?>
        ModalSystem.warning('<?php echo addslashes($_SESSION['warning_message']); ?>');
        <?php unset($_SESSION['warning_message']); ?>
    <?php endif; ?>
    
    <?php if (isset($_SESSION['info_message'])): ?>
        ModalSystem.info('<?php echo addslashes($_SESSION['info_message']); ?>');
        <?php unset($_SESSION['info_message']); ?>
    <?php endif; ?>
});
</script>