<?php
// student_affairs_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(0);
}

/* ===== Get role from URL parameter ===== */
$role = $_GET['role'] ?? 'student_affairs'; // Default to 'student_affairs'

/* ===== 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 " . htmlspecialchars(__DIR__, ENT_QUOTES, 'UTF-8') . "</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(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'); }
}

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 student affairs dashboard ===== */
if (!empty($_SESSION['committee_id']) && ($_SESSION['committee_role_id'] ?? 0) == 8) {
  header("Location: student_affairs_dashboard.php");
  exit;
}

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

/* ===== Handle POST (login) ===== */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  try {
    if (!verify_csrf($_POST['csrf'] ?? '')) {
      $error = 'رمز الجلسة غير صالح.';
    } else {
      $username = trim((string)($_POST['username'] ?? ''));
      $password = (string)($_POST['password'] ?? '');

      if ($username === '' || $password === '') {
        $error = 'اسم المستخدم وكلمة المرور مطلوبان.';
      } else {
        // التحقق من وجود المستخدم مع role_id = 8 (عمادة شؤون الطلاب)
        $stmt = $mysqli1->prepare("SELECT id, username, password_hash, name, can_view_all, college_id, role_id FROM committee_users WHERE username=? AND role_id=8 LIMIT 1");
        $stmt->bind_param("s", $username);
        $stmt->execute();
        $user = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        // DEBUGGING
        if ($user) {
          error_log("=== STUDENT AFFAIRS LOGIN DEBUG ===");
          error_log("Username: '" . $username . "'");
          error_log("User found with role_id: " . ($user['role_id'] ?? 'NULL'));
        } else {
          error_log("=== STUDENT AFFAIRS LOGIN: USER NOT FOUND OR WRONG ROLE ===");
          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: " . ($ok ? 'SUCCESS' : 'FAILED'));
          } else {
            // Legacy: plaintext comparison
            $stored_clean = trim($user['password_hash']);
            $input_clean = trim($password);
            $ok = ($stored_clean === $input_clean) || 
                  (strcasecmp($stored_clean, $input_clean) === 0);
            error_log("Plain text comparison: " . ($ok ? 'SUCCESS' : 'FAILED'));
          }
        }

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

        if ($ok && ($user['role_id'] ?? 0) == 8) {
          // 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']     = (int)$user['role_id']; // يجب أن يكون 8
          
          // Store the role in session for redirection
          $_SESSION['user_role'] = 'student_affairs';

          // Redirect to student affairs dashboard
          header("Location: student_affairs_dashboard.php");
          exit;
        } else {
          $error = 'بيانات الاعتماد غير صحيحة أو ليس لديك صلاحية الدخول كعمادة شؤون الطلاب.';
          if ($DEBUG) {
            $error .= ' تحقق من سجلات الأخطاء للحصول على معلومات تصحيح تفصيلية.';
          }
        }
      }
    }
  } catch (Throwable $e) {
    error_log("[student_affairs_login][EXC] ".$e->getMessage()." @ ".$e->getFile().":".$e->getLine());
    $error = $DEBUG ? ('خطأ: '.$e->getMessage()) : 'حدث خطأ في الخادم.';
  }
}

/* ===== 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">
    <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: #00796B; /* Teal color for student affairs */
            --secondary-color: #4DB6AC;
            --accent-color: #FFD54F;
            --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%, #009688 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(0, 121, 107, 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(0, 121, 107, 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;
            -webkit-appearance: none;
            -moz-appearance: none;
            appearance: none;
        }

        .password-toggle:hover {
            color: var(--primary-color);
            background: rgba(0, 121, 107, 0.1);
        }

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

        .login-btn {
            width: 100%;
            height: 60px;
            background: linear-gradient(135deg, var(--primary-color), #009688);
            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(0, 121, 107, 0.25);
        }

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

        .login-btn i {
            margin-left: 12px;
            font-size: 1.3rem;
            pointer-events: 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), #009688);
            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(0, 121, 107, 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(0, 121, 107, 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);
        }

        /* إضافة مؤشر اليد لجميع العناصر القابلة للنقر */
        button, 
        [type="button"], 
        [type="submit"], 
        [type="reset"],
        a,
        .btn,
        .clickable {
            cursor: pointer !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: 12px 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;
            }
            
            .back-home-link {
                max-width: 260px;
                padding: 12px 20px;
                font-size: 0.95rem;
            }
            
            .input-container .input-icon {
                right: 15px;
                font-size: 1.2rem;
            }
            
            .password-toggle {
                left: 15px;
                width: 40px;
                height: 40px;
                font-size: 1.1rem;
            }
        }
    </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-users"></i>
                        <span>إدارة الأنشطة الطلابية والمنظمات</span>
                    </li>
                    <li>
                        <i class="fas fa-handshake"></i>
                        <span>تقديم الخدمات والدعم للطلاب</span>
                    </li>
                    <li>
                        <i class="fas fa-calendar-alt"></i>
                        <span>تنظيم الفعاليات والأنشطة الطلابية</span>
                    </li>
                    <li>
                        <i class="fas fa-chart-bar"></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-users"></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="student_affairs_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" id="submitBtn">
                        <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="index.php" 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(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 and 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 = '<i class="fas fa-spinner fa-spin"></i> جاري تسجيل الدخول...';
            
            // 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();
            }
            
            // تأكيد أن جميع الأزرار لها مؤشر اليد
            const buttons = document.querySelectorAll('button, .login-btn, .back-home-link, .lang-btn, [type="button"], [type="submit"]');
            buttons.forEach(button => {
                button.style.cursor = 'pointer';
            });
            
            // تأكيد أن جميع الروابط لها مؤشر اليد
            const links = document.querySelectorAll('a');
            links.forEach(link => {
                link.style.cursor = 'pointer';
            });
        });
        
        // Disable right-click on sensitive areas (optional security)
        document.querySelector('.login-right').addEventListener('contextmenu', function(e) {
            e.preventDefault();
            return false;
        });
    </script>
</body>
</html>