<?php
// unified_login.php - Combined functionality with improved design

error_reporting(E_ALL);
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();
}

/* ===== Database connection ===== */
require 'db.php';
if (isset($mysqli1) && $mysqli1 instanceof mysqli) {
    $mysqli1->set_charset('utf8mb4');
}

/* ===== Helper functions ===== */
if (!function_exists('e')) {
    function e($s) { return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
}
if (!function_exists('csrf_token')) {
    function csrf_token() { 
        if (empty($_SESSION['csrf'])) {
            $_SESSION['csrf'] = bin2hex(random_bytes(16));
        }
        return $_SESSION['csrf']; 
    }
}
if (!function_exists('verify_csrf')) {
    function verify_csrf($t) { 
        return isset($_SESSION['csrf']) && hash_equals($_SESSION['csrf'], (string)$t); 
    }
}

/* ===== Check if already logged in ===== */
if (!empty($_SESSION['committee_id'])) {
    // Check if user has card printing privileges (role_id 1 or 4)
    $user_role_id = $_SESSION['committee_role_id'] ?? null;
    if (in_array($user_role_id, [1, 4])) {
        // Users with role_id 1 (admin) or 4 (card printing) go to card printing dashboard
        header("Location: card_printing_dashboard.php");
        exit;
    } else {
        // Other users go based on their session role
        $user_role = $_SESSION['user_role'] ?? 'committee';
        switch($user_role) {
            case 'accountant':
                header("Location: accountant_dashboard.php");
                exit;
            case 'committee':
            default:
                header("Location: committee_dashboard.php");
                exit;
        }
    }
}

/* ===== Define roles ===== */
$roles = [
    'committee' => ['name' => 'إدارة الكلية', 'color' => '#006400', 'icon' => 'fas fa-users'],
    'card_printing' => ['name' => 'طباعة البطاقات', 'color' => '#f39c12', 'icon' => 'fas fa-id-card'],
    'accountant' => ['name' => 'المحاسب', 'color' => '#27ae60', 'icon' => 'fas fa-calculator']
];

/* ===== Get role from URL ===== */
$selected_role = isset($_GET['role']) && isset($roles[$_GET['role']]) ? $_GET['role'] : 'committee';
$role_info = $roles[$selected_role];

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

/* ===== Handle login POST ===== */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        // Verify CSRF token
        if (!verify_csrf($_POST['csrf'] ?? '')) {
            $error = 'رمز الجلسة غير صالح.';
        } else {
            $username = trim((string)($_POST['username'] ?? ''));
            $password = (string)($_POST['password'] ?? '');
            $role = isset($_POST['role']) ? $_POST['role'] : 'committee';
            
            if ($username === '' || $password === '') {
                $error = 'اسم المستخدم وكلمة المرور مطلوبان.';
            } else {
                // Check database for user
                $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();
                
                $ok = false;
                if ($user) {
                    // COMPREHENSIVE PASSWORD VERIFICATION
                    // Check if password is hashed
                    $info = password_get_info($user['password_hash']);
                    if (!empty($info['algo'])) {
                        // Modern password hash
                        $ok = password_verify($password, $user['password_hash']);
                    } else {
                        // Legacy: stored as plaintext or other format
                        // Try exact comparison first
                        if ($user['password_hash'] === $password) {
                            $ok = true;
                        } else {
                            // Try trimmed comparison
                            $stored_clean = trim($user['password_hash']);
                            $input_clean = trim($password);
                            if ($stored_clean === $input_clean || strcasecmp($stored_clean, $input_clean) === 0) {
                                $ok = true;
                            } else {
                                // Try MD5 (in case passwords were stored as MD5 hashes)
                                $ok = (md5($password) === $user['password_hash']);
                            }
                        }
                    }
                }
                
                if ($ok && $user) {
                    // Store 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']     = isset($user['role_id']) ? (int)$user['role_id'] : null;
                    $_SESSION['user_role'] = $role;

                    // ===== CHECK FOR CARD PRINTING PRIVILEGES =====
                    // Users with role_id 1 (admin) or 4 (card printing) go to card printing dashboard
                    // regardless of the URL parameter
                    if (in_array($_SESSION['committee_role_id'], [1, 4])) {
                        header("Location: card_printing_dashboard.php");
                        exit;
                    }
                    
                    // For other users, redirect based on the URL role parameter
                    switch($role) {
                        case 'accountant':
                            header("Location: accountant_dashboard.php");
                            exit;
                        case 'card_printing':
                            // This should not happen for non-1,4 roles but keep as fallback
                            header("Location: card_printing_dashboard.php");
                            exit;
                        case 'committee':
                        default:
                            header("Location: committee_dashboard.php");
                            exit;
                    }
                } else {
                    $error = 'بيانات الدخول غير صحيحة.';
                    if ($DEBUG) {
                        $error .= ' تحقق من سجلات الأخطاء في الخادم لمزيد من التفاصيل.';
                    }
                }
            }
        }
    } catch (Throwable $e) {
        error_log("[unified_login][EXC] ".$e->getMessage()." @ ".$e->getFile().":".$e->getLine());
        $error = $DEBUG ? ('خطأ: '.$e->getMessage()) : 'حدث خطأ في الخادم.';
    }
}
?>

