<?php
// card_login.php - CARD PRINTING LOGIN WITH ADVANCED SECURITY
// نسخة محسنة وآمنة مع جميع الإصلاحات

/* ===== Debug toggle: add ?debug=1 to see errors on page ===== */
$DEBUG = isset($_GET['debug']) && $_GET['debug'] === '1';
if ($DEBUG) {
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);
    header("Content-Type: text/html; charset=UTF-8");
} else {
    error_reporting(0); // لا تعرض الأخطاء في الإنتاج
}

/* ===== Helper to locate required files no matter current dir ===== */
function req_path($fname) {
    $candidates = [
        __DIR__ . "/$fname",
        dirname(__DIR__) . "/$fname",
        __DIR__ . "/../$fname",
    ];
    foreach ($candidates as $p) {
        if (is_file($p)) return $p;
    }
    return null;
}

/* ===== Include db + helpers safely ===== */
$dbphp = req_path('db.php');
$helphp = req_path('helpers.php');

if (!$dbphp || !$helphp) {
    http_response_code(500);
    if ($DEBUG) {
        echo "<h3>خطأ في تضمين الملفات</h3>";
        echo "<p>لم يتم العثور على <code>db.php</code> أو <code>helpers.php</code> في المسار: " . htmlspecialchars(__DIR__) . "</p>";
    } else {
        echo "خطأ في النظام. الرجاء الاتصال بالدعم الفني.";
    }
    exit;
}

require_once $dbphp;
require_once $helphp;

/* ===== Ensure session ===== */
if (function_exists('session_status') && session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

/* ===== Ensure core helpers exist ===== */
if (!function_exists('verify_csrf') || !function_exists('csrf_token')) {
    function csrf_token() { 
        return $_SESSION['csrf'] = $_SESSION['csrf'] ?? bin2hex(random_bytes(32)); 
    }
    function verify_csrf($t) { 
        return isset($_SESSION['csrf']) && hash_equals($_SESSION['csrf'], (string)$t); 
    }
}
if (!function_exists('e')) {
    function e($s) { 
        return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); 
    }
}

/* ===== Check database connection ===== */
if (!isset($mysqli1) || !($mysqli1 instanceof mysqli)) {
    http_response_code(500);
    if ($DEBUG) {
        echo "<h3>خطأ في قاعدة البيانات</h3>";
        echo "<p>لم يتم إنشاء اتصال قاعدة البيانات بشكل صحيح.</p>";
    } else {
        echo "خطأ في النظام. الرجاء الاتصال بالدعم الفني.";
    }
    exit;
}

$mysqli1->set_charset('utf8mb4');
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

/* ===== If already logged in with proper permissions, go to dashboard ===== */
if (!empty($_SESSION['committee_id'])) {
    // Check if user has permission to access card printing dashboard
    $user_role_id = $_SESSION['committee_role_id'] ?? 0;
    
    // Only allow role_id = 4 (card_printing) to access card printing dashboard
    if ($user_role_id == 4 && ($_SESSION['user_role'] ?? '') === 'card_printing') {
        header("Location: card_printing_dashboard.php");
        exit;
    } else {
        // Destroy session if user doesn't have permission
        $_SESSION = array();
        if (ini_get("session.use_cookies")) {
            $params = session_get_cookie_params();
            setcookie(session_name(), '', time() - 42000,
                $params["path"], $params["domain"],
                $params["secure"], $params["httponly"]
            );
        }
        session_destroy();
        session_start();
    }
}

/* ===== Initialize variables ===== */
$error = '';
$username = '';

