<?php
// /admission33333/committee_login.php — robust includes + debug + secure login
 
/* ===== 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);
}
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
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'])) {
  $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 {
        $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();
        $user = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        // 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) {
          // Store ALL user data in session for use across pages
          $_SESSION['committee_id']          = (int)$user['id'];
          $_SESSION['committee_username']    = (string)$user['username'];
          $_SESSION['committee_name']        = (string)$user['name'];
          $_SESSION['committee_can_all']     = (int)$user['can_view_all'] === 1;
          $_SESSION['committee_college_id']  = isset($user['college_id']) ? (int)$user['college_id'] : null;
          $_SESSION['committee_role_id']     = isset($user['role_id']) ? (int)$user['role_id'] : null; // Store role_id
          
          // Store the role in session for redirection
          $_SESSION['user_role'] = $role;

          // 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: #1a5f7a;
            --secondary-color: #57cc99;
            --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 */
        .form-control {
            width: 100%;
            height: 55px;
            padding: 0 50px 0 15px;
            border: 2px solid var(--gray-border);
            border-radius: 12px;
            font-size: 1rem;
            transition: all 0.3s ease;
            background: white;
            color: var(--dark-text);
            text-align: center;
            direction: rtl;
        }

        .form-control:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(26, 95, 122, 0.1);
            outline: none;
        }

        /* Icon styling - FIXED POSITIONING */
        .input-container .input-icon {
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: #94a3b8;
            font-size: 1.2rem;
            z-index: 2;
            width: 24px;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        /* Password toggle button - FIXED POSITIONING */
        .password-toggle {
            position: absolute;
            left: 15px;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            border: none;
            color: #94a3b8;
            cursor: pointer;
            font-size: 1.1rem;
            padding: 5px;
            z-index: 3;
            width: 30px;
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .password-toggle:hover {
            color: var(--primary-color);
            background: rgba(26, 95, 122, 0.05);
            border-radius: 5px;
        }

        .login-btn {
            width: 100%;
            height: 55px;
            background: linear-gradient(135deg, var(--primary-color), #2a7a9a);
            color: white;
            border: none;
            border-radius: 12px;
            font-size: 1.1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-top: 10px;
        }

        .login-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(26, 95, 122, 0.2);
        }

        .login-btn i {
            margin-left: 8px;
        }

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

        .alert-custom {
            border-radius: 12px;
            padding: 15px 20px;
            font-size: 1rem;
            border: none;
            background: #fee2e2;
            color: var(--danger);
            margin-bottom: 25px;
            display: flex;
            align-items: center;
            text-align: right;
        }

        .alert-custom.info {
            background: #dbeafe;
            color: #1d4ed8;
        }

        .alert-custom i {
            margin-left: 12px;
            font-size: 1.2rem;
        }

        /* التصحيح المهم: رابط العودة إلى الصفحة الرئيسية */
        .footer-links {
            text-align: center;
            margin-top: 30px;
            color: #64748b;
            font-size: 0.95rem;
            padding-top: 20px;
            border-top: 1px solid var(--gray-border);
        }

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

        .footer-links p i {
            margin-left: 8px;
        }

        /* التصحيح: رابط العودة */
        .back-home-link {
            display: block;
            color: var(--primary-color);
            text-decoration: none;
            font-weight: 600;
            margin-top: 20px;
            padding: 12px 25px;
            border: 2px solid var(--primary-color);
            border-radius: 12px;
            transition: all 0.3s ease;
            background: white;
            text-align: center;
            width: 100%;
            max-width: 300px;
            margin-left: auto;
            margin-right: auto;
            box-shadow: 0 4px 6px rgba(26, 95, 122, 0.1);
        }

        .back-home-link:hover {
            background: var(--primary-color);
            color: white;
            text-decoration: none;
            transform: translateY(-2px);
            box-shadow: 0 6px 12px rgba(26, 95, 122, 0.15);
        }

        .back-home-link i {
            margin-left: 10px;
            transition: transform 0.3s ease;
        }

        .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: none;
            color: white;
            padding: 8px 15px;
            border-radius: 8px;
            font-weight: 600;
            cursor: pointer;
        }

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

        /* Debug styles to see elements */
        .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: 250px;
                padding: 10px 20px;
            }
        }

        @media (max-width: 576px) {
            .login-left, .login-right {
                padding: 30px 20px;
            }
            
            .login-title {
                font-size: 1.6rem;
            }
            
            .form-control {
                height: 50px;
                padding: 0 45px 0 15px;
            }
            
            .login-btn {
                height: 50px;
            }
            
            .welcome-text {
                font-size: 1.8rem;
            }
            
            .input-container .input-icon {
                right: 12px;
                font-size: 1.1rem;
            }
            
            .password-toggle {
                left: 12px;
                font-size: 1rem;
            }
            
            .back-home-link {
                padding: 10px 15px;
                font-size: 0.9rem;
                max-width: 220px;
            }
        }
    </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':'' ?>">
                    <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) ?>">
                            <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 >
                            <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>
                    <p class="mb-0">
                        <i class="fas fa-phone-alt"></i>
                        هاتف الدعم: 7777-33-0128
                    </p>
                    
                    <!-- رابط العودة المحدث -->
                    <a href="https://uofg.edu.sd/Registration" class="back-home-link">
                        <i class="fas fa-arrow-right"></i>
                        العودة إلى الصفحة الرئيسية
                    </a>
                </div>
            </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');
            }
        });
        
        // 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;
            }
        });
        
        // Auto-focus on username field
        document.addEventListener('DOMContentLoaded', function() {
            const usernameField = document.getElementById('username');
            if (usernameField && usernameField.value === '') {
                usernameField.focus();
            }
            
            // 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');
                });
            }
        });
    </script>
</body>
</html>