<?php
// accountant_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';

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

// Check if already logged in as accountant
if (isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'accountant') {
    header("Location: accountant_dashboard.php");
    exit;
}

// If logged in with other role, destroy session
if (isset($_SESSION['user_role']) && $_SESSION['user_role'] !== 'accountant') {
    session_destroy();
    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()];
        }
    }
}

// Check if accountant user exists in database, if not, create one
$check_table = @$mysqli1->query("SHOW TABLES LIKE 'committee_users'");
if ($check_table && $check_table->num_rows > 0) {
    $result = @$mysqli1->query("SELECT id FROM committee_users WHERE role_name = 'accountant' LIMIT 1");
    if (!$result || $result->num_rows === 0) {
        // Create default accountant user
        $default_password = 'accountant#123';
        $hash = password_hash($default_password, PASSWORD_DEFAULT);
        $name = 'محاسب النظام';
        $role_id = 2;
        $insert_query = "INSERT INTO committee_users (username, password_hash, name, can_view_all, role_id, role_name, created_at) 
                        VALUES ('accountant', ?, ?, 1, ?, 'accountant', NOW())";
        $stmt = @$mysqli1->prepare($insert_query);
        if ($stmt) {
            $stmt->bind_param("ssi", $username_default, $hash, $role_id);
            $username_default = 'accountant';
            $stmt->execute();
            $stmt->close();
        }
    }
}

// ==================== LOGIN PROCESSING ====================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !$is_locked) {
    if (!isset($_POST['csrf']) || $_POST['csrf'] !== $_SESSION['csrf_token']) {
        $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 {
            // Check for accountant user
            $stmt = @$mysqli1->prepare("SELECT id, username, password_hash, name, can_view_all, role_id FROM committee_users WHERE username = ? AND role_name = 'accountant' LIMIT 1");
            
            if (!$stmt) {
                error_log("Database error in accountant_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['name'];
                    $stored_password = $row['password_hash'];
                    $can_view_all = (int)$row['can_view_all'];
                    
                    // محاولة التحقق من كلمة المرور بطرق متعددة
                    $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 committee_users SET password_hash = ? WHERE id = ?");
                            if ($update_stmt) {
                                $update_stmt->bind_param("si", $new_hash, $id);
                                $update_stmt->execute();
                                $update_stmt->close();
                            }
                        }
                    }
                    
                    if ($password_valid) {
                        // Clear rate limiting
                        unset($_SESSION[$rate_key]);
                        
                        // Set session variables
                        $_SESSION['committee_id'] = $id;
                        $_SESSION['committee_username'] = $username;
                        $_SESSION['committee_name'] = $full_name;
                        $_SESSION['committee_can_all'] = $can_view_all;
                        $_SESSION['user_role'] = 'accountant';
                        $_SESSION['login_time'] = time();
                        $_SESSION['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
                        $_SESSION['ip_address'] = $ip;
                        
                        // Regenerate session ID for security
                        session_regenerate_id(true);
                        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
                        
                        $stmt->close();
                        error_log("Successful login for accountant ID: $id from IP: $ip");
                        
                        header("Location: accountant_dashboard.php");
                        exit;
                    } else {
                        // Failed password
                        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 accountant username: $username from IP: $ip");
                    }
                } else {
                    // Username not found
                    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 accountant username: $username from IP: $ip");
                }
                $stmt->close();
            }
        }
    }
}

$csrf_token = $_SESSION['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' data:; script-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://cdnjs.cloudflare.com https://cdn.jsdelivr.net; font-src 'self' data: https://fonts.gstatic.com https://cdnjs.cloudflare.com https://cdn.jsdelivr.net; img-src 'self' data:;">
    
    <!-- Google Fonts - تحميل قبل Font Awesome -->
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    
    <!-- Font Awesome 6 - نسخة ثابتة مع integrity -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" 
          integrity="sha512-Fo3rlrZj/k7ujTnHg4CGR2D7kSs0v4LLanw2qksYuRlEzO+tcaEPQogQ0KaoGN26/zrn20ImR1DfuLWnOo7aBA==" 
          crossorigin="anonymous" referrerpolicy="no-referrer" />
    
    <!-- Font Awesome 6 - CDN احتياطي -->
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v6.0.0-beta3/css/all.css">
    
    <style>
        /* إعادة تعيين الخطوط */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Cairo', 'Tahoma', 'Arial', sans-serif !important;
            background: linear-gradient(135deg, #E0F7FA 0%, #B2EBF2 50%, #80DEEA 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="%2300BCD4" stroke-width="0.5" opacity="0.1"/><circle cx="30" cy="70" r="8" fill="%2300A0B4" opacity="0.1"/><circle cx="70" cy="30" r="6" fill="%234DD0E1" opacity="0.1"/></svg>');
            background-size: 200px;
            opacity: 0.15;
            z-index: -1;
        }

        :root {
            --accounting-teal: #00BCD4;
            --accounting-dark-teal: #00A0B4;
            --accounting-light-teal: #4DD0E1;
            --accounting-deep-teal: #00838F;
            --accounting-soft-blue: #B2EBF2;
            --light-bg: #F0F9FA;
            --dark-text: #1e293b;
            --gray-border: #e2e8f0;
            --danger: #dc2626;
            --warning: #f59e0b;
            --success: #10b981;
        }

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

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

        .login-left {
            flex: 1;
            background: linear-gradient(135deg, #00BCD4 0%, #00A0B4 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;
        }

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

        .financial-icon:nth-child(1) { top: 15%; left: 15%; transform: rotate(-15deg); }
        .financial-icon:nth-child(2) { bottom: 20%; right: 20%; transform: rotate(10deg); }
        .financial-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);
            font-family: 'Cairo', sans-serif;
        }

        .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;
            font-family: 'Cairo', sans-serif;
        }

        .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);
            font-family: 'Cairo', sans-serif;
        }

        .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);
            font-family: 'Font Awesome 6 Free', 'Font Awesome 5 Free', 'FontAwesome' !important;
            font-weight: 900;
        }

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

        .accountant-icon {
            width: 120px;
            height: 120px;
            background: linear-gradient(135deg, #00BCD4, #00838F);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 25px;
            box-shadow: 0 15px 35px rgba(0, 188, 212, 0.3);
            position: relative;
            overflow: hidden;
            border: 4px solid rgba(255,255,255,0.2);
        }

        .accountant-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%;
        }

        .accountant-icon i {
            font-size: 3.5rem;
            color: white;
            z-index: 1;
            filter: drop-shadow(2px 2px 4px rgba(0,0,0,0.2));
            font-family: 'Font Awesome 6 Free', 'Font Awesome 5 Free', 'FontAwesome' !important;
            font-weight: 900;
        }

        .role-badge {
            display: inline-block;
            background: linear-gradient(135deg, #00BCD4, #00838F);
            color: white;
            padding: 10px 30px;
            border-radius: 50px;
            font-weight: 700;
            font-size: 1.1rem;
            margin-bottom: 15px;
            box-shadow: 0 5px 15px rgba(0, 188, 212, 0.3);
            border: 1px solid rgba(255,255,255,0.2);
            font-family: 'Cairo', sans-serif;
        }

        .role-badge i {
            font-family: 'Font Awesome 6 Free', 'Font Awesome 5 Free', 'FontAwesome' !important;
            font-weight: 900;
        }

        .login-title {
            font-size: 2.2rem;
            font-weight: 800;
            color: #00BCD4;
            margin-bottom: 10px;
            background: linear-gradient(135deg, #00BCD4, #00838F);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
            font-family: 'Cairo', sans-serif;
        }

        .login-subtitle {
            color: #64748b;
            font-size: 1.1rem;
            margin-bottom: 30px;
            font-family: 'Cairo', sans-serif;
        }

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

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

        .input-icon {
            position: absolute;
            right: 20px;
            top: 50%;
            transform: translateY(-50%);
            color: #00BCD4;
            font-size: 1.2rem;
            z-index: 2;
            opacity: 0.7;
            font-family: 'Font Awesome 6 Free', 'Font Awesome 5 Free', 'FontAwesome' !important;
            font-weight: 900;
        }

        .form-control {
            width: 100%;
            height: 65px;
            border-radius: 15px;
            border: 2px solid #e2e8f0;
            padding: 0 55px 0 55px;
            font-size: 1.1rem;
            transition: all 0.3s ease;
            background: #f8fafc;
            font-family: 'Cairo', sans-serif;
        }

        .form-control:focus {
            border-color: #00BCD4;
            box-shadow: 0 0 0 4px rgba(0, 188, 212, 0.15);
            background: white;
            outline: none;
        }

        .login-btn {
            background: linear-gradient(135deg, #00BCD4, #00A0B4);
            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(0, 188, 212, 0.3);
            font-family: 'Cairo', sans-serif;
        }

        .login-btn i {
            font-family: 'Font Awesome 6 Free', 'Font Awesome 5 Free', 'FontAwesome' !important;
            font-weight: 900;
        }

        .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(0, 188, 212, 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: #E1F5FE;
            color: #00838F;
            margin-bottom: 25px;
            border-right: 4px solid #00BCD4;
            display: flex;
            align-items: center;
            gap: 10px;
            box-shadow: 0 5px 10px rgba(0, 188, 212, 0.1);
            font-family: 'Cairo', sans-serif;
        }

        .alert-custom i {
            font-size: 1.2rem;
            color: #00BCD4;
            font-family: 'Font Awesome 6 Free', 'Font Awesome 5 Free', 'FontAwesome' !important;
            font-weight: 900;
        }

        .footer-links {
            text-align: center;
            margin-top: 30px;
            color: #64748b;
            font-size: 0.95rem;
            font-family: 'Cairo', sans-serif;
        }

        .footer-links a {
            color: #00BCD4;
            text-decoration: none;
            font-weight: 600;
            transition: all 0.3s ease;
            border-bottom: 1px dashed transparent;
        }

        .footer-links a:hover {
            color: #00A0B4;
            border-bottom-color: #00A0B4;
        }

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

        .password-toggle i {
            font-family: 'Font Awesome 6 Free', 'Font Awesome 5 Free', 'FontAwesome' !important;
            font-weight: 900;
        }

        .password-toggle:hover {
            opacity: 1;
            color: #00A0B4;
        }

        .back-home {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            margin-top: 20px;
            color: #00BCD4;
            font-weight: 600;
            text-decoration: none;
            transition: all 0.3s ease;
            padding: 8px 20px;
            border-radius: 50px;
            background: #E0F7FA;
            font-family: 'Cairo', sans-serif;
        }

        .back-home i {
            font-family: 'Font Awesome 6 Free', 'Font Awesome 5 Free', 'FontAwesome' !important;
            font-weight: 900;
        }

        .back-home:hover {
            background: #00BCD4;
            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: #00BCD4;
            margin-top: 10px;
            text-align: center;
            background: #E0F7FA;
            padding: 8px;
            border-radius: 50px;
            font-weight: 600;
            font-family: 'Cairo', sans-serif;
        }

        /* تأكد من ظهور الأيقونات */
        .fas, .far, .fab, .fa {
            display: inline-block !important;
            font-style: normal !important;
            font-variant: normal !important;
            text-rendering: auto !important;
            -webkit-font-smoothing: antialiased !important;
            font-family: 'Font Awesome 6 Free', 'Font Awesome 5 Free', 'FontAwesome' !important;
            font-weight: 900 !important;
        }

        .far {
            font-weight: 400 !important;
        }

        .fab {
            font-family: 'Font Awesome 6 Brands', 'Font Awesome 5 Brands', 'FontAwesome' !important;
            font-weight: 400 !important;
        }

        @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;
            }
            
            .accountant-icon {
                width: 100px;
                height: 100px;
            }
            
            .accountant-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;
            }
        }
    </style>
