// Business Logic and Database Operations for System Settings Page

function escapeHTML(str) {
    if (str === null || str === undefined) return '';
    return String(str)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
}

// -------------------------------------------------------------
// 1. Default Settings Seeding & State
// -------------------------------------------------------------
const DEFAULT_SETTINGS = {
    orgName: "شركة الراية للخدمات واللوجستيات",
    orgEmail: "info@alraaya.com",
    currency: "د.ع",
    maxDailyExpense: 5000000.00,
    lowBalanceThreshold: 1000000.00,
    workDayStartHour: 5,
    workDayEndHour: 17
};

let currentSettings = {};

// -------------------------------------------------------------
// 2. DOM Selection
// -------------------------------------------------------------
const dom = {
    // General Inputs
    orgNameInput: document.getElementById("settings-org-name"),
    orgEmailInput: document.getElementById("settings-org-email"),
    currencySelect: document.getElementById("settings-currency"),
    usernameInput: document.getElementById("settings-username"),
    passwordInput: document.getElementById("settings-password"),
    btnToggleSettingsPassword: document.getElementById("btn-toggle-settings-password"),
    settingsPasswordToggleIcon: document.getElementById("settings-password-toggle-icon"),
    
    // Policy Inputs
    maxExpenseInput: document.getElementById("settings-max-expense"),
    lowBalanceInput: document.getElementById("settings-low-balance"),
    workDayStartSelect: document.getElementById("settings-workday-start"),
    workDayEndSelect: document.getElementById("settings-workday-end"),
    
    // Metrics Cards
    metricForms: document.getElementById("metric-forms"),
    metricMaterials: document.getElementById("metric-materials"),
    metricGatherers: document.getElementById("metric-gatherers"),

    // Forms
    settingsForm: document.getElementById("settings-form"),
    
    // Validation Errors
    orgNameError: document.getElementById("org-name-error"),
    orgEmailError: document.getElementById("org-email-error"),
    maxExpenseError: document.getElementById("max-expense-error"),
    lowBalanceError: document.getElementById("low-balance-error"),
    
    // Backup & Restore Actions
    btnBackup: document.getElementById("btn-backup"),
    btnTriggerRestore: document.getElementById("btn-trigger-restore"),
    restoreFileInput: document.getElementById("restore-file-input"),
    btnShiftReset: document.getElementById("btn-shift-reset"),
    btnFactoryReset: document.getElementById("btn-factory-reset"),
    
    // Shift Reset Modal
    shiftResetModal: document.getElementById("shift-reset-modal"),
    cancelShiftResetBtn: document.getElementById("cancel-shift-reset-btn"),
    confirmShiftResetBtn: document.getElementById("confirm-shift-reset-btn"),

    // Factory Reset Modal
    resetConfirmModal: document.getElementById("reset-confirm-modal"),
    cancelResetBtn: document.getElementById("cancel-reset-btn"),
    confirmResetBtn: document.getElementById("confirm-reset-btn"),
    
    // Theme Toggle
    themeToggle: document.getElementById("theme-toggle"),
    
    // Toast Container
    toastContainer: document.getElementById("toast-container")
};

// -------------------------------------------------------------
// 3. Initialization
// -------------------------------------------------------------
function initSettings() {
    loadSettings();
    initTheme();
    setupEventListeners();
    loadSavedBackupsList();
}

if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", initSettings);
} else {
    initSettings();
}

