<?php
// /admission33333/committee_login.php — robust includes + debug + secure login
// نسخة محسنة بناءً على أزرار admin_login.php

/* ===== 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(E_ALL);
}

/* ===== Get role from URL parameter ===== */
$role = $_GET['role'] ?? 'committee'; // Default to 'committee' if no role specified

/* ===== 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>Include error</h3>";
    echo "<p>Could not find <code>db.php</code> or <code>helpers.php</code> near " . e(__DIR__) . "</p>";
  }
  exit;
}

require_once $dbphp;
require_once $helphp;

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

/* ===== Ensure core helpers & DB handle exist ===== */
if (!function_exists('verify_csrf') || !function_exists('csrf_token')) {
  function csrf_token() { return $_SESSION['csrf'] = $_SESSION['csrf'] ?? bin2hex(random_bytes(16)); }
  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'); }
}

if (!isset($mysqli1) || !($mysqli1 instanceof mysqli)) {
  http_response_code(500);
  if ($DEBUG) {
    echo "<h3>DB error</h3><p><code>\$mysqli1</code> was not created by db.php.</p>";
  }
  exit;
}
$mysqli1->set_charset('utf8mb4');
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

/* ===== If already logged in, go to appropriate dashboard ===== */
if (!empty($_SESSION['committee_id'])) {
  // Check if user has permission to access committee dashboard
  $user_role_id = $_SESSION['committee_role_id'] ?? 0;
  
  // Only allow role_id = 1 (admin) or 2 (registrar) to access committee dashboard
  if (!in_array($user_role_id, [1, 2])) {
    // Destroy session if user doesn't have permission
    session_destroy();
    header("Location: committee_login.php?role=committee");
    exit;
  }
  
  $user_role = $_SESSION['user_role'] ?? 'committee';
  switch($user_role) {
    case 'committee':
    default:
      header("Location: committee_dashboard.php");
      exit;
  }
}

$error = '';
$username = '';

