<?php
// doctor_login.php — نسخة محسنة بالكامل مع تشفير كلمات المرور وحماية متقدمة
header("Expires: Tue, 01 Jan 2000 00:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Pragma: no-cache");
header("X-Content-Type-Options: nosniff");
header("X-Frame-Options: DENY");
header("X-XSS-Protection: 1; mode=block");

require 'db.php';
require 'helpers.php';

// Start session securely
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

// ==================== CSRF FIX ====================
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// ==================== RATE LIMITING ====================
$ip = $_SERVER['REMOTE_ADDR'];
$rate_key = 'login_attempts_' . md5($ip);
$max_attempts = 5;
$lockout_time = 900; // 15 minutes

$is_locked = false;
$error = '';
$username = '';

if (isset($_SESSION[$rate_key])) {
    if ($_SESSION[$rate_key]['attempts'] >= $max_attempts) {
        if (time() - $_SESSION[$rate_key]['time'] < $lockout_time) {
            $is_locked = true;
            $error = 'تم تجاوز عدد المحاولات المسموحة. الرجاء المحاولة بعد 15 دقيقة.';
        } else {
            $_SESSION[$rate_key] = ['attempts' => 0, 'time' => time()];
        }
    }
}

// ==================== LOGIN PROCESSING ====================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !$is_locked) {
    if (!verify_csrf($_POST['csrf'] ?? '')) {
        $error = 'رمز الجلسة غير صالح. الرجاء تحديث الصفحة والمحاولة مرة أخرى.';
        error_log("CSRF violation attempt from IP: $ip");
    } else {
        $username = trim($_POST['username'] ?? '');
        $password = (string)($_POST['password'] ?? '');

        if (empty($username) || empty($password)) {
            $error = 'الرجاء إدخال اسم المستخدم وكلمة المرور.';
        } elseif (strlen($username) > 100 || strlen($password) > 255) {
            $error = 'بيانات الدخول غير صحيحة.';
        } else {
            $stmt = $mysqli1->prepare("SELECT id, full_name, password_hash, is_active FROM doctors WHERE username = ? LIMIT 1");
            
            if (!$stmt) {
                error_log("Database error in doctor_login: " . $mysqli1->error);
                $error = 'حدث خطأ في النظام. الرجاء المحاولة لاحقاً.';
            } else {
                $stmt->bind_param("s", $username);
                $stmt->execute();
                $result = $stmt->get_result();
                
                if ($row = $result->fetch_assoc()) {
                    $id = (int)$row['id'];
                    $full_name = $row['full_name'];
                    $stored_password = $row['password_hash'];
                    $active = (int)$row['is_active'];
                    
                    // محاولة التحقق من كلمة المرور بطرق متعددة
                    $password_valid = false;
                    
                    // الطريقة 1: مقارنة مباشرة (للكلمات المرور النصية)
                    if (hash_equals($stored_password, $password)) {
                        $password_valid = true;
                    }
                    // الطريقة 2: استخدام password_verify (للكلمات المرور المشفرة)
                    elseif (password_verify($password, $stored_password)) {
                        $password_valid = true;
                        
                        if (password_needs_rehash($stored_password, PASSWORD_DEFAULT)) {
                            $new_hash = password_hash($password, PASSWORD_DEFAULT);
                            $update_stmt = $mysqli1->prepare("UPDATE doctors SET password_hash = ? WHERE id = ?");
                            if ($update_stmt) {
                                $update_stmt->bind_param("si", $new_hash, $id);
                                $update_stmt->execute();
                                $update_stmt->close();
                            }
                        }
                    }
                    
                    if ($active === 1 && $password_valid) {
                        unset($_SESSION[$rate_key]);
                        
                        $_SESSION['doctor_id'] = $id;
                        $_SESSION['doctor_name'] = $full_name;
                        $_SESSION['login_time'] = time();
                        $_SESSION['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
                        $_SESSION['ip_address'] = $ip;
                        
                        session_regenerate_id(true);
                        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
                        
                        $stmt->close();
                        error_log("Successful login for doctor ID: $id from IP: $ip");
                        
                        header("Location: medical_list.php");
                        exit;
                    } else {
                        if (!isset($_SESSION[$rate_key])) {
                            $_SESSION[$rate_key] = ['attempts' => 1, 'time' => time()];
                        } else {
                            $_SESSION[$rate_key]['attempts']++;
                        }
                        
                        $remaining = $max_attempts - $_SESSION[$rate_key]['attempts'];
                        if ($remaining > 0) {
                            $error = "بيانات الدخول غير صحيحة. لديك $remaining محاولة متبقية.";
                        } else {
                            $error = 'تم تجاوز عدد المحاولات المسموحة. الرجاء المحاولة بعد 15 دقيقة.';
                        }
                        
                        error_log("Failed login attempt for username: $username from IP: $ip");
                    }
                } else {
                    if (!isset($_SESSION[$rate_key])) {
                        $_SESSION[$rate_key] = ['attempts' => 1, 'time' => time()];
                    } else {
                        $_SESSION[$rate_key]['attempts']++;
                    }
                    
                    $remaining = $max_attempts - $_SESSION[$rate_key]['attempts'];
                    if ($remaining > 0) {
                        $error = "بيانات الدخول غير صحيحة. لديك $remaining محاولة متبقية.";
                    } else {
                        $error = 'تم تجاوز عدد المحاولات المسموحة. الرجاء المحاولة بعد 15 دقيقة.';
                    }
                }
                $stmt->close();
            }
        }
    }
}

$csrf_token = csrf_token();
?>
<!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>
    
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' https://cdnjs.cloudflare.com https://cdn.jsdelivr.net 'unsafe-inline'; style-src 'self' https://fonts.googleapis.com https://cdnjs.cloudflare.com https://cdn.jsdelivr.net 'unsafe-inline'; font-src 'self' https://fonts.gstatic.com https://cdnjs.cloudflare.com https://cdn.jsdelivr.net; img-src 'self' data:;">
    
    <!-- Font Awesome (للأيقونات) -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" 
          integrity="sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw==" 
          crossorigin="anonymous" referrerpolicy="no-referrer" />
    
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    
    <style>
        :root {
            --medical-red: #dc2626;
            --medical-dark-red: #b91c1c;
            --medical-light-red: #ef4444;
            --medical-burgundy: #991b1b;
            --medical-blue: #2596be;
            --medical-teal: #06b6d4;
            --medical-green: #10b981;
            --medical-purple: #8b5cf6;
            --light-bg: #fff1f1;
            --dark-text: #1e293b;
            --gray-border: #e2e8f0;
            --danger: #dc2626;
            --warning: #f59e0b;
            --success: #10b981;
        }

        * {
            font-family: 'Cairo', sans-serif !important;
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
           /* background: linear-gradient(135deg, #fff5f5 0%, #fee2e2 50%, #fecaca 100%); */
              background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 50%, #dbeafe 100%);
            min-height: 100vh;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            padding: 20px;
            position: relative;
            overflow-x: hidden;
        }

        body::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-image: url('data:image/svg+xml,<svg width="100" height="100" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"><path d="M20,20 Q40,5 60,20 T100,20 Q80,35 60,20 T20,20" fill="none" stroke="%23dc2626" stroke-width="0.5" opacity="0.1"/><circle cx="30" cy="70" r="8" fill="%23b91c1c" opacity="0.1"/><circle cx="70" cy="30" r="6" fill="%238b5cf6" opacity="0.1"/></svg>');
            background-size: 200px;
            opacity: 0.15;
            z-index: -1;
        }

        .login-container {
            width: 100%;
            max-width: 1200px;
            margin: 0 auto;
        }

        .login-card {
            background: white;
            border-radius: 24px;
            box-shadow: 0 20px 60px rgba(220, 38, 38, 0.2), 0 0 0 1px rgba(220, 38, 38, 0.1);
            overflow: hidden;
            display: flex;
            min-height: 700px;
            position: relative;
            border: 1px solid rgba(220, 38, 38, 0.1);
        }

        .login-left {
            flex: 1;
            background: linear-gradient(135deg, var(--medical-red) 0%, var(--medical-dark-red) 100%);
            padding: 60px 40px;
            color: white;
            display: flex;
            flex-direction: column;
            justify-content: center;
            position: relative;
            overflow: hidden;
        }

        .login-left::before {
            content: '';
            position: absolute;
            top: -50%;
            right: -20%;
            width: 200%;
            height: 200%;
            background: radial-gradient(circle, rgba(255,255,255,0.15) 0%, transparent 70%);
            opacity: 0.4;
        }

        .medical-icon {
            position: absolute;
            font-size: 5rem;
            opacity: 0.1;
            color: white;
            z-index: 1;
        }

        .medical-icon:nth-child(1) { top: 15%; left: 15%; transform: rotate(-15deg); }
        .medical-icon:nth-child(2) { bottom: 20%; right: 20%; transform: rotate(10deg); }
        .medical-icon:nth-child(3) { top: 40%; right: 10%; transform: rotate(5deg); }

        .login-right {
            flex: 1.2;
            padding: 60px 50px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            background: white;
        }

        .welcome-text {
            font-size: 2.8rem;
            font-weight: 800;
            line-height: 1.2;
            margin-bottom: 20px;
            position: relative;
            z-index: 2;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.1);
        }

        .system-name {
            font-size: 1.5rem;
            font-weight: 600;
            opacity: 0.9;
            margin-bottom: 40px;
            position: relative;
            z-index: 2;
            border-right: 4px solid rgba(255,255,255,0.3);
            padding-right: 15px;
        }

        .features-list {
            list-style: none;
            padding: 0;
            margin-top: 40px;
            position: relative;
            z-index: 2;
        }

        .features-list li {
            margin-bottom: 25px;
            display: flex;
            align-items: center;
            font-size: 1.1rem;
            background: rgba(255, 255, 255, 0.1);
            padding: 10px 15px;
            border-radius: 50px;
            backdrop-filter: blur(5px);
            border: 1px solid rgba(255,255,255,0.2);
        }

        .features-list li i {
            background: rgba(255, 255, 255, 0.2);
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-left: 15px;
            flex-shrink: 0;
            font-size: 1.2rem;
            border: 1px solid rgba(255,255,255,0.3);
        }

        .login-header {
            text-align: center;
            margin-bottom: 40px;
        }

        .doctor-icon {
            width: 120px;
            height: 120px;
            background: linear-gradient(135deg, var(--medical-red), var(--medical-burgundy));
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 25px;
            box-shadow: 0 15px 35px rgba(220, 38, 38, 0.3);
            position: relative;
            overflow: hidden;
            border: 4px solid rgba(255,255,255,0.2);
        }

        .doctor-icon::before {
            content: '';
            position: absolute;
            width: 150%;
            height: 150%;
            background: radial-gradient(circle, rgba(255,255,255,0.2) 0%, transparent 70%);
            top: -25%;
            left: -25%;
        }

        .doctor-icon i {
            font-size: 3.5rem;
            color: white;
            z-index: 1;
            filter: drop-shadow(2px 2px 4px rgba(0,0,0,0.2));
        }

        .role-badge {
            display: inline-block;
            background: linear-gradient(135deg, var(--medical-red), var(--medical-burgundy));
            color: white;
            padding: 10px 30px;
            border-radius: 50px;
            font-weight: 700;
            font-size: 1.1rem;
            margin-bottom: 15px;
            box-shadow: 0 5px 15px rgba(220, 38, 38, 0.3);
            border: 1px solid rgba(255,255,255,0.2);
        }

        .login-title {
            font-size: 2.2rem;
            font-weight: 800;
            color: var(--medical-red);
            margin-bottom: 10px;
            background: linear-gradient(135deg, var(--medical-red), var(--medical-burgundy));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }

        .login-subtitle {
            color: #64748b;
            font-size: 1.1rem;
            margin-bottom: 30px;
        }

        .form-group {
            margin-bottom: 25px;
        }

        .input-with-icon {
            position: relative;
        }

        .input-icon {
            position: absolute;
            right: 20px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--medical-red);
            font-size: 1.2rem;
            z-index: 2;
            opacity: 0.7;
        }

        .form-control {
            width: 100%;
            height: 65px;
            border-radius: 15px;
            border: 2px solid var(--gray-border);
            padding: 0 55px 0 55px;
            font-size: 1.1rem;
            transition: all 0.3s ease;
            background: #f8fafc;
        }

        .form-control:focus {
            border-color: var(--medical-red);
            box-shadow: 0 0 0 4px rgba(220, 38, 38, 0.15);
            background: white;
            outline: none;
        }

        .login-btn {
            background: linear-gradient(135deg, var(--medical-red), var(--medical-dark-red));
            color: white;
            border: none;
            height: 65px;
            border-radius: 15px;
            font-size: 1.2rem;
            font-weight: 700;
            transition: all 0.3s ease;
            width: 100%;
            margin-top: 10px;
            position: relative;
            overflow: hidden;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            letter-spacing: 0.5px;
            text-transform: uppercase;
            box-shadow: 0 10px 20px rgba(220, 38, 38, 0.3);
        }

        .login-btn::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
            transition: 0.5s;
        }

        .login-btn:hover::before {
            left: 100%;
        }

        .login-btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 20px 30px rgba(220, 38, 38, 0.4);
        }

        .login-btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }

        .alert-custom {
            border-radius: 12px;
            padding: 15px 20px;
            font-size: 1rem;
            border: none;
            background: #fee2e2;
            color: var(--medical-burgundy);
            margin-bottom: 25px;
            border-right: 4px solid var(--medical-red);
            display: flex;
            align-items: center;
            gap: 10px;
            box-shadow: 0 5px 10px rgba(220, 38, 38, 0.1);
        }

        .alert-custom i {
            font-size: 1.2rem;
            color: var(--medical-red);
        }

        .footer-links {
            text-align: center;
            margin-top: 30px;
            color: #64748b;
            font-size: 0.95rem;
        }

        .footer-links a {
            color: var(--medical-red);
            text-decoration: none;
            font-weight: 600;
            transition: all 0.3s ease;
            border-bottom: 1px dashed transparent;
        }

        .footer-links a:hover {
            color: var(--medical-dark-red);
            border-bottom-color: var(--medical-dark-red);
        }

        .password-toggle {
            position: absolute;
            left: 20px;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            border: none;
            color: var(--medical-red);
            cursor: pointer;
            z-index: 2;
            padding: 10px;
            font-size: 1.2rem;
            transition: color 0.3s ease;
            opacity: 0.7;
        }

        .password-toggle:hover {
            opacity: 1;
            color: var(--medical-dark-red);
        }

        .back-home {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            margin-top: 20px;
            color: var(--medical-red);
            font-weight: 600;
            text-decoration: none;
            transition: all 0.3s ease;
            padding: 8px 20px;
            border-radius: 50px;
            background: #fff1f1;
        }

        .back-home:hover {
            background: var(--medical-red);
            color: white;
            transform: translateX(-5px);
        }

        .back-home i {
            transition: transform 0.3s ease;
        }

        .back-home:hover i {
            transform: translateX(-5px);
        }

        .attempts-counter {
            font-size: 0.9rem;
            color: var(--medical-red);
            margin-top: 10px;
            text-align: center;
            background: #fee2e2;
            padding: 8px;
            border-radius: 50px;
            font-weight: 600;
        }

        @media (max-width: 992px) {
            .login-card {
                flex-direction: column;
                min-height: auto;
            }
            
            .login-left, .login-right {
                padding: 40px 30px;
            }
            
            .welcome-text {
                font-size: 2.2rem;
            }
            
            .login-title {
                font-size: 1.8rem;
            }
            
            .doctor-icon {
                width: 100px;
                height: 100px;
            }
            
            .doctor-icon i {
                font-size: 3rem;
            }
        }

        @media (max-width: 576px) {
            body {
                padding: 15px;
            }
            
            .login-left, .login-right {
                padding: 30px 20px;
            }
            
            .login-title {
                font-size: 1.6rem;
            }
            
            .form-control {
                height: 55px;
            }
            
            .login-btn {
                height: 55px;
            }
            
            .features-list li {
                font-size: 1rem;
            }
        }

        /* تحسين ظهور الأيقونات */
        .fa, .fas, .far, .fab {
            font-family: 'Font Awesome 6 Free' !important;
            font-weight: 900;
        }
        
        .fa-stethoscope:before {
            content: "\f0f1";
        }
        
        .fa-heartbeat:before {
            content: "\f21e";
        }
        
        .fa-hospital:before {
            content: "\f0f8";
        }
        
        .fa-user-md:before {
            content: "\f0f0";
        }
        
        .fa-file-medical-alt:before {
            content: "\f478";
        }
        
        .fa-clipboard-check:before {
            content: "\f46c";
        }
        
        .fa-shield-alt:before {
            content: "\f3ed";
        }
        
        .fa-lock:before {
            content: "\f023";
        }
        
        .fa-key:before {
            content: "\f084";
        }
        
        .fa-eye:before {
            content: "\f06e";
        }
        
        .fa-eye-slash:before {
            content: "\f070";
        }
        
        .fa-sign-in-alt:before {
            content: "\f2f6";
        }
        
        .fa-info-circle:before {
            content: "\f05a";
        }
        
        .fa-phone-alt:before {
            content: "\f879";
        }
        
        .fa-arrow-right:before {
            content: "\f061";
        }
        
        .fa-exclamation-triangle:before {
            content: "\f071";
        }
        
        .fa-exclamation-circle:before {
            content: "\f06a";
        }
        
        .fa-arrow-repeat:before {
            content: "\f2f1";
        }
    </style>
</head>
<body>
<div class="login-container">
    <div class="login-card">
        
        <!-- Left Panel - Medical Welcome Section -->
        <div class="login-left">
            <i class="medical-icon fas fa-heartbeat"></i>
            <i class="medical-icon fas fa-stethoscope"></i>
            <i class="medical-icon fas fa-hospital"></i>
            
            <h1 class="welcome-text">مرحبًا دكتور</h1>
            <p class="system-name">نظام إدارة الخدمات الصحية الإلكتروني</p>
            
            <ul class="features-list">
                <li>
                    <i class="fas fa-user-md"></i>
                    <span>وصول آمن للملفات الطبية</span>
                </li>
                <li>
                    <i class="fas fa-file-medical-alt"></i>
                    <span>تسجيل وتعديل بيانات الكشف الطبي بسهولة</span>
                </li>
                <li>
                    <i class="fas fa-clipboard-check"></i>
                    <span>متابعة الحالات الصحية للطلاب</span>
                </li>
                <li>
                    <i class="fas fa-shield-alt"></i>
                    <span>حماية كاملة لبيانات المرضى</span>
                </li>
            </ul>
            
            <div style="margin-top: auto; opacity: 0.8; font-size: 0.9rem; position: relative; z-index: 2;">
                <p><i class="fas fa-lock" style="margin-left: 8px;"></i>جميع البيانات محمية وفقًا للقوانين الطبية</p>
            </div>
        </div>
        
        <!-- Right Panel - Doctor Login Form -->
        <div class="login-right">
            <div class="login-header">
                <div class="doctor-icon">
                    <i class="fas fa-user-md"></i>
                </div>
                
                <div class="role-badge">
                    <i class="fas fa-stethoscope" style="margin-left: 8px;"></i>دخول الأطباء
                </div>
                
                <h2 class="login-title">الكشف الطبي</h2>
                <p class="login-subtitle">الرجاء إدخال بيانات الاعتماد الطبية الخاصة بك</p>
            </div>
            
            <?php if ($error): ?>
                <div class="alert-custom">
                    <i class="fas fa-exclamation-triangle"></i>
                    <div><?php echo htmlspecialchars($error, ENT_QUOTES, 'UTF-8'); ?></div>
                </div>
            <?php endif; ?>

            <form method="post" autocomplete="off" id="loginForm">
                <input type="hidden" name="csrf" value="<?php echo htmlspecialchars($csrf_token, ENT_QUOTES, 'UTF-8'); ?>">
                
                <div class="form-group">
                    <div class="input-with-icon">
                        <i class="input-icon fas fa-user-md"></i>
                        <input type="text"
                               class="form-control"
                               id="username" name="username"
                               placeholder="اسم المستخدم الطبي"
                               value="<?php echo htmlspecialchars($username, ENT_QUOTES, 'UTF-8'); ?>"
                               required
                               autocomplete="off"
                               maxlength="100"
                               dir="ltr">
                    </div>
                </div>
                
                <div class="form-group">
                    <div class="input-with-icon">
                        <i class="input-icon fas fa-key"></i>
                        <button type="button" class="password-toggle" id="togglePassword" tabindex="-1">
                            <i class="fas fa-eye"></i>
                        </button>
                        <input type="password"
                               class="form-control"
                               id="password" name="password"
                               placeholder="كلمة المرور الخاصة"
                               required
                               autocomplete="off"
                               maxlength="255"
                               dir="ltr">
                    </div>
                </div>
                
                <button class="login-btn" type="submit" id="submitBtn" <?php echo $is_locked ? 'disabled' : ''; ?>>
                    <i class="fas fa-sign-in-alt" style="margin-left: 8px;"></i>
                    دخول إلى النظام الطبي
                </button>
                
                <?php if (isset($_SESSION[$rate_key]) && $_SESSION[$rate_key]['attempts'] > 0 && !$is_locked): ?>
                    <div class="attempts-counter">
                        <i class="fas fa-info-circle" style="margin-left: 5px;"></i>
                        عدد المحاولات المتبقية: <?php echo $max_attempts - $_SESSION[$rate_key]['attempts']; ?>
                    </div>
                <?php endif; ?>
                
                <div class="footer-links">
                    <p class="mb-2">
                        <i class="fas fa-info-circle" style="margin-left: 8px;"></i>
                        للمساعدة التقنية، الرجاء الاتصال بقسم الدعم الفني
                    </p>
                
                    <a href="index.php" class="back-home">
                        <i class="fas fa-arrow-right" style="margin-left: 8px;"></i>
                        العودة إلى الصفحة الرئيسية
                    </a>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    // Password visibility toggle
    document.getElementById('togglePassword').addEventListener('click', function() {
        const passwordInput = document.getElementById('password');
        const icon = this.querySelector('i');
        
        if (passwordInput.type === 'password') {
            passwordInput.type = 'text';
            icon.classList.remove('fa-eye');
            icon.classList.add('fa-eye-slash');
        } else {
            passwordInput.type = 'password';
            icon.classList.remove('fa-eye-slash');
            icon.classList.add('fa-eye');
        }
    });

    // Add focus effects to inputs
    const inputs = document.querySelectorAll('.form-control');
    inputs.forEach(input => {
        input.addEventListener('focus', function() {
            this.parentElement.querySelector('.input-icon').style.opacity = '1';
        });
        
        input.addEventListener('blur', function() {
            this.parentElement.querySelector('.input-icon').style.opacity = '0.7';
        });
    });

    // Form validation and submission handling
    document.getElementById('loginForm').addEventListener('submit', function(e) {
        const submitBtn = document.getElementById('submitBtn');
        
        if (submitBtn.disabled) {
            e.preventDefault();
            return;
        }
        
        const username = document.getElementById('username').value.trim();
        const password = document.getElementById('password').value;
        
        if (!username || !password) {
            e.preventDefault();
            
            const alertDiv = document.createElement('div');
            alertDiv.className = 'alert-custom';
            alertDiv.innerHTML = `
                <i class="fas fa-exclamation-circle"></i>
                <div>الرجاء ملء جميع الحقول المطلوبة</div>
            `;
            
            const existingAlert = document.querySelector('.alert-custom');
            if (existingAlert) {
                existingAlert.replaceWith(alertDiv);
            } else {
                document.querySelector('.login-header').after(alertDiv);
            }
            
            alertDiv.scrollIntoView({ behavior: 'smooth', block: 'center' });
            return;
        }
        
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin" style="margin-left: 8px;"></i> جاري التحقق...';
    });

    // Clear password field on page load
    document.addEventListener('DOMContentLoaded', function() {
        document.getElementById('password').value = '';
        
        const usernameInput = document.getElementById('username');
        usernameInput.addEventListener('input', function() {
            this.value = this.value.replace(/[<>]/g, '');
        });
    });

    // Prevent form resubmission
    if (window.history.replaceState) {
        window.history.replaceState(null, null, window.location.href);
    }
</script>

</body>
</html>