<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>تسجيل الدخول - <?php echo e($role_info['name']); ?></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, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        .login-container {
            width: 100%;
            max-width: 500px;
        }
        .login-card {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
        }
        
        /* Header Image */
        .header-image {
            text-align: center;
            margin-bottom: 20px;
        }
        .header-image img {
            max-width: 100%;
            max-height: 200px;
            border-radius: 10px;
            object-fit: cover;
        }
        
        /* Role Tabs */
        .role-tabs {
            display: flex;
            justify-content: center;
            gap: 10px;
            margin-bottom: 25px;
            flex-wrap: wrap;
        }
        .role-tab {
            padding: 10px 15px;
            border-radius: 8px;
            background: #f8f9fa;
            color: #6c757d;
            text-decoration: none;
            font-weight: 600;
            font-size: 0.9rem;
            transition: all 0.3s;
            display: flex;
            align-items: center;
            gap: 5px;
            border: 2px solid transparent;
        }
        .role-tab:hover {
            background: #e9ecef;
            transform: translateY(-2px);
        }
        .role-tab.active {
            background: <?php echo $role_info['color']; ?>;
            color: white;
            border-color: <?php echo $role_info['color']; ?>;
        }
        
        /* Title */
        .login-title {
            text-align: center;
            margin-bottom: 25px;
            color: #333;
            font-size: 1.5rem;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
        }
        
        /* Error Message */
        .alert {
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 20px;
            background: #fee2e2;
            color: #991b1b;
            border: 1px solid #fecaca;
            text-align: center;
            font-weight: 600;
        }
        .alert.info {
            background: #dbeafe;
            color: #1e40af;
            border-color: #bfdbfe;
        }
        
        /* Form */
        .form-group {
            margin-bottom: 20px;
        }
        .form-label {
            display: block;
            margin-bottom: 8px;
            color: #555;
            font-weight: 600;
            font-size: 1rem;
        }
        .form-control {
            width: 100%;
            padding: 14px 15px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 1rem;
            font-family: 'Cairo', sans-serif;
            transition: all 0.3s;
        }
        .form-control:focus {
            outline: none;
            border-color: <?php echo $role_info['color']; ?>;
            box-shadow: 0 0 0 3px rgba(<?php 
                $hex = str_replace('#', '', $role_info['color']);
                list($r, $g, $b) = sscanf($hex, "%02x%02x%02x");
                echo "$r,$g,$b";
            ?>, 0.1);
        }
        .input-with-icon {
            position: relative;
        }
        .input-icon {
            position: absolute;
            left: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: #6c757d;
            cursor: pointer;
        }
        .input-icon-right {
            left: auto;
            right: 15px;
        }
        
        /* Button */
        .btn-login {
            width: 100%;
            padding: 16px;
            background: <?php echo $role_info['color']; ?>;
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 1.1rem;
            font-weight: 700;
            cursor: pointer;
            transition: all 0.3s;
            margin-top: 10px;
            font-family: 'Cairo', sans-serif;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        .btn-login:hover {
            background: <?php 
                // Darken color
                $color = $role_info['color'];
                if ($color[0] == '#') {
                    $hex = str_replace('#', '', $color);
                    if (strlen($hex) == 3) {
                        $hex = $hex[0].$hex[0].$hex[1].$hex[1].$hex[2].$hex[2];
                    }
                    $r = hexdec(substr($hex, 0, 2));
                    $g = hexdec(substr($hex, 2, 2));
                    $b = hexdec(substr($hex, 4, 2));
                    $r = max(0, $r - 30);
                    $g = max(0, $g - 30);
                    $b = max(0, $b - 30);
                    echo "#".dechex($r).dechex($g).dechex($b);
                } else {
                    echo $color;
                }
            ?>;
            transform: translateY(-2px);
            box-shadow: 0 6px 12px rgba(0,0,0,0.15);
        }
        
        /* Debug Info */
        .debug-info {
            margin-top: 20px;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 8px;
            border: 1px solid #dee2e6;
            font-size: 0.9rem;
            color: #666;
        }
        
        @media (max-width: 480px) {
            .login-card { padding: 20px; }
            .role-tab { padding: 8px 12px; font-size: 0.85rem; }
            .login-title { font-size: 1.3rem; }
        }
    </style>
</head>
<body>
    <div class="login-container">
        <div class="login-card">
            
            <!-- Header Image -->
            <div class="header-image">
                <img src="img/banar2.jpg" alt="Committee Banner" onerror="this.style.display='none'">
            </div>
            
            <!-- Role Tabs -->
            <div class="role-tabs">
                <?php foreach ($roles as $key => $info): ?>
                    <a href="unified_login.php?role=<?php echo $key; ?><?php echo $DEBUG ? '&debug=1' : ''; ?>" 
                       class="role-tab <?php echo $selected_role == $key ? 'active' : ''; ?>">
                        <i class="<?php echo $info['icon']; ?>"></i>
                        <?php echo e($info['name']); ?>
                    </a>
                <?php endforeach; ?>
            </div>
            
            <!-- Title -->
            <h2 class="login-title">
                <i class="<?php echo $role_info['icon']; ?>"></i>
                <?php echo e($role_info['name']); ?>
            </h2>
            
            <!-- Error Message -->
            <?php if ($error): ?>
                <div class="alert">
                    <i class="fas fa-exclamation-triangle"></i>
                    <?php echo e($error); ?>
                </div>
            <?php endif; ?>
            
            <?php if ($DEBUG): ?>
            <div class="alert info">
                <h6>وضع التصحيح مفعل</h6>
                <p>تحقق من سجلات الأخطاء في الخادم لمعلومات تصحيح تسجيل الدخول الشاملة.</p>
                <p>معرف الجلسة: <?php echo session_id(); ?></p>
                <p>الدور المحدد: <?php echo e($selected_role); ?></p>
                <p class="mb-0">ملاحظة: المستخدمون برقم دور 1 أو 4 سيتم توجيههم إلى لوحة طباعة البطاقات</p>
            </div>
            <?php endif; ?>
            
            <!-- Login Form -->
            <form method="post">
                <input type="hidden" name="csrf" value="<?php echo e(csrf_token()); ?>">
                <input type="hidden" name="role" value="<?php echo e($selected_role); ?>">
                
                <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 e($username); ?>"
                               placeholder="أدخل اسم المستخدم"
                               required
                               autofocus>
                        <span class="input-icon">
                            <i class="fas fa-user"></i>
                        </span>
                    </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" 
                               id="password"
                               placeholder="أدخل كلمة المرور"
                               required>
                        <span class="input-icon input-icon-right" 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> دخول إلى <?php echo e($role_info['name']); ?>
                </button>
            </form>
            
            <?php if ($DEBUG): ?>
            <div class="debug-info">
                <p><strong>معلومات التصحيح:</strong></p>
                <p>معرف الجلسة: <?php echo session_id(); ?></p>
                <p>الرمز المميز لـ CSRF: <?php echo substr(e(csrf_token()), 0, 10); ?>...</p>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <script>
        // Toggle password visibility
        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');
            }
        });
        
        // Auto-focus on username
        document.querySelector('input[name="username"]').focus();
        
        // Add animation to form
        document.querySelector('form').addEventListener('submit', function(e) {
            const button = this.querySelector('.btn-login');
            button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> جاري الدخول...';
            button.disabled = true;
        });
    </script>
</body>
</html>