/* ===== Handle POST (login) ===== */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  try {
    if (!verify_csrf($_POST['csrf'] ?? '')) {
      $error = 'Invalid session token.';
    } else {
      $username = trim((string)($_POST['username'] ?? ''));
      $password = (string)($_POST['password'] ?? '');

      if ($username === '' || $password === '') {
        $error = 'Username and password are required.';
      } else {
        // تحسين: استخدام prepared statement مع تحديد النوع بدقة
        $stmt = $mysqli1->prepare("SELECT id, username, password_hash, name, can_view_all, college_id, role_id FROM committee_users WHERE username=? LIMIT 1");
        $stmt->bind_param("s", $username);
        $stmt->execute();
        $result = $stmt->get_result();
        $user = $result->fetch_assoc();
        $stmt->close();

        // تحسين: تنظيف النتائج وإغلاق النتيجة
        if ($result) {
          $result->free();
        }

        // COMPREHENSIVE DEBUGGING
        if ($user) {
          error_log("=== LOGIN DEBUG START ===");
          error_log("Username input: '" . $username . "'");
          error_log("Password input: '" . $password . "'");
          error_log("Stored hash: '" . $user['password_hash'] . "'");
          error_log("Stored hash length: " . strlen($user['password_hash']));
          error_log("Input password length: " . strlen($password));
          
          // Character-by-character analysis
          error_log("--- CHARACTER ANALYSIS ---");
          $max_len = max(strlen($user['password_hash']), strlen($password));
          for ($i = 0; $i < $max_len; $i++) {
            $stored_char = isset($user['password_hash'][$i]) ? 'char#' . $i . '=' . ord($user['password_hash'][$i]) . "('" . $user['password_hash'][$i] . "')" : 'END';
            $input_char = isset($password[$i]) ? 'char#' . $i . '=' . ord($password[$i]) . "('" . $password[$i] . "')" : 'END';
            if ($stored_char !== $input_char) {
              error_log("CHARACTER MISMATCH at position $i: stored=$stored_char, input=$input_char");
            }
          }
          
          $info = password_get_info($user['password_hash']);
          error_log("--- PASSWORD INFO ---");
          error_log("Algo: " . $info['algo']);
          error_log("AlgoName: " . $info['algoname']);
          error_log("Options: " . print_r($info['options'], true));
        } else {
          error_log("=== LOGIN DEBUG: USER NOT FOUND ===");
          error_log("Username searched: '" . $username . "'");
        }

        $ok = false;
        if ($user) {
          // Prefer strong hash if stored
          $info = password_get_info($user['password_hash']);
          if (!empty($info['algo'])) {
            $ok = password_verify($password, $user['password_hash']);
            error_log("--- PASSWORD_VERIFY RESULT ---");
            error_log("Using password_verify - Result: " . ($ok ? 'SUCCESS' : 'FAILED'));
          } else {
            // Legacy: stored as plaintext in password_hash column
            // Test multiple comparison methods
            error_log("--- PLAIN TEXT COMPARISON METHODS ---");
            
            // Method 1: Exact comparison
            $method1 = ($user['password_hash'] === $password);
            error_log("Exact comparison (===): " . ($method1 ? 'MATCH' : 'NO MATCH'));
            
            // Method 2: Trimmed comparison
            $stored_clean = trim($user['password_hash']);
            $input_clean = trim($password);
            $method2 = ($stored_clean === $input_clean);
            error_log("Trimmed comparison: " . ($method2 ? 'MATCH' : 'NO MATCH'));
            error_log("Stored trimmed: '" . $stored_clean . "'");
            error_log("Input trimmed: '" . $input_clean . "'");
            
            // Method 3: Case-insensitive
            $method3 = (strcasecmp($stored_clean, $input_clean) === 0);
            error_log("Case-insensitive comparison: " . ($method3 ? 'MATCH' : 'NO MATCH'));
            
            // Method 4: MD5 comparison (if someone stored MD5 hashes)
            $method4 = (md5($password) === $user['password_hash']);
            error_log("MD5 comparison: " . ($method4 ? 'MATCH' : 'NO MATCH'));
            
            $ok = $method1 || $method2 || $method3 || $method4;
            error_log("FINAL PLAIN TEXT RESULT: " . ($ok ? 'SUCCESS' : 'FAILED'));
          }
        }

        error_log("=== LOGIN DEBUG END ===");

        if ($ok) {
          // تحسين: التحقق من صحة البيانات قبل التخزين
          $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']) ? filter_var($user['can_view_all'], FILTER_VALIDATE_INT) === 1 : false;
          $college_id = isset($user['college_id']) ? filter_var($user['college_id'], FILTER_VALIDATE_INT) : null;
          
          // Only allow role_id = 1 (admin) or 2 (registrar) to access committee dashboard
          if (!in_array($user_role_id, [1, 2])) {
            $error = 'ليس لديك صلاحية للوصول إلى لوحة التحكم. الرجاء الاتصال بالمسؤول.';
            error_log("ACCESS DENIED: User role_id=$user_role_id attempted to access committee dashboard");
          } else {
            // تحسين: تخزين البيانات بشكل آمن في الجلسة
            $_SESSION['committee_id']          = $user_id;
            $_SESSION['committee_username']    = htmlspecialchars($user['username'], ENT_QUOTES, 'UTF-8');
            $_SESSION['committee_name']        = htmlspecialchars($user['name'], ENT_QUOTES, 'UTF-8');
            $_SESSION['committee_can_all']     = $can_view_all;
            $_SESSION['committee_college_id']  = $college_id;
            $_SESSION['committee_role_id']     = $user_role_id;
            
            // Store the role in session for redirection
            $_SESSION['user_role'] = htmlspecialchars($role, ENT_QUOTES, 'UTF-8');

            // تحسين: إعادة إنشاء معرف الجلسة لمنع تثبيت الجلسة
            session_regenerate_id(true);

            // Redirect based on role
            switch($role) {
              case 'committee':
              default:
                header("Location: committee_dashboard.php");
                exit;
            }
          }
        } else {
          $error = 'Invalid credentials.';
          if ($DEBUG) {
            $error .= ' Check server error logs for detailed debugging information.';
          }
        }
      }
    }
  } catch (Throwable $e) {
    error_log("[committee_login][EXC] ".$e->getMessage()." @ ".$e->getFile().":".$e->getLine());
    $error = $DEBUG ? ('Exception: '.$e->getMessage()) : 'Server error.';
  }
}