// Load settings and live system metrics from database
function loadSettings() {
    fetch('api/settings.php?action=get')
        .then(r => r.json())
        .then(res => {
            if (res.status === 'success' && res.settings) {
                currentSettings = res.settings;
                
                // Populate metrics KPI cards
                if (res.metrics) {
                    if (dom.metricForms) dom.metricForms.textContent = res.metrics.forms || 0;
                    if (dom.metricMaterials) dom.metricMaterials.textContent = res.metrics.materials || 0;
                    if (dom.metricGatherers) dom.metricGatherers.textContent = res.metrics.gatherers || 0;
                }
            } else {
                currentSettings = { ...DEFAULT_SETTINGS };
            }
            saveSettingsToLocal();
            
            // Populate form fields
            dom.orgNameInput.value = currentSettings.orgName || "";
            dom.orgEmailInput.value = currentSettings.orgEmail || "";
            dom.currencySelect.value = "د.ع";
            dom.maxExpenseInput.value = currentSettings.maxDailyExpense || 5000000;
            dom.lowBalanceInput.value = currentSettings.lowBalanceThreshold || 1000000;
            dom.workDayStartSelect.value = currentSettings.workDayStartHour !== undefined ? currentSettings.workDayStartHour : 5;
            if (dom.workDayEndSelect) dom.workDayEndSelect.value = currentSettings.workDayEndHour !== undefined ? currentSettings.workDayEndHour : 17;
            if (dom.usernameInput) dom.usernameInput.value = currentSettings.username || localStorage.getItem("dashboard_username") || "admin";

            if (currentSettings.headerBanner) {
                localStorage.setItem("header_banner_path", currentSettings.headerBanner);
                const previewImg = document.getElementById("banner-preview-img");
                if (previewImg) previewImg.src = currentSettings.headerBanner;
            }
        })
        .catch(() => {
            // Local fallback
            const localSettings = localStorage.getItem("dashboard_settings");
            if (localSettings) {
                currentSettings = JSON.parse(localSettings);
            } else {
                currentSettings = { ...DEFAULT_SETTINGS };
            }
            dom.orgNameInput.value = currentSettings.orgName;
            dom.orgEmailInput.value = currentSettings.orgEmail;
            dom.currencySelect.value = "د.ع";
            dom.maxExpenseInput.value = currentSettings.maxDailyExpense;
            dom.lowBalanceInput.value = currentSettings.lowBalanceThreshold;
            dom.workDayStartSelect.value = currentSettings.workDayStartHour;
            if (dom.workDayEndSelect) dom.workDayEndSelect.value = currentSettings.workDayEndHour !== undefined ? currentSettings.workDayEndHour : 17;
            if (dom.usernameInput) dom.usernameInput.value = localStorage.getItem("dashboard_username") || "admin";
        });
}

// Save state to LocalStorage
function saveSettingsToLocal() {
    localStorage.setItem("dashboard_settings", JSON.stringify(currentSettings));
}

// -------------------------------------------------------------
// 4. Toast Notifications
// -------------------------------------------------------------
function showToast(message, type = "success") {
    const toast = document.createElement("div");
    toast.className = `toast toast-${type}`;
    
    let iconClass = "fa-circle-check";
    if (type === "danger") iconClass = "fa-circle-xmark";
    if (type === "warning") iconClass = "fa-circle-exclamation";
    if (type === "info") iconClass = "fa-circle-info";
    
    toast.innerHTML = `
        <i class="fa-solid ${iconClass} toast-icon"></i>
        <span class="toast-message">${message}</span>
    `;
    
    dom.toastContainer.appendChild(toast);
    
    setTimeout(() => {
        toast.remove();
    }, 3000);
}

// -------------------------------------------------------------
// 5. Theme Settings Integration
// -------------------------------------------------------------
function initTheme() {
    const savedTheme = localStorage.getItem("dashboard_theme");
    if (savedTheme === "dark") {
        document.body.classList.add("dark-theme");
        if (dom.themeToggle) dom.themeToggle.innerHTML = '<i class="fa-solid fa-sun"></i>';
    } else {
        document.body.classList.remove("dark-theme");
        if (dom.themeToggle) dom.themeToggle.innerHTML = '<i class="fa-solid fa-moon"></i>';
    }
}

