<?php
// committee_login.php - COMMITTEE REGISTRAR ONLY (ROLE_ID = 2)
error_reporting(0);
ini_set('display_errors', 0);

// Debug toggle
$DEBUG = isset($_GET['debug']) && $_GET['debug'] === '1';
if ($DEBUG) {
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);
}

// Start session
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Check if already logged in as committee registrar (role_id = 2)
if (isset($_SESSION['committee_role_id']) && $_SESSION['committee_role_id'] == 2) {
    header("Location: committee_dashboard.php");
    exit;
}

// If logged in with other role_id, destroy session
if (isset($_SESSION['committee_role_id']) && $_SESSION['committee_role_id'] != 2) {
    session_destroy();
    session_start();
}

// Simple database connection
require 'db.php';
@$mysqli1->set_charset('utf8mb4');

// Define committee registrar role ONLY
$role_info = [
    'name' => 'مسجل الكلية',
    'color' => '#006400',
    'icon' => 'fas fa-university',
    'role' => 'committee',
    'role_id' => 2  // Fixed role_id = 2
];

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

// Handle login
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['username']) && isset($_POST['password'])) {
    $username = trim($_POST['username']);
    $password = $_POST['password'];
    
    // Validation
    if (empty($username) || empty($password)) {
        $error = 'اسم المستخدم وكلمة المرور مطلوبان';
    } else {
        try {
            // Check ONLY for users with role_id = 2
            $stmt = @$mysqli1->prepare("SELECT id, username, password_hash, name, can_view_all, college_id, role_id FROM committee_users WHERE username = ? AND role_id = 2 LIMIT 1");
            if ($stmt) {
                $stmt->bind_param("s", $username);
                $stmt->execute();
                $result = $stmt->get_result();
                $user = $result->fetch_assoc();
                $stmt->close();
                
                if ($user) {
                    // Check password using comprehensive method
                    $ok = false;
                    
                    // Prefer strong hash if stored
                    $info = password_get_info($user['password_hash']);
                    if (!empty($info['algo'])) {
                        $ok = password_verify($password, $user['password_hash']);
                    } else {
                        // Legacy: stored as plaintext in password_hash column
                        // Test multiple comparison methods
                        
                        // Method 1: Exact comparison
                        $method1 = ($user['password_hash'] === $password);
                        
                        // Method 2: Trimmed comparison
                        $stored_clean = trim($user['password_hash']);
                        $input_clean = trim($password);
                        $method2 = ($stored_clean === $input_clean);
                        
                        // Method 3: Case-insensitive
                        $method3 = (strcasecmp($stored_clean, $input_clean) === 0);
                        
                        // Method 4: MD5 comparison (if someone stored MD5 hashes)
                        $method4 = (md5($password) === $user['password_hash']);
                        
                        $ok = $method1 || $method2 || $method3 || $method4;
                    }
                    
                    if ($ok) {
                        // Store ALL user data in session
                        $_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']; // Must be 2
                        
                        // Store the role in session
                        $_SESSION['user_role'] = 'committee';

                        // Double check that role_id is 2
                        if ($_SESSION['committee_role_id'] == 2) {
                            header("Location: committee_dashboard.php");
                            exit;
                        } else {
                            $error = 'خطأ: المستخدم ليس لديه الصلاحية المطلوبة';
                            session_destroy();
                        }
                    } else {
                        $error = 'كلمة المرور غير صحيحة';
                    }
                } else {
                    // Check if user exists but has different role_id
                    $stmt2 = @$mysqli1->prepare("SELECT role_id FROM committee_users WHERE username = ? LIMIT 1");
                    if ($stmt2) {
                        $stmt2->bind_param("s", $username);
                        $stmt2->execute();
                        $result2 = $stmt2->get_result();
                        if ($result2->num_rows > 0) {
                            $user_data = $result2->fetch_assoc();
                            if ($user_data['role_id'] != 2) {
                                $error = 'المستخدم ليس لديه صلاحية مسجل الكلية (role_id يجب أن يكون 2)';
                            } else {
                                $error = 'اسم المستخدم أو كلمة المرور غير صحيحة';
                            }
                        } else {
                            $error = 'اسم المستخدم غير موجود';
                        }
                        $stmt2->close();
                    } else {
                        $error = 'اسم المستخدم غير موجود';
                    }
                }
            } else {
                $error = 'خطأ في النظام';
            }
        } catch (Throwable $e) {
            error_log("[committee_login][EXC] ".$e->getMessage()." @ ".$e->getFile().":".$e->getLine());
            $error = $DEBUG ? ('Exception: '.$e->getMessage()) : 'خطأ في الخادم';
        }
    }
}