/* ===== Page Title Based on Role ===== */
$page_titles = [
  'committee' => 'مسجل الكلية',
];

$page_title = $page_titles[$role] ?? 'مسجل الكلية';
?>

<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <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: #43A047;
            --secondary-color: #43A047;
            --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, #f0f9ff 0%, #e0f2fe 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%, #2a7a9a 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;
        }

        .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(26, 95, 122, 0.2);
        }

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

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

        /* Input field styling - محسن مثل admin_login */
        .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;
            appearance: none;
            font-weight: 500;
        }

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

        /* أيقونة الإدخال على اليمين - مثل admin_login */
        .input-container .input-icon {
            position: absolute;
            right: 20px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--primary-color);
            font-size: 1.3rem;
            z-index: 2;
            width: 26px;
            height: 26px;
            display: flex;
            align-items: center;
            justify-content: center;
            pointer-events: none;
        }

        /* ===== زر إظهار/إخفاء كلمة المرور - محسن مثل admin_login ===== */
        .password-toggle {
            position: absolute;
            left: 20px !important; /* تأكيد اليسار */
            right: auto !important; /* إلغاء اليمين */
            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;
            -webkit-appearance: none;
            -moz-appearance: none;
            appearance: none;
            outline: none;
            
            /* تحسين المؤشر */
            pointer-events: auto !important;
            user-select: none;
            -webkit-user-select: none;
            -moz-user-select: none;
            -ms-user-select: none;
        }

        .password-toggle:hover {
            color: var(--primary-color);
            background: rgba(26, 95, 122, 0.1);
            cursor: pointer !important;
            
            /* تأثير hover */
            transform: translateY(-50%) scale(1.05);
        }

        .password-toggle:active {
            transform: translateY(-50%) scale(0.98);
        }

        .password-toggle i {
            font-size: 1.3rem;
            display: block;
            line-height: 1;
            pointer-events: none; /* الأيقونة لا تمنع النقر */
            width: 24px;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        /* ===== زر الدخول - محسن مثل admin_login ===== */
        .login-btn {
            width: 100%;
            height: 60px;
            background: linear-gradient(135deg, var(--primary-color), #2a7a9a);
            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;
            letter-spacing: 0.5px;
            
            /* تعديلات المؤشر */
            cursor: pointer !important;
            position: relative;
            z-index: 1;
            -webkit-appearance: none;
            -moz-appearance: none;
            appearance: none;
            user-select: none;
            -webkit-user-select: none;
            -moz-user-select: none;
            -ms-user-select: none;
            box-sizing: border-box;
            margin: 10px 0 0 0;
            padding: 0 20px;
            outline: none;
            
            /* تحسين المؤشر */
            pointer-events: auto !important;
            line-height: 1;
        }

        .login-btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 15px 30px rgba(26, 95, 122, 0.25);
            background: linear-gradient(135deg, #2a7a9a, var(--primary-color));
            cursor: pointer !important;
        }

        .login-btn:active {
            transform: translateY(-1px);
            cursor: pointer !important;
        }

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

        /* ===== زر العودة للرئيسية - محسن مثل admin_login ===== */
        .back-home-link {
            display: flex;
            align-items: center;
            justify-content: center;
            background: linear-gradient(135deg, var(--primary-color), #2a7a9a);
            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(26, 95, 122, 0.2);
            border: none;
            
            /* تعديلات المؤشر */
            cursor: pointer !important;
            position: relative;
            z-index: 1;
            box-sizing: border-box;
            -webkit-appearance: none;
            -moz-appearance: none;
            appearance: none;
            outline: none;
            
            /* تحسين المؤشر */
            pointer-events: auto !important;
            user-select: none;
        }

        .back-home-link:hover {
            transform: translateY(-3px);
            box-shadow: 0 10px 20px rgba(26, 95, 122, 0.3);
            text-decoration: none;
            color: white;
            background: linear-gradient(135deg, #2a7a9a, var(--primary-color));
            cursor: pointer !important;
        }

        .back-home-link:active {
            transform: translateY(-1px);
            cursor: pointer !important;
        }

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

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

        /* ===== زر تبديل اللغة - محسن مثل admin_login ===== */
        .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;
            border: none;
            outline: none;
            
            /* تحسين المؤشر */
            pointer-events: auto !important;
            user-select: none;
        }

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

        .lang-btn:active {
            transform: translateY(0);
        }

        .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 styling - محسن */
        .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;
        }

        /* Footer links - محسن */
        .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);
        }

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

        /* تحسين للـ RTL */
        [dir="rtl"] .password-toggle {
            left: 20px !important;
            right: auto !important;
        }

        [dir="rtl"] .input-icon {
            right: 20px !important;
            left: auto !important;
        }

        /* Debug styles */
        .debug-outline {
            border: 1px solid red !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;
            }
            
            .back-home-link {
                max-width: 280px;
                padding: 14px 25px;
            }
        }

        @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;
            }
            
            .input-container .input-icon {
                right: 15px;
                font-size: 1.2rem;
            }
            
            .password-toggle {
                left: 15px !important;
                width: 44px;
                height: 44px;
            }
            
            .back-home-link {
                padding: 12px 20px;
                font-size: 1rem;
                max-width: 250px;
            }
        }
    </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">EN</button>
                </div>
                
                <h1 class="welcome-text">مرحبًا بعودتك</h1>
                <p class="system-name">نظام القبول والتسجيل الإلكتروني</p>
                
                <ul class="features-list">
                    <li>
                        <i class="fas fa-shield-alt"></i>
                        <span>تسجيل دخول آمن ومشفر</span>
                    </li>
                    <li>
                        <i class="fas fa-tachometer-alt"></i>
                        <span>لوحة تحكم متكاملة وسهلة الاستخدام</span>
                    </li>
                    <li>
                        <i class="fas fa-users-cog"></i>
                        <span>إدارة طلبات القبول والتسجيل بكفاءة</span>
                    </li>
                    <li>
                        <i class="fas fa-chart-line"></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-user-tie"></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" action="committee_login.php?role=<?= e($role) ?><?= $DEBUG ? '&debug=1':'' ?>" 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">
                                <i class="fas fa-eye"></i>
                            </button>
                            <i class="input-icon fas fa-lock"></i>
                        </div>
                    </div>
                    
                    <button class="login-btn" type="submit">
                        <i class="fas fa-sign-in-alt"></i>
                        تسجيل الدخول
                    </button>
                </form>
                
                <!-- رابط العودة إلى الصفحة الرئيسية -->
                <div class="footer-links">
                    <p class="mb-2">
                        <i class="fas fa-info-circle"></i>
                        للمساعدة التقنية، الرجاء الاتصال بقسم الدعم التقني
                    </p>
                 
                    
                    <!-- رابط العودة المحدث -->
                    <a href="https://uofg.edu.sd/Registration" 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');
            }
        });
        
        // Language switcher placeholder
        document.querySelector('.lang-btn').addEventListener('click', function() {
            alert('سيتم تفعيل ميزة الترجمة في تحديث لاحق');
        });
        
        // Form validation feedback
        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;
            }
            
            // منع الإرسال المتكرر للنموذج
            const submitBtn = this.querySelector('button[type="submit"]');
            if (submitBtn.disabled) {
                e.preventDefault();
                return false;
            }
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i> جاري تسجيل الدخول...';
        });
        
        // Auto-focus on username field
        document.addEventListener('DOMContentLoaded', function() {
            const usernameField = document.getElementById('username');
            if (usernameField && usernameField.value === '') {
                usernameField.focus();
            }
            
            // تأكيد أن المؤشر يعمل على كل الأزرار
            const buttons = document.querySelectorAll('button, .back-home-link, .lang-btn, .password-toggle, .login-btn');
            buttons.forEach(btn => {
                btn.style.cursor = 'pointer';
            });
            
            // Debug: Add visual outlines to see element positions
            if (window.location.search.includes('debug')) {
                document.querySelectorAll('.input-container').forEach(el => {
                    el.classList.add('debug-outline');
                });
            }
        });
        
        // إضافة مؤشر الماوس للأزرار عند التحويم
        const style = document.createElement('style');
        style.textContent = `
            button, .btn, [role="button"], input[type="submit"], input[type="button"], input[type="reset"] {
                cursor: pointer !important;
            }
            button * {
                pointer-events: none;
            }
        `;
        document.head.appendChild(style);
    </script>
</body>
</html>