function toggleTheme() {
    if (document.body.classList.contains("dark-theme")) {
        document.body.classList.remove("dark-theme");
        if (dom.themeToggle) dom.themeToggle.innerHTML = '<i class="fa-solid fa-moon"></i>';
        localStorage.setItem("dashboard_theme", "light");
        showToast("تم تفعيل الوضع المضيء", "info");
    } else {
        document.body.classList.add("dark-theme");
        if (dom.themeToggle) dom.themeToggle.innerHTML = '<i class="fa-solid fa-sun"></i>';
        localStorage.setItem("dashboard_theme", "dark");
        showToast("تم تفعيل الوضع الداكن", "info");
    }
}

// -------------------------------------------------------------
// 6. Form Submission & Validation
// -------------------------------------------------------------
function clearValidationErrors() {
    document.querySelectorAll(".form-group").forEach(el => {
        el.classList.remove("has-error");
    });
}

function setErrorGroup(el) {
    if (el) {
        const grp = el.closest(".form-group");
        if (grp) grp.classList.add("has-error");
    }
}

function validateSettingsForm(orgName, orgEmail, maxExpense, lowBalance, username, password) {
    let isValid = true;
    clearValidationErrors();

    const orgNameInput = document.getElementById("settings-org-name");
    const orgEmailInput = document.getElementById("settings-org-email");
    const maxExpenseInput = document.getElementById("settings-max-expense");
    const lowBalanceInput = document.getElementById("settings-low-balance");
    const usernameInput = document.getElementById("settings-username");
    const passwordInput = document.getElementById("settings-password");

    // Org Name Validation
    if (!orgName || orgName.trim().length < 3) {
        setErrorGroup(orgNameInput);
        isValid = false;
    }

    // Email format validation
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!orgEmail || !emailRegex.test(orgEmail.trim())) {
        setErrorGroup(orgEmailInput);
        isValid = false;
    }

    // Max Expense limits
    if (isNaN(maxExpense) || maxExpense <= 0) {
        setErrorGroup(maxExpenseInput);
        isValid = false;
    }

    // Low Balance Warning limit
    if (isNaN(lowBalance) || lowBalance <= 0) {
        setErrorGroup(lowBalanceInput);
        isValid = false;
    }

    // Username validation
    if (!username || username.trim().length < 3) {
        setErrorGroup(usernameInput);
        isValid = false;
    }

    // Password validation (only if filled)
    if (password && password.trim().length < 4) {
        setErrorGroup(passwordInput);
        isValid = false;
    }

    return isValid;
}

window.saveSettingsNow = function(e) {
    if (e && typeof e.preventDefault === 'function') {
        e.preventDefault();
    }
    handleFormSubmit(e);
};

function handleFormSubmit(e) {
    if (e && typeof e.preventDefault === 'function') {
        e.preventDefault();
    }

    const orgNameInput = document.getElementById("settings-org-name");
    const orgEmailInput = document.getElementById("settings-org-email");
    const maxExpenseInput = document.getElementById("settings-max-expense");
    const lowBalanceInput = document.getElementById("settings-low-balance");
    const workDayStartSelect = document.getElementById("settings-workday-start");
    const workDayEndSelect = document.getElementById("settings-workday-end");
    const usernameInput = document.getElementById("settings-username");
    const passwordInput = document.getElementById("settings-password");

    const orgName = orgNameInput ? orgNameInput.value.trim() : "";
    const orgEmail = orgEmailInput ? orgEmailInput.value.trim() : "";
    const currency = "د.ع"; // Always force Iraqi Dinar
    const maxExpense = maxExpenseInput ? parseFloat(maxExpenseInput.value) : 0;
    const lowBalance = lowBalanceInput ? parseFloat(lowBalanceInput.value) : 0;
    const workdayStartHour = workDayStartSelect ? parseInt(workDayStartSelect.value) : 5;
    const workdayEndHour = workDayEndSelect ? parseInt(workDayEndSelect.value) : 17;
    const username = usernameInput ? usernameInput.value.trim() : "";
    const password = passwordInput ? passwordInput.value.trim() : "";

    if (!validateSettingsForm(orgName, orgEmail, maxExpense, lowBalance, username, password)) {
        showToast("فشل الحفظ: يرجى إكمال الحقول والتأكد من البيانات أدناه", "danger");
        return;
    }

    // Update settings object
    currentSettings = {
        orgName,
        orgEmail,
        currency,
        maxDailyExpense: maxExpense,
        lowBalanceThreshold: lowBalance,
        workDayStartHour: workdayStartHour,
        workDayEndHour: workdayEndHour,
        username,
        password
    };

    // Save to database & users table
    fetch('api/settings.php?action=save', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(currentSettings)
    })
    .then(r => r.json())
    .then(res => {
        if (res.status === 'success') {
            saveSettingsToLocal();
            localStorage.setItem("dashboard_username", username);
            showToast("تم حفظ جميع إعدادات النظام وحساب المستخدم بنجاح!");
            if (passwordInput) passwordInput.value = "";
        } else {
            showToast("فشل حفظ الإعدادات: " + (res.message || ""), "danger");
        }
    })
    .catch(() => {
        showToast("فشل الاتصال بالخادم لحفظ الإعدادات", "danger");
    });
}