// Check if committee user (role_id = 2) exists in database, if not, create one
$result = @$mysqli1->query("SELECT id FROM committee_users WHERE role_id = 2 LIMIT 1");
if (!$result || $result->num_rows === 0) {
    // Create default committee registrar user with role_id = 2
    $default_password = 'committee#123';
    $hash = password_hash($default_password, PASSWORD_DEFAULT);
    $insert_query = "INSERT INTO committee_users (username, password_hash, name, can_view_all, role_id, role_name, created_at) 
                    VALUES ('registrar', '$hash', 'مسجل الكلية', 1, 2, 'committee', NOW())";
    @$mysqli1->query($insert_query);
}

?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>تسجيل الدخول - نظام تسجيل الكلية</title>
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;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>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: 'Cairo', sans-serif;
            background: linear-gradient(135deg, #1a2980, #26d0ce);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        .login-container {
            width: 100%;
            max-width: 450px;
        }
        .login-card {
            background: white;
            border-radius: 15px;
            padding: 35px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            text-align: center;
            border-top: 5px solid #006400;
        }
        .header-icon {
            background: #006400;
            color: white;
            width: 90px;
            height: 90px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 25px;
            font-size: 2.5rem;
            box-shadow: 0 4px 15px rgba(0, 100, 0, 0.3);
        }
        .university-name {
            color: #006400;
            font-weight: 800;
            margin-bottom: 10px;
            font-size: 1.4rem;
            text-shadow: 1px 1px 2px rgba(0,0,0,0.1);
        }
        .login-title {
            text-align: center;
            margin-bottom: 15px;
            color: #333;
            font-size: 1.6rem;
        }
        .role-badge {
            display: inline-block;
            background: #e6f7e6;
            color: #006400;
            padding: 5px 15px;
            border-radius: 20px;
            font-size: 0.9rem;
            font-weight: 600;
            margin-bottom: 25px;
            border: 1px solid #b3e6b3;
        }
        .login-subtitle {
            color: #666;
            margin-bottom: 30px;
            font-size: 1rem;
            line-height: 1.6;
        }
        .form-group {
            margin-bottom: 25px;
        }
        .form-label {
            display: block;
            margin-bottom: 10px;
            color: #555;
            font-weight: 700;
            text-align: right;
            font-size: 1.05rem;
        }
        .form-control {
            width: 100%;
            padding: 14px 18px;
            border: 2px solid #ddd;
            border-radius: 10px;
            font-size: 1.05rem;
            font-family: 'Cairo', sans-serif;
            transition: all 0.3s;
            background: #f9f9f9;
        }
        .form-control:focus {
            outline: none;
            border-color: #006400;
            background: white;
            box-shadow: 0 0 0 3px rgba(0, 100, 0, 0.1);
        }
        .input-with-icon {
            position: relative;
        }
        .btn-login {
            width: 100%;
            padding: 16px;
            background: linear-gradient(to right, #006400, #008000);
            color: white;
            border: none;
            border-radius: 10px;
            font-size: 1.2rem;
            font-weight: 800;
            cursor: pointer;
            transition: all 0.3s;
            margin-top: 15px;
            letter-spacing: 1px;
            box-shadow: 0 4px 15px rgba(0, 100, 0, 0.2);
        }
        .btn-login:hover {
            background: linear-gradient(to right, #004d00, #006400);
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(0, 100, 0, 0.3);
        }
        .btn-login:active {
            transform: translateY(0);
        }
        .alert {
            padding: 15px;
            border-radius: 10px;
            margin-bottom: 25px;
            background: #ffe6e6;
            color: #cc0000;
            border: 2px solid #ff9999;
            text-align: center;
            font-weight: 600;
        }
        .system-info {
            background: #f0f8ff;
            border-radius: 10px;
            padding: 18px;
            margin-top: 25px;
            text-align: center;
            border: 2px dashed #b3d9ff;
            font-size: 0.95rem;
            color: #336699;
        }
        .password-toggle {
            position: absolute;
            left: 18px;
            top: 50%;
            transform: translateY(-50%);
            color: #666;
            cursor: pointer;
            background: white;
            padding: 8px;
            border-radius: 50%;
            transition: all 0.3s;
        }
        .password-toggle:hover {
            background: #f0f0f0;
            color: #006400;
        }
        .default-user {
            background: linear-gradient(to right, #e8f4fd, #d9edf7);
            border-radius: 10px;
            padding: 15px;
            margin-top: 25px;
            text-align: center;
            border: 2px solid #b3d9ff;
            font-size: 0.9rem;
        }
        .default-user-title {
            font-weight: bold;
            margin-bottom: 12px;
            color: #2980b9;
            font-size: 1rem;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }
        .cred-item {
            display: flex;
            justify-content: space-between;
            padding: 8px 0;
            font-family: 'Cairo', monospace;
            border-bottom: 1px dashed #ccc;
        }
        .cred-item:last-child {
            border-bottom: none;
        }
        .note {
            margin-top: 12px;
            font-size: 0.8rem;
            color: #7f8c8d;
            font-style: italic;
        }
        .restriction-note {
            background: #fff8e1;
            border-radius: 8px;
            padding: 12px;
            margin-top: 20px;
            text-align: center;
            border: 1px solid #ffd54f;
            font-size: 0.85rem;
            color: #5d4037;
        }
        @media (max-width: 480px) {
            .login-card { padding: 25px; }
            .header-icon { width: 70px; height: 70px; font-size: 2rem; }
            .login-title { font-size: 1.4rem; }
        }
    </style>
</head>
<body>
    <div class="login-container">
        <div class="login-card">
            <!-- Header Icon -->
            <div class="header-icon">
                <i class="fas fa-university"></i>
            </div>
            
            <!-- Title and Badge -->
            <div class="university-name">نظام تسجيل الكلية</div>
            <h2 class="login-title">تسجيل الدخول - مسجلي الكليات فقط</h2>
            <div class="role-badge">
                <i class="fas fa-user-check"></i> نظام خاص بمسجلي الكليات (role_id = 2)
            </div>
            <div class="login-subtitle">
                نظام آمن خاص بتسجيل الطلاب وإدارة بياناتهم<br>
                <strong>مسؤولي التسجيل بالكليات فقط (role_id = 2)</strong>
            </div>
            
            <!-- Error Message -->
            <?php if ($error): ?>
                <div class="alert">
                    <i class="fas fa-exclamation-circle"></i>
                    <?php echo htmlspecialchars($error); ?>
                </div>
            <?php endif; ?>
            
            <!-- Login Form -->
            <form method="post">
                <div class="form-group">
                    <label class="form-label">
                        <i class="fas fa-user"></i> اسم المستخدم
                    </label>
                    <div class="input-with-icon">
                        <input type="text" 
                               class="form-control" 
                               name="username" 
                               value="<?php echo htmlspecialchars($username); ?>"
                               placeholder="أدخل اسم المستخدم"
                               required
                               autofocus>
                    </div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">
                        <i class="fas fa-lock"></i> كلمة المرور
                    </label>
                    <div class="input-with-icon">
                        <input type="password" 
                               class="form-control" 
                               name="password" 
                               placeholder="أدخل كلمة المرور"
                               required
                               id="passwordInput">
                        <span class="password-toggle" id="togglePassword">
                            <i class="fas fa-eye"></i>
                        </span>
                    </div>
                </div>
                
                <button type="submit" class="btn-login">
                    <i class="fas fa-sign-in-alt"></i> دخول كمسجل كلية
                </button>
            </form>
            
            <!-- Restriction Note -->
            <div class="restriction-note">
                <i class="fas fa-exclamation-triangle"></i>
                <strong>تنبيه:</strong> هذا النظام خاص بمسجلي الكليات فقط. جميع المستخدمين الآخرين ممنوعون من الدخول.
            </div>
            
            <!-- Default User Info -->
            <div class="default-user">
                <div class="default-user-title">
                    <i class="fas fa-user-circle"></i> مستخدم افتراضي
                </div>
                <div class="cred-item">
                    <span>اسم المستخدم:</span>
                    <strong style="color: #006400;">registrar</strong>
                </div>
                <div class="cred-item">
                    <span>كلمة المرور:</span>
                    <strong style="color: #cc0000;">committee#123</strong>
                </div>
                <div class="note">
                    <i class="fas fa-info-circle"></i> سيتم إنشاء هذا المستخدم تلقائياً إذا لم يكن موجوداً
                </div>
            </div>
            
            <!-- System Info -->
            <div class="system-info">
                <i class="fas fa-shield-alt"></i> 
                نظام آمن خاص بتسجيل وإدارة بيانات الطلاب - مسجلي الكليات فقط (role_id = 2)
            </div>
        </div>
    </div>

    <script>
        // Toggle password visibility
        document.getElementById('togglePassword').addEventListener('click', function() {
            const passwordInput = document.getElementById('passwordInput');
            const icon = this.querySelector('i');
            
            if (passwordInput.type === 'password') {
                passwordInput.type = 'text';
                icon.classList.remove('fa-eye');
                icon.classList.add('fa-eye-slash');
                this.style.color = '#006400';
            } else {
                passwordInput.type = 'password';
                icon.classList.remove('fa-eye-slash');
                icon.classList.add('fa-eye');
                this.style.color = '#666';
            }
        });
        
        // Auto-focus on username and enhance UX
        document.addEventListener('DOMContentLoaded', function() {
            const usernameInput = document.querySelector('input[name="username"]');
            usernameInput.focus();
            
            // Add input validation styling
            const inputs = document.querySelectorAll('.form-control');
            inputs.forEach(input => {
                input.addEventListener('blur', function() {
                    if (this.value.trim() === '') {
                        this.style.borderColor = '#ff9999';
                    } else {
                        this.style.borderColor = '#ddd';
                    }
                });
            });
        });
    </script>
</body>
</html>