<?php
// unified_login.php - SIMPLIFIED AND OPTIMIZED VERSION
error_reporting(0); // Turn off error reporting for production
ini_set('display_errors', 0);

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

// Check if already logged in
if (isset($_SESSION['committee_id'])) {
    // Simple redirect based on role
    $role = $_SESSION['user_role'] ?? 'committee';
    $dashboards = [
        'admin' => 'admin_dashboard.php',
        'accountant' => 'accountant_dashboard.php',
        'card_printing' => 'card_printing_dashboard.php',
        'committee' => 'committee_dashboard.php'
    ];
    
    $dashboard = $dashboards[$role] ?? 'committee_dashboard.php';
    header("Location: $dashboard");
    exit;
}

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

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

// 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
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['username']) && isset($_POST['password'])) {
    $username = trim($_POST['username']);
    $password = $_POST['password'];
    $role = isset($_POST['role']) ? $_POST['role'] : 'committee';
    
    // Simple validation
    if (empty($username) || empty($password)) {
        $error = 'اسم المستخدم وكلمة المرور مطلوبان';
    } else {
        // Check for default admin
        if ($username === 'admin' && $password === 'admin#778855') {
            // Quick admin check
            $result = @$mysqli1->query("SELECT id FROM committee_users WHERE username = 'admin' LIMIT 1");
            
            if (!$result || $result->num_rows === 0) {
                // Create admin if doesn't exist
                $hash = password_hash($password, PASSWORD_DEFAULT);
                @$mysqli1->query("INSERT INTO committee_users (username, password_hash, name, can_view_all, role_id, role_name, created_at) 
                                 VALUES ('admin', '$hash', 'Administrator', 1, 1, 'admin', NOW())");
                
                $admin_id = $mysqli1->insert_id;
                $_SESSION['committee_id'] = $admin_id;
                $_SESSION['committee_username'] = 'admin';
                $_SESSION['committee_name'] = 'Administrator';
                $_SESSION['committee_can_all'] = 1;
                $_SESSION['user_role'] = $role;
                
                header("Location: admin_dashboard.php");
                exit;
            } else {
                $admin = $result->fetch_assoc();
                $_SESSION['committee_id'] = $admin['id'];
                $_SESSION['committee_username'] = 'admin';
                $_SESSION['committee_name'] = 'Administrator';
                $_SESSION['committee_can_all'] = 1;
                $_SESSION['user_role'] = $role;
                
                header("Location: admin_dashboard.php");
                exit;
            }
        }
        
        // Regular user login
        $stmt = @$mysqli1->prepare("SELECT id, username, password_hash, name, can_view_all, role_id FROM committee_users WHERE username = ? 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
                if (password_verify($password, $user['password_hash']) || $user['password_hash'] === $password) {
                    $_SESSION['committee_id'] = $user['id'];
                    $_SESSION['committee_username'] = $user['username'];
                    $_SESSION['committee_name'] = $user['name'];
                    $_SESSION['committee_can_all'] = ($user['can_view_all'] == 1);
                    $_SESSION['user_role'] = $role;
                    
                    // Redirect based on role
                    $dashboard = [
                        'admin' => 'admin_dashboard.php',
                        'accountant' => 'accountant_dashboard.php',
                        'card_printing' => 'card_printing_dashboard.php',
                        'committee' => 'committee_dashboard.php'
                    ][$role] ?? 'committee_dashboard.php';
                    
                    header("Location: $dashboard");
                    exit;
                } else {
                    $error = 'كلمة المرور غير صحيحة';
                }
            } else {
                $error = 'اسم المستخدم غير موجود';
            }
        } else {
            $error = 'خطأ في النظام';
        }
    }
}