// -------------------------------------------------------------
// 7. Database Backups: Export JSON & Server Auto-Backups
// -------------------------------------------------------------
window.loadSavedBackupsList = function() {
    const container = document.getElementById("saved-backups-container");
    if (!container) return;

    fetch('api/settings.php?action=list_backups')
        .then(r => r.text())
        .then(text => {
            let res;
            try {
                res = JSON.parse(text);
            } catch (e) {
                console.error("JSON Parse Error in list_backups:", text);
                container.innerHTML = `<p style="font-size:12px; color:var(--danger); text-align:center; padding:10px;">استجابة السيرفر غير صالحة. (${escapeHTML(text.substring(0, 80))})</p>`;
                return;
            }

            if (res.status !== 'success') {
                container.innerHTML = `<p style="font-size:12px; color:var(--danger); text-align:center; padding:10px;">${escapeHTML(res.message || 'فشل جلب قائمة النسخ الاحتياطية')}</p>`;
                return;
            }
            if (!res.data || res.data.length === 0) {
                container.innerHTML = `<p style="font-size:12px; color:var(--text-muted); text-align:center; padding:10px;">لا توجد نسخ احتياطية محفوظة بالسيرفر حالياً.</p>`;
                return;
            }

            let rows = res.data.map(item => `
                <div style="display:flex; justify-content:space-between; align-items:center; padding:6px 10px; border-bottom:1px solid var(--border-color); font-size:12px;">
                    <div>
                        <strong style="color:var(--text-primary);">${escapeHTML(item.filename)}</strong>
                        <span style="font-size:10px; color:var(--primary); background:rgba(59,130,246,0.1); padding:1px 6px; border-radius:10px; margin-right:6px;">${escapeHTML(item.type)}</span>
                        <div style="font-size:10px; color:var(--text-muted);">${escapeHTML(item.date)} • ${escapeHTML(item.size)}</div>
                    </div>
                    <div style="display:flex; gap:5px;">
                        <a href="api/settings.php?action=download_backup_file&filename=${encodeURIComponent(item.filename)}" class="btn btn-secondary-outline" style="padding:2px 8px; font-size:11px;" title="تحميل الملف">
                            <i class="fa-solid fa-download"></i>
                        </a>
                        <button type="button" onclick="window.restoreSavedBackup('${escapeHTML(item.filename)}')" class="btn" style="padding:2px 8px; font-size:11px; background:#3b82f6; color:white; border:none;" title="استعادة هذه النسخة">
                            <i class="fa-solid fa-rotate-left"></i>
                        </button>
                        <button type="button" onclick="window.deleteSavedBackup('${escapeHTML(item.filename)}')" class="btn" style="padding:2px 8px; font-size:11px; background:#ef4444; color:white; border:none;" title="حذف الملف">
                            <i class="fa-solid fa-trash"></i>
                        </button>
                    </div>
                </div>
            `).join("");

            container.innerHTML = rows;
        })
        .catch(err => {
            console.error("loadSavedBackupsList fetch error:", err);
            const msg = (err && err.message) ? err.message : 'فشل الاتصال بالسيرفر لجلب القائمة.';
            container.innerHTML = `<p style="font-size:12px; color:var(--danger); text-align:center; padding:10px;">${escapeHTML(msg)}</p>`;
        });
};