/* ===== Check if card_printing user exists, if not, create one (with prepared statements) ===== */
try {
    $check_stmt = $mysqli1->prepare("SELECT COUNT(*) as count FROM committee_users WHERE role_id = 4");
    $check_stmt->execute();
    $check_result = $check_stmt->get_result()->fetch_assoc();
    $check_stmt->close();
    
    if ($check_result['count'] == 0) {
        // Create default card printing user
        $default_username = 'card_printer';
        $default_password = 'cardprint#123';
        $default_name = 'طباعة البطاقات';
        $hash = password_hash($default_password, PASSWORD_DEFAULT);
        $role_id = 4;
        $role_name = 'card_printing';
        $can_view_all = 1;
        
        $insert_stmt = $mysqli1->prepare("
            INSERT INTO committee_users 
            (username, password_hash, name, can_view_all, role_id, role_name, created_at) 
            VALUES (?, ?, ?, ?, ?, ?, NOW())
        ");
        $insert_stmt->bind_param("sssiss", $default_username, $hash, $default_name, $can_view_all, $role_id, $role_name);
        $insert_stmt->execute();
        $insert_stmt->close();
        
        if ($DEBUG) {
            error_log("Default card printing user created: $default_username / $default_password");
        }
    }
} catch (Exception $e) {
    error_log("Error checking/creating default user: " . $e->getMessage());
}

/* ===== Handle POST (login) ===== */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        // Validate CSRF token
        if (!isset($_POST['csrf']) || !verify_csrf($_POST['csrf'])) {
            $error = 'رمز الأمان غير صالح. الرجاء تحديث الصفحة والمحاولة مرة أخرى.';
            error_log("[SECURITY] CSRF token validation failed from IP: " . ($_SERVER['REMOTE_ADDR'] ?? 'unknown'));
        } else {
            // Sanitize and validate input
            $username = trim((string)($_POST['username'] ?? ''));
            $password = (string)($_POST['password'] ?? '');
            
            // Validate input length
            if (strlen($username) > 100 || strlen($password) > 255) {
                $error = 'بيانات الدخول غير صالحة.';
                error_log("[SECURITY] Input length validation failed - username length: " . strlen($username));
            } elseif ($username === '' || $password === '') {
                $error = 'اسم المستخدم وكلمة المرور مطلوبان.';
            } else {
                // Use prepared statement to prevent SQL injection
                $stmt = $mysqli1->prepare("SELECT id, username, password_hash, name, can_view_all, role_id FROM committee_users WHERE username = ? AND role_id = 4 LIMIT 1");
                if (!$stmt) {
                    throw new Exception("فشل تحضير الاستعلام");
                }
                
                $stmt->bind_param("s", $username);
                $stmt->execute();
                $result = $stmt->get_result();
                $user = $result->fetch_assoc();
                $stmt->close();

                $ok = false;
                if ($user) {
                    // Secure password verification
                    $password_hash = $user['password_hash'];
                    
                    // Check if it's a valid password hash
                    $password_info = password_get_info($password_hash);
                    $hash_algo = $password_info['algo'] ?? 0;
                    
                    if ($hash_algo !== 0) {
                        // Modern password_hash format
                        $ok = password_verify($password, $password_hash);
                        
                        // Debug logging (only in debug mode)
                        if ($DEBUG) {
                            error_log("=== CARD PRINTING LOGIN DEBUG ===");
                            error_log("Username: " . $username);
                            error_log("Using password_verify: " . ($ok ? 'SUCCESS' : 'FAILED'));
                            error_log("Hash algorithm: " . ($password_info['algoName'] ?? 'unknown'));
                        }
                    } else {
                        // Legacy plain text (for backward compatibility only)
                        // WARNING: Remove this in production!
                        $ok = ($password_hash === $password);
                        
                        if ($DEBUG) {
                            error_log("=== CARD PRINTING LEGACY LOGIN ===");
                            error_log("Using plain text comparison: " . ($ok ? 'SUCCESS' : 'FAILED'));
                            error_log("SECURITY WARNING: Plain text passwords should not be used!");
                        }
                        
                        // If legacy login works, update to modern hash
                        if ($ok) {
                            $new_hash = password_hash($password, PASSWORD_DEFAULT);
                            $update_stmt = $mysqli1->prepare("UPDATE committee_users SET password_hash = ? WHERE id = ?");
                            $update_stmt->bind_param("si", $new_hash, $user['id']);
                            $update_stmt->execute();
                            $update_stmt->close();
                            if ($DEBUG) {
                                error_log("Password upgraded to modern hash for user: " . $username);
                            }
                        }
                    }
                } else {
                    if ($DEBUG) {
                        error_log("=== CARD PRINTING LOGIN DEBUG ===");
                        error_log("User not found with role_id=4: " . $username);
                        
                        // Check if user exists with wrong role
                        $check_stmt = $mysqli1->prepare("SELECT role_id FROM committee_users WHERE username = ? LIMIT 1");
                        $check_stmt->bind_param("s", $username);
                        $check_stmt->execute();
                        $check_result = $check_stmt->get_result();
                        if ($check_row = $check_result->fetch_assoc()) {
                            error_log("User exists but has role_id: " . $check_row['role_id'] . " (should be 4)");
                        }
                        $check_stmt->close();
                    }
                }

                if ($ok) {
                    // Validate user data before storing in session
                    $user_id = filter_var($user['id'], FILTER_VALIDATE_INT);
                    $user_role_id = isset($user['role_id']) ? filter_var($user['role_id'], FILTER_VALIDATE_INT) : 0;
                    $can_view_all = isset($user['can_view_all']) ? (bool)$user['can_view_all'] : false;
                    
                    // Only allow role_id = 4 (card_printing)
                    if ($user_role_id != 4) {
                        $error = 'ليس لديك صلاحية للوصول إلى نظام طباعة البطاقات. الرجاء الاتصال بالمسؤول.';
                        error_log("[SECURITY] Access denied - User ID: $user_id, Role ID: $user_role_id attempted to access card printing dashboard");
                    } else {
                        // Regenerate session ID to prevent session fixation
                        session_regenerate_id(true);
                        
                        // Store minimal necessary data in session
                        $_SESSION['committee_id'] = $user_id;
                        $_SESSION['committee_username'] = $user['username'];
                        $_SESSION['committee_name'] = $user['name'];
                        $_SESSION['committee_can_all'] = $can_view_all;
                        $_SESSION['committee_role_id'] = $user_role_id;
                        $_SESSION['user_role'] = 'card_printing';
                        $_SESSION['login_time'] = time();
                        $_SESSION['ip_address'] = $_SERVER['REMOTE_ADDR'] ?? '';
                        $_SESSION['user_agent'] = $_SERVER['HTTP_USER_AGENT'] ?? '';
                        
                        // Clear CSRF token after successful login
                        unset($_SESSION['csrf']);
                        
                        if ($DEBUG) {
                            error_log("Successful login for user: $username (ID: $user_id, Role: $user_role_id)");
                        }
                        
                        // Redirect to dashboard
                        header("Location: card_printing_dashboard.php");
                        exit;
                    }
                } else {
                    // Use generic error message to prevent user enumeration
                    $error = 'اسم المستخدم أو كلمة المرور غير صحيحة.';
                    
                    // Add delay to prevent brute force attacks
                    usleep(500000); // 0.5 second delay
                    
                    // Log failed attempt
                    error_log("[SECURITY] Failed login attempt for username: $username from IP: " . ($_SERVER['REMOTE_ADDR'] ?? 'unknown'));
                }
            }
        }
    } catch (Throwable $e) {
        // Log error but don't expose details to user
        error_log("[ERROR] card_login.php: " . $e->getMessage() . " at " . $e->getFile() . ":" . $e->getLine());
        $error = 'حدث خطأ في النظام. الرجاء المحاولة مرة أخرى لاحقاً.';
    }
}