</head>
<body>
<div class="login-container">
    <div class="login-card">
        
        <!-- Left Panel - Financial Welcome Section -->
        <div class="login-left">
            <i class="financial-icon fa-solid fa-chart-line"></i>
            <i class="financial-icon fa-solid fa-calculator"></i>
            <i class="financial-icon fa-solid fa-coins"></i>
            
            <h1 class="welcome-text">مرحبًا بك</h1>
            <p class="system-name">نظام الإدارة المالية والمحاسبية</p>
            
            <ul class="features-list">
                <li>
                    <i class="fa-solid fa-file-invoice-dollar"></i>
                    <span>إدارة الفواتير والمدفوعات</span>
                </li>
                <li>
                    <i class="fa-solid fa-chart-pie"></i>
                    <span>تقارير مالية متقدمة</span>
                </li>
                <li>
                    <i class="fa-solid fa-hand-holding-dollar"></i>
                    <span>متابعة الميزانيات والمصروفات</span>
                </li>
                <li>
                    <i class="fa-solid 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="fa-solid fa-lock" style="margin-left: 8px;"></i>جميع البيانات المالية محفوظة بسرية تامة</p>
            </div>
        </div>
        
        <!-- Right Panel - Accountant Login Form -->
        <div class="login-right">
            <div class="login-header">
                <div class="accountant-icon">
                    <i class="fa-solid fa-calculator"></i>
                </div>
                
                <div class="role-badge">
                    <i class="fa-solid fa-user-tie" 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="fa-solid fa-triangle-exclamation"></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 fa-solid fa-user-tie"></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 fa-solid fa-key"></i>
                        <button type="button" class="password-toggle" id="togglePassword" tabindex="-1">
                            <i class="fa-regular 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="fa-solid fa-arrow-right-to-bracket" 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="fa-solid fa-circle-info" 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="fa-solid fa-circle-info" style="margin-left: 8px;"></i>
                        للمساعدة التقنية، الرجاء الاتصال بقسم الدعم الفني
                    </p>
                
                    <a href="index.php" class="back-home">
                        <i class="fa-solid fa-arrow-left" 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="fa-solid fa-circle-exclamation"></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="fa-solid 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>