window.triggerAutoBackupNow = function() {
    showToast("جاري إنشاء نسخة احتياطية تلقائية جديدة...", "info");
    fetch('api/settings.php?action=trigger_auto_backup')
        .then(r => r.json())
        .then(res => {
            if (res.status === 'success') {
                showToast(res.message, "success");
                loadSavedBackupsList();
            } else {
                showToast(res.message || "فشل إنشاء النسخة التلقائية", "danger");
            }
        })
        .catch(() => showToast("فشل الاتصال بالخادم", "danger"));
};

window.restoreSavedBackup = function(filename) {
    if (!confirm(`هل أنت تأكد من رغبتك في استعادة البيانات من النسخة الاحتياطية المحفوظة: ${filename}؟\nسيتم دمج وتعين البيانات الحالية بأمان.`)) {
        return;
    }
    showToast("جاري استعادة البيانات من النسخة الاحتياطية...", "info");
    fetch('api/settings.php?action=restore_saved_backup', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ filename })
    })
    .then(r => r.json())
    .then(res => {
        if (res.status === 'success') {
            showToast(res.message, "success");
            setTimeout(() => location.reload(), 1500);
        } else {
            showToast(res.message || "فشلت استعادة البيانات", "danger");
        }
    })
    .catch(() => showToast("فشل الاتصال بالخادم للاستعادة", "danger"));
};

window.deleteSavedBackup = function(filename) {
    if (!confirm(`هل أنت متاكد من حذف ملف النسخة الاحتياطية: ${filename}؟`)) return;
    fetch('api/settings.php?action=delete_backup_file', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ filename })
    })
    .then(r => r.json())
    .then(res => {
        if (res.status === 'success') {
            showToast(res.message, "success");
            loadSavedBackupsList();
        } else {
            showToast(res.message || "فشل حذف الملف", "danger");
        }
    })
    .catch(() => showToast("فشل الاتصال بالخادم", "danger"));
};

function downloadBackupJSON() {
    return fetch('api/settings.php?action=backup_db')
        .then(r => r.json())
        .then(res => {
            if (res.status === 'success' && res.data) {
                const jsonString = JSON.stringify(res.data, null, 4);
                const blob = new Blob([jsonString], { type: "application/json" });
                const url = URL.createObjectURL(blob);
                const link = document.createElement("a");
                const today = new Date().toISOString().split('T')[0];
                link.href = url;
                link.download = `mysql_backup_${today}.json`;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                URL.revokeObjectURL(url);
                showToast("تم تنزيل النسخة الاحتياطية لقاعدة البيانات بنجاح!");
                return true;
            } else {
                showToast("فشل تحميل البيانات من السيرفر: " + res.message, "danger");
                return false;
            }
        })
        .catch(() => {
            showToast("فشل الاتصال بالسيرفر لتنزيل النسخة الاحتياطية", "danger");
            return false;
        });
}

// -------------------------------------------------------------
// 8. Database Backups: Restore JSON
// -------------------------------------------------------------
function triggerFileRestore() {
    dom.restoreFileInput.click();
}