// Generate new CSRF token for the form
$csrf_token = csrf_token();

// Page Title
$page_title = 'طباعة البطاقات';
?>

<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="robots" content="noindex, nofollow">
    <title>تسجيل الدخول - <?= e($page_title) ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary-color: #f39c12;
            --secondary-color: #e67e22;
            --accent-color: #ffd166;
            --light-bg: #f8fafc;
            --dark-text: #1e293b;
            --gray-border: #e2e8f0;
            --success: #10b981;
            --danger: #ef4444;
            --warning: #f59e0b;
        }

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

        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
            direction: rtl;
        }

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

        .login-card {
            background: white;
            border-radius: 24px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.08);
            overflow: hidden;
            display: flex;
            min-height: 700px;
        }

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

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

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

        .welcome-text {
            font-size: 2.8rem;
            font-weight: 800;
            line-height: 1.2;
            margin-bottom: 20px;
            position: relative;
            z-index: 1;
        }

        .system-name {
            font-size: 1.5rem;
            font-weight: 600;
            opacity: 0.9;
            margin-bottom: 40px;
            position: relative;
            z-index: 1;
        }

        .features-list {
            list-style: none;
            padding: 0;
            margin-top: 40px;
        }

        .features-list li {
            margin-bottom: 25px;
            display: flex;
            align-items: center;
            font-size: 1.1rem;
            position: relative;
            z-index: 1;
        }

        .features-list li i {
            background: rgba(255, 255, 255, 0.2);
            width: 36px;
            height: 36px;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-left: 15px;
            flex-shrink: 0;
            pointer-events: none;
        }

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

        .login-icon {
            width: 80px;
            height: 80px;
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            border-radius: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 20px;
            box-shadow: 0 10px 30px rgba(243, 156, 18, 0.2);
        }

        .login-icon i {
            font-size: 2.5rem;
            color: white;
            pointer-events: none;
        }

        .login-title {
            font-size: 2.2rem;
            font-weight: 800;
            color: var(--primary-color);
            margin-bottom: 10px;
        }

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

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

        .input-container {
            position: relative;
            width: 100%;
        }

        .form-control {
            width: 100%;
            height: 60px;
            padding: 0 60px 0 60px;
            border: 2px solid var(--gray-border);
            border-radius: 14px;
            font-size: 1.1rem;
            transition: all 0.3s ease;
            background: white;
            color: var(--dark-text);
            text-align: center;
            direction: rtl;
            -webkit-appearance: none;
            -moz-appearance: none;
            appearance: none;
        }

        .form-control:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 4px rgba(243, 156, 18, 0.15);
            outline: none;
            background: #f8fafc;
        }

        .input-container .input-icon {
            position: absolute;
            right: 20px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--primary-color);
            font-size: 1.3rem;
            z-index: 2;
            pointer-events: none;
        }

        .password-toggle {
            position: absolute;
            left: 20px;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            border: none;
            color: #94a3b8;
            font-size: 1.2rem;
            padding: 0;
            z-index: 3;
            width: 48px;
            height: 48px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 8px;
            transition: all 0.3s ease;
            cursor: pointer !important;
        }

        .password-toggle:hover {
            color: var(--primary-color);
            background: rgba(243, 156, 18, 0.1);
        }

        .password-toggle i {
            pointer-events: none;
        }

        .login-btn {
            width: 100%;
            height: 60px;
            background: linear-gradient(135deg, var(--primary-color), #e67e22);
            color: white;
            border: none;
            border-radius: 14px;
            font-size: 1.2rem;
            font-weight: 700;
            transition: all 0.4s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-top: 10px;
            cursor: pointer !important;
            position: relative;
            overflow: hidden;
            -webkit-appearance: none;
            -moz-appearance: none;
            appearance: none;
        }

        .login-btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 15px 30px rgba(243, 156, 18, 0.25);
        }

        .login-btn:active {
            transform: translateY(-1px);
        }

        .login-btn i {
            margin-left: 12px;
            font-size: 1.3rem;
            pointer-events: none;
        }

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

        .role-badge {
            display: inline-block;
            background: var(--accent-color);
            color: #854d0e;
            padding: 8px 20px;
            border-radius: 50px;
            font-weight: 700;
            font-size: 1rem;
            margin-bottom: 20px;
        }

        .alert-custom {
            border-radius: 14px;
            padding: 18px 24px;
            font-size: 1.1rem;
            border: none;
            background: #fee2e2;
            color: var(--danger);
            margin-bottom: 30px;
            display: flex;
            align-items: center;
            text-align: right;
            border-right: 5px solid var(--danger);
        }

        .alert-custom.info {
            background: #dbeafe;
            color: #1d4ed8;
            border-right: 5px solid #1d4ed8;
        }

        .alert-custom i {
            margin-left: 15px;
            font-size: 1.4rem;
            pointer-events: none;
        }

        .footer-links {
            text-align: center;
            margin-top: 40px;
            color: #475569;
            font-size: 1rem;
            padding-top: 25px;
            border-top: 2px solid var(--gray-border);
        }

        .footer-links p {
            margin-bottom: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .footer-links p i {
            margin-left: 10px;
            color: var(--secondary-color);
            pointer-events: none;
        }

        .back-home-link {
            display: flex;
            align-items: center;
            justify-content: center;
            background: linear-gradient(135deg, var(--primary-color), #e67e22);
            color: white;
            text-decoration: none;
            font-weight: 700;
            margin-top: 25px;
            padding: 15px 30px;
            border-radius: 14px;
            transition: all 0.3s ease;
            text-align: center;
            width: 100%;
            max-width: 320px;
            margin-left: auto;
            margin-right: auto;
            box-shadow: 0 6px 12px rgba(243, 156, 18, 0.2);
            border: none;
            cursor: pointer !important;
            -webkit-appearance: none;
            -moz-appearance: none;
            appearance: none;
        }

        .back-home-link:hover {
            transform: translateY(-3px);
            box-shadow: 0 10px 20px rgba(243, 156, 18, 0.3);
            text-decoration: none;
            color: white;
        }

        .back-home-link i {
            margin-left: 12px;
            transition: transform 0.3s ease;
            pointer-events: none;
        }

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

        .language-switcher {
            position: absolute;
            top: 30px;
            left: 30px;
            z-index: 10;
        }

        .lang-btn {
            background: rgba(255, 255, 255, 0.2);
            border: 2px solid rgba(255, 255, 255, 0.3);
            color: white;
            padding: 12px 24px;
            border-radius: 12px;
            font-weight: 700;
            backdrop-filter: blur(10px);
            transition: all 0.3s ease;
            cursor: pointer !important;
            -webkit-appearance: none;
            -moz-appearance: none;
            appearance: none;
        }

        .lang-btn:hover {
            background: rgba(255, 255, 255, 0.3);
            transform: translateY(-2px);
        }

        .default-creds {
            background: #f8f9fa;
            border-radius: 12px;
            padding: 15px;
            margin-top: 20px;
            text-align: center;
            border: 1px dashed var(--gray-border);
        }

        .creds-item {
            display: inline-block;
            background: white;
            padding: 5px 15px;
            border-radius: 20px;
            margin: 5px;
            font-family: monospace;
            border: 1px solid var(--gray-border);
        }

        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(255,255,255,.3);
            border-radius: 50%;
            border-top-color: #fff;
            animation: spin 1s ease-in-out infinite;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        @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;
            }
        }

        @media (max-width: 576px) {
            .login-left, .login-right {
                padding: 30px 20px;
            }
            
            .login-title {
                font-size: 1.6rem;
            }
            
            .form-control {
                height: 55px;
                padding: 0 50px 0 50px;
                font-size: 1rem;
            }
            
            .login-btn {
                height: 55px;
                font-size: 1.1rem;
            }
            
            .welcome-text {
                font-size: 1.8rem;
            }
            
            .back-home-link {
                max-width: 280px;
                padding: 12px 20px;
            }
        }
    </style>
</head>
<body>
    <div class="login-container">
        <div class="login-card">
            
            <!-- Left Panel - Welcome Section -->
            <div class="login-left">
                <div class="language-switcher">
                    <button class="lang-btn" type="button" onclick="alert('سيتم تفعيل الترجمة قريباً')">
                        EN
                    </button>
                </div>
                
                <h1 class="welcome-text">نظام طباعة البطاقات</h1>
                <p class="system-name">إصدار وإدارة البطاقات الجامعية</p>
                
                <ul class="features-list">
                    <li>
                        <i class="fas fa-id-card"></i>
                        <span>طباعة بطاقات الطلاب بجودة عالية</span>
                    </li>
                    <li>
                        <i class="fas fa-qrcode"></i>
                        <span>دعم الباركود والـ QR Code</span>
                    </li>
                    <li>
                        <i class="fas fa-print"></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;">
                    <p>© 2026 نظام القبول الإلكتروني. جميع الحقوق محفوظة.</p>
                </div>
            </div>
            
            <!-- Right Panel - Login Form -->
            <div class="login-right">
                <div class="login-header">
                    <div class="login-icon">
                        <i class="fas fa-id-card"></i>
                    </div>
                    
                    <div class="role-badge">
                        <?= e($page_title) ?>
                    </div>
                    
                    <h2 class="login-title">تسجيل الدخول</h2>
                    <p class="login-subtitle">الرجاء إدخال بيانات الاعتماد الخاصة بك</p>
                </div>
                
                <?php if ($error): ?>
                    <div class="alert-custom" role="alert">
                        <i class="fas fa-exclamation-circle"></i>
                        <div><?= e($error) ?></div>
                    </div>
                <?php endif; ?>

                <?php if ($DEBUG): ?>
                    <div class="alert-custom info" role="alert">
                        <i class="fas fa-bug"></i>
                        <div>
                            <strong>وضع التصحيح نشط</strong>
                            <p class="mb-0">هذا الوضع مخصص للاختبار فقط</p>
                        </div>
                    </div>
                <?php endif; ?>

                <form method="post" autocomplete="off">
                    <input type="hidden" name="csrf" value="<?= e($csrf_token) ?>">
                    
                    <div class="form-group">
                        <div class="input-container">
                            <input type="text"
                                   class="form-control"
                                   id="username" 
                                   name="username"
                                   placeholder="اسم المستخدم"
                                   required 
                                   value="<?= e($username) ?>"
                                   autocomplete="off"
                                   maxlength="100">
                            <i class="input-icon fas fa-user"></i>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <div class="input-container">
                            <input type="password"
                                   class="form-control"
                                   id="password" 
                                   name="password"
                                   placeholder="كلمة المرور"
                                   required
                                   autocomplete="off"
                                   maxlength="255">
                            <button type="button" class="password-toggle" id="togglePassword" tabindex="-1">
                                <i class="fas fa-eye"></i>
                            </button>
                            <i class="input-icon fas fa-lock"></i>
                        </div>
                    </div>
                    
                    <button class="login-btn" type="submit" id="submitBtn">
                        <i class="fas fa-sign-in-alt"></i>
                        دخول لطباعة البطاقات
                    </button>
                </form>
                
                <!-- Default credentials (shown in debug mode only) -->
                <?php if ($DEBUG): ?>
                    <div class="default-creds">
                        <small class="text-muted">
                            <i class="fas fa-info-circle"></i>
                            للاختبار: اسم المستخدم: <span class="creds-item">card_printer</span> 
                            كلمة المرور: <span class="creds-item">cardprint#123</span>
                        </small>
                    </div>
                <?php endif; ?>
                
                <!-- Footer Links -->
                <div class="footer-links">
                    <p class="mb-2">
                        <i class="fas fa-info-circle"></i>
                        للمساعدة التقنية، الرجاء الاتصال بقسم الدعم
                    </p>
                    
                    <a href="https://nu.edu.sd/nu" class="back-home-link" rel="noopener noreferrer">
                        <i class="fas fa-arrow-right"></i>
                        العودة إلى الصفحة الرئيسية
                    </a>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Password visibility toggle
        document.getElementById('togglePassword').addEventListener('click', function(e) {
            e.preventDefault();
            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');
            }
        });

        // Form submission handling
        document.querySelector('form').addEventListener('submit', function(e) {
            const username = document.getElementById('username').value.trim();
            const password = document.getElementById('password').value;
            
            if (!username || !password) {
                e.preventDefault();
                alert('يرجى ملء جميع الحقول المطلوبة');
                return false;
            }
            
            // Prevent double submission
            const submitBtn = document.getElementById('submitBtn');
            if (submitBtn.disabled) {
                e.preventDefault();
                return false;
            }
            
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<span class="loading"></span> جاري تسجيل الدخول...';
            
            // Re-enable after 10 seconds in case of timeout
            setTimeout(function() {
                submitBtn.disabled = false;
                submitBtn.innerHTML = '<i class="fas fa-sign-in-alt"></i> دخول لطباعة البطاقات';
            }, 10000);
        });

        // Auto-focus on username field
        document.addEventListener('DOMContentLoaded', function() {
            const usernameField = document.getElementById('username');
            if (usernameField && usernameField.value === '') {
                usernameField.focus();
            }
        });

        // Disable right-click on sensitive areas (optional security)
        document.querySelector('.login-right').addEventListener('contextmenu', function(e) {
            e.preventDefault();
            return false;
        });
    </script>
</body>
</html>