<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>تسجيل الدخول | لوحة التحكم</title>
    <!-- Google Fonts: Cairo for beautiful Arabic Typography -->
    <link rel="stylesheet" href="css/cairo.css">
    <!-- Font Awesome for premium icons -->
    <link rel="stylesheet" href="css/fontawesome/css/all.min.css">
    <!-- Favicon inline fallback -->
    <link rel="icon" href="data:image/x-icon;," type="image/x-icon">
    <!-- Styling -->
    <link rel="stylesheet" href="css/style.css">
    <!-- Auth redirect check -->
    <script src="js/auth.js"></script>
</head>
<body>
    <div class="login-wrapper">
        <!-- Theme Toggle button on the login page -->
        <div class="login-theme-toggle">
            <button class="theme-toggle-btn" id="theme-toggle" title="تغيير المظهر" type="button">
                <i class="fa-solid fa-moon"></i>
            </button>
        </div>

        <div class="login-card">
            <div class="login-header">
                <div class="login-logo">
                    <i class="fa-solid fa-layer-group"></i>
                </div>
                <h1 id="org-name-title">لوحة التحكم الرئيسية</h1>
                <p>الرجاء تسجيل الدخول لمتابعة العمل</p>
            </div>

            <form id="login-form" novalidate>
                <div class="form-group" id="username-group">
                    <label for="username">اسم المستخدم</label>
                    <div class="input-wrapper">
                        <i class="fa-solid fa-user input-icon"></i>
                        <input type="text" id="username" placeholder="أدخل اسم المستخدم..." required autocomplete="username">
                    </div>
                    <span class="error-msg" id="username-error">يرجى إدخال اسم مستخدم صحيح</span>
                </div>

                <div class="form-group" id="password-group">
                    <label for="password">كلمة المرور</label>
                    <div class="input-wrapper">
                        <i class="fa-solid fa-key input-icon"></i>
                        <input type="password" id="password" placeholder="أدخل كلمة المرور..." required autocomplete="current-password">
                        <button type="button" class="password-toggle" id="btn-toggle-password" title="عرض كلمة المرور">
                            <i class="fa-solid fa-eye" id="password-toggle-icon"></i>
                        </button>
                    </div>
                    <span class="error-msg" id="password-error">يرجى إدخال كلمة المرور</span>
                </div>

                <div class="login-actions">
                    <label class="login-remember">
                        <input type="checkbox" id="remember-me" checked>
                        <span>تذكرني على هذا الجهاز</span>
                    </label>
                </div>

                <button type="submit" class="btn btn-primary login-btn" id="btn-submit">
                    <i class="fa-solid fa-right-to-bracket"></i>
                    <span>تسجيل الدخول</span>
                </button>
            </form>
        </div>
    </div>

    <!-- Toast Notifications Container -->
    <div class="toast-container" id="toast-container"></div>

    <script>
        // -------------------------------------------------------------
        // 1. Initial configuration
        // -------------------------------------------------------------
        const dom = {
            loginForm: document.getElementById("login-form"),
            usernameInput: document.getElementById("username"),
            passwordInput: document.getElementById("password"),
            usernameGroup: document.getElementById("username-group"),
            passwordGroup: document.getElementById("password-group"),
            btnTogglePassword: document.getElementById("btn-toggle-password"),
            passwordToggleIcon: document.getElementById("password-toggle-icon"),
            themeToggle: document.getElementById("theme-toggle"),
            orgNameTitle: document.getElementById("org-name-title"),
            toastContainer: document.getElementById("toast-container")
        };

        document.addEventListener("DOMContentLoaded", () => {
            initTheme();
            loadOrgName();
            setupEventListeners();
        });

        // -------------------------------------------------------------
        // 2. Load Organization Name dynamically
        // -------------------------------------------------------------
        function loadOrgName() {
            fetch('api/settings.php?action=get_settings')
                .then(r => r.json())
                .then(res => {
                    if (res.status === 'success' && res.settings && res.settings.orgName) {
                        dom.orgNameTitle.textContent = res.settings.orgName;
                        localStorage.setItem("dashboard_settings", JSON.stringify(res.settings));
                    }
                })
                .catch(() => {
                    const localSettings = localStorage.getItem("dashboard_settings");
                    if (localSettings) {
                        try {
                            const settings = JSON.parse(localSettings);
                            if (settings.orgName) {
                                dom.orgNameTitle.textContent = settings.orgName;
                            }
                        } catch(e) {}
                    }
                });
        }

        // -------------------------------------------------------------
        // 3. Theme Management
        // -------------------------------------------------------------
        function initTheme() {
            const savedTheme = localStorage.getItem("dashboard_theme");
            if (savedTheme === "dark") {
                document.body.classList.add("dark-theme");
                dom.themeToggle.innerHTML = '<i class="fa-solid fa-sun"></i>';
            } else {
                document.body.classList.remove("dark-theme");
                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");
                dom.themeToggle.innerHTML = '<i class="fa-solid fa-moon"></i>';
                localStorage.setItem("dashboard_theme", "light");
                showToast("تم تفعيل الوضع المضيء", "info");
            } else {
                document.body.classList.add("dark-theme");
                dom.themeToggle.innerHTML = '<i class="fa-solid fa-sun"></i>';
                localStorage.setItem("dashboard_theme", "dark");
                showToast("تم تفعيل الوضع الداكن", "info");
            }
        }

        // -------------------------------------------------------------
        // 4. Toast Notification
        // -------------------------------------------------------------
        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. Password visibility toggle
        // -------------------------------------------------------------
        function togglePassword() {
            if (dom.passwordInput.type === "password") {
                dom.passwordInput.type = "text";
                dom.passwordToggleIcon.classList.remove("fa-eye");
                dom.passwordToggleIcon.classList.add("fa-eye-slash");
            } else {
                dom.passwordInput.type = "password";
                dom.passwordToggleIcon.classList.remove("fa-eye-slash");
                dom.passwordToggleIcon.classList.add("fa-eye");
            }
        }

        // -------------------------------------------------------------
        // 6. Validation and Login Action
        // -------------------------------------------------------------
        function clearErrors() {
            dom.usernameGroup.classList.remove("has-error");
            dom.passwordGroup.classList.remove("has-error");
        }

        function handleLoginSubmit(e) {
            e.preventDefault();
            clearErrors();

            const username = dom.usernameInput.value.trim();
            const password = dom.passwordInput.value;

            let isValid = true;
            if (!username) {
                dom.usernameGroup.classList.add("has-error");
                isValid = false;
            }
            if (!password) {
                dom.passwordGroup.classList.add("has-error");
                isValid = false;
            }

            if (!isValid) return;

            // Fetch submit to backend API
            fetch('api/auth.php?action=login', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ username, password })
            })
            .then(r => r.json())
            .then(res => {
                if (res.status === 'success') {
                    showToast(res.message || "تم تسجيل الدخول بنجاح! جاري التوجيه...", "success");
                    localStorage.setItem("dashboard_logged_in", "true");
                    localStorage.setItem("dashboard_current_user", JSON.stringify(res.user));
                    
                    // Add loading state to button
                    const btnSubmit = document.getElementById("btn-submit");
                    if (btnSubmit) {
                        btnSubmit.disabled = true;
                        btnSubmit.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> جاري التحميل...';
                    }

                    setTimeout(() => {
                        window.location.href = "index.php";
                    }, 1000);
                } else {
                    dom.usernameGroup.classList.add("has-error");
                    dom.passwordGroup.classList.add("has-error");
                    showToast(res.message || "خطأ: اسم المستخدم أو كلمة المرور غير صحيحة", "danger");
                }
            })
            .catch(err => {
                console.error("Login request failed:", err);
                showToast("حدث خطأ أثناء الاتصال بالخادم، يرجى المحاولة لاحقاً.", "danger");
            });
        }

        // -------------------------------------------------------------
        // 7. Event Listeners Setup
        // -------------------------------------------------------------
        function setupEventListeners() {
            dom.themeToggle.addEventListener("click", toggleTheme);
            dom.btnTogglePassword.addEventListener("click", togglePassword);
            dom.loginForm.addEventListener("submit", handleLoginSubmit);
        }
    </script>
</body>
</html>