function handleFileRestore(e) {
    const file = e.target.files[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = function(evt) {
        try {
            const parsedData = JSON.parse(evt.target.result);
            
            // Send to server to write to database
            fetch('api/settings.php?action=restore_db', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ data: parsedData })
            })
            .then(r => r.json())
            .then(res => {
                if (res.status === 'success') {
                    showToast("تم استعادة قاعدة بيانات السيرفر بنجاح! جاري تحديث الصفحة...", "success");
                    dom.restoreFileInput.value = "";
                    setTimeout(() => {
                        window.location.reload();
                    }, 1500);
                } else {
                    showToast("فشلت الاستعادة: " + res.message, "danger");
                    dom.restoreFileInput.value = "";
                }
            })
            .catch(() => {
                showToast("فشل الاتصال بالسيرفر لاستعادة البيانات", "danger");
                dom.restoreFileInput.value = "";
            });
        } catch (err) {
            showToast("فشل قراءة الملف: البيانات المرفوعة ليست بصيغة JSON صالحة!", "danger");
            dom.restoreFileInput.value = "";
        }
    };
    reader.readAsText(file);
}

// -------------------------------------------------------------
// 9. Reset Operations (Shift & Factory)
// -------------------------------------------------------------
function openShiftResetModal() {
    if (dom.shiftResetModal) dom.shiftResetModal.classList.add("open");
}

function closeShiftResetModal() {
    if (dom.shiftResetModal) dom.shiftResetModal.classList.remove("open");
}

function executeShiftReset() {
    fetch('api/settings.php?action=reset_transactions_only', { method: 'POST' })
        .then(r => r.json())
        .then(res => {
            if (res.status === 'success') {
                showToast("تم تصفير حركات الوردية والطلبات بنجاح مع الحفاظ على دليل المواد والجلابين!", "success");
                closeShiftResetModal();
                loadSettings();
            } else {
                showToast("فشلت عملية تصفير الوردية: " + res.message, "danger");
                closeShiftResetModal();
            }
        })
        .catch(() => {
            showToast("فشل الاتصال بالسيرفر لتنفيذ تصفير الوردية", "danger");
            closeShiftResetModal();
        });
}

function openResetModal() {
    if (dom.resetConfirmModal) dom.resetConfirmModal.classList.add("open");
}

function closeResetModal() {
    if (dom.resetConfirmModal) dom.resetConfirmModal.classList.remove("open");
}

function executeFactoryReset() {
    // Automatically trigger safety backup first!
    downloadBackupJSON();

    setTimeout(() => {
        fetch('api/settings.php?action=factory_reset_db', { method: 'POST' })
            .then(r => r.json())
            .then(res => {
                if (res.status === 'success') {
                    localStorage.removeItem("dashboard_logged_in");
                    localStorage.removeItem("dashboard_current_user");
                    localStorage.removeItem("dashboard_settings");
                    showToast("تم تهيئة قاعدة البيانات بالكامل وتنزيل نسخة احتياطية آمنة! جاري التوجيه...", "danger");
                    closeResetModal();
                    setTimeout(() => {
                        window.location.href = "login.php";
                    }, 1500);
                } else {
                    showToast("فشلت التهيئة: " + res.message, "danger");
                    closeResetModal();
                }
            })
            .catch(() => {
                showToast("فشل الاتصال بالسيرفر لتنفيذ التهيئة", "danger");
                closeResetModal();
            });
    }, 1000);
}

// -------------------------------------------------------------
// 10. Event Listeners
// -------------------------------------------------------------
function setupEventListeners() {
    // Theme
    if (dom.themeToggle) dom.themeToggle.addEventListener("click", toggleTheme);

    // Form
    if (dom.settingsForm) dom.settingsForm.addEventListener("submit", handleFormSubmit);

    // Backup & Restore
    if (dom.btnBackup) dom.btnBackup.addEventListener("click", downloadBackupJSON);
    if (dom.btnTriggerRestore) dom.btnTriggerRestore.addEventListener("click", triggerFileRestore);
    if (dom.restoreFileInput) dom.restoreFileInput.addEventListener("change", handleFileRestore);

    // Shift Reset Modal
    if (dom.btnShiftReset) dom.btnShiftReset.addEventListener("click", openShiftResetModal);
    if (dom.cancelShiftResetBtn) dom.cancelShiftResetBtn.addEventListener("click", closeShiftResetModal);
    if (dom.confirmShiftResetBtn) dom.confirmShiftResetBtn.addEventListener("click", executeShiftReset);

    // Factory Reset Modal
    if (dom.btnFactoryReset) dom.btnFactoryReset.addEventListener("click", openResetModal);
    if (dom.cancelResetBtn) dom.cancelResetBtn.addEventListener("click", closeResetModal);
    if (dom.confirmResetBtn) dom.confirmResetBtn.addEventListener("click", executeFactoryReset);

    // Close on overlay click
    window.addEventListener("click", (e) => {
        if (e.target === dom.resetConfirmModal) closeResetModal();
        if (e.target === dom.shiftResetModal) closeShiftResetModal();
    });

    // Close on Escape
    window.addEventListener("keydown", (e) => {
        if (e.key === "Escape") {
            closeResetModal();
            closeShiftResetModal();
        }
    });

    // Toggle password visibility on settings page
    if (dom.btnToggleSettingsPassword) {
        dom.btnToggleSettingsPassword.addEventListener("click", () => {
            if (dom.passwordInput.type === "password") {
                dom.passwordInput.type = "text";
                dom.settingsPasswordToggleIcon.classList.remove("fa-eye");
                dom.settingsPasswordToggleIcon.classList.add("fa-eye-slash");
            } else {
                dom.passwordInput.type = "password";
                dom.settingsPasswordToggleIcon.classList.remove("fa-eye-slash");
                dom.settingsPasswordToggleIcon.classList.add("fa-eye");
            }
        });
    }
}

// -------------------------------------------------------------
// 12. Form Print Banner Upload
// -------------------------------------------------------------
window.handleBannerFileSelected = function(event) {
    const file = event.target.files[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = function(e) {
        const previewImg = document.getElementById("banner-preview-img");
        if (previewImg) previewImg.src = e.target.result;
        const uploadBtn = document.getElementById("upload-banner-btn");
        if (uploadBtn) uploadBtn.style.display = "inline-flex";
    };
    reader.readAsDataURL(file);
};

window.uploadBannerNow = function() {
    const fileInput = document.getElementById("settings-banner-file");
    if (!fileInput || !fileInput.files[0]) {
        showToast("يرجى اختيار ملف صورة أولاً", "warning");
        return;
    }

    const formData = new FormData();
    formData.append("banner", fileInput.files[0]);

    const uploadBtn = document.getElementById("upload-banner-btn");
    if (uploadBtn) {
        uploadBtn.disabled = true;
        uploadBtn.innerHTML = '<i class="fa-solid fa-spinner fa-spin" style="margin-left: 6px;"></i>جاري رفع البنر...';
    }

    fetch("api/settings.php?action=upload_banner", {
        method: "POST",
        body: formData
    })
    .then(r => r.json())
    .then(res => {
        if (uploadBtn) {
            uploadBtn.disabled = false;
            uploadBtn.innerHTML = '<i class="fa-solid fa-cloud-arrow-up" style="margin-left: 6px;"></i>حفظ وتأكيد البنر الجديد';
        }
        if (res.status === "success") {
            showToast(res.message || "تم حفظ وتحديث البنر بنجاح", "success");
            localStorage.setItem("header_banner_path", res.bannerPath);
            const previewImg = document.getElementById("banner-preview-img");
            if (previewImg) previewImg.src = res.bannerPath;
            if (uploadBtn) uploadBtn.style.display = "none";
        } else {
            showToast(res.message || "فشل رفع البنر", "danger");
        }
    })
    .catch(err => {
        if (uploadBtn) {
            uploadBtn.disabled = false;
            uploadBtn.innerHTML = '<i class="fa-solid fa-cloud-arrow-up" style="margin-left: 6px;"></i>حفظ وتأكيد البنر الجديد';
        }
        showToast("حدث خطأ أثناء رفع ملف البنر", "danger");
    });
};