// Simple HTML output starts immediately
?>
<!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 htmlspecialchars($role_info['name']); ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700&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: 400px;
        }
        .login-card {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
        }
        .role-tabs {
            display: flex;
            justify-content: center;
            gap: 10px;
            margin-bottom: 20px;
            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;
        }
        .role-tab:hover {
            background: #e9ecef;
        }
        .role-tab.active {
            background: <?php echo $role_info['color']; ?>;
            color: white;
        }
        .login-title {
            text-align: center;
            margin-bottom: 25px;
            color: #333;
            font-size: 1.5rem;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
        }
        .form-group {
            margin-bottom: 20px;
        }
        .form-label {
            display: block;
            margin-bottom: 8px;
            color: #555;
            font-weight: 600;
        }
        .form-control {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 1rem;
            font-family: 'Cairo', sans-serif;
            transition: border-color 0.3s;
        }
        .form-control:focus {
            outline: none;
            border-color: <?php echo $role_info['color']; ?>;
        }
        .input-with-icon {
            position: relative;
        }
        .input-icon {
            position: absolute;
            left: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: #6c757d;
        }
        .btn-login {
            width: 100%;
            padding: 14px;
            background: <?php echo $role_info['color']; ?>;
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 1.1rem;
            font-weight: 700;
            cursor: pointer;
            transition: background 0.3s;
            margin-top: 10px;
        }
        .btn-login:hover {
            background: <?php 
                // Darken color by 10%
                $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;
                }
            ?>;
        }
        .alert {
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 20px;
            background: #fee2e2;
            color: #991b1b;
            border: 1px solid #fecaca;
            text-align: center;
        }
        .admin-info {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            margin-top: 20px;
            text-align: center;
            border: 1px dashed #dee2e6;
        }
        .admin-info h4 {
            color: #6c757d;
            margin-bottom: 10px;
            font-size: 1rem;
        }
        .admin-creds {
            background: white;
            padding: 10px;
            border-radius: 6px;
            margin-top: 10px;
        }
        .cred-item {
            display: flex;
            justify-content: space-between;
            padding: 5px 0;
            font-family: monospace;
        }
        @media (max-width: 480px) {
            .login-card { padding: 20px; }
            .role-tab { padding: 8px 12px; font-size: 0.85rem; }
        }
    </style>
</head>
<body>
    <div class="login-container">
        <div class="login-card">
            <!-- Role Tabs -->
            <div class="role-tabs">
                <?php foreach ($roles as $key => $info): ?>
                    <a href="unified_login.php?role=<?php echo $key; ?>" 
                       class="role-tab <?php echo $selected_role == $key ? 'active' : ''; ?>">
                        <i class="<?php echo $info['icon']; ?>"></i>
                        <?php echo htmlspecialchars($info['name']); ?>
                    </a>
                <?php endforeach; ?>
            </div>
            
            <!-- Title -->
            <h2 class="login-title">
                <i class="<?php echo $role_info['icon']; ?>"></i>
                <?php echo htmlspecialchars($role_info['name']); ?>
            </h2>
            
            <!-- Error Message -->
            <?php if ($error): ?>
                <div class="alert">
                    <i class="fas fa-exclamation-triangle"></i>
                    <?php echo htmlspecialchars($error); ?>
                </div>
            <?php endif; ?>
            
            <!-- Login Form -->
            <form method="post">
                <input type="hidden" name="role" value="<?php echo htmlspecialchars($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 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>
                        <span class="input-icon" id="togglePassword" style="cursor: pointer; right: 15px; left: auto;">
                            <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>
            
            <!-- Admin Credentials Info -->
           <!--   <div class="admin-info">
                <h4><i class="fas fa-info-circle"></i> بيانات الدخول الافتراضية</h4>
                <div class="admin-creds">
                    <div class="cred-item">
                        <span>اسم المستخدم:</span>
                        <strong>admin</strong>
                    </div>
                    <div class="cred-item">
                        <span>كلمة المرور:</span>
                        <strong></strong>
                    </div>
                </div>
                <p style="margin-top: 10px; font-size: 0.8rem; color: #6c757d;">
                    قم بتغيير كلمة المرور بعد أول دخول
                </p>
            </div>  -->
        </div>
    </div>

    <script>
        // Toggle password visibility
        document.getElementById('togglePassword').addEventListener('click', function() {
            const passwordInput = document.querySelector('input[name="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();
    </script>
</body>
</html>