<?php
require_once 'core/bootstrap.php';

// --- Security Check ---
// Only allow access from localhost OR if logged in as super_admin
$is_localhost = in_array($_SERVER['REMOTE_ADDR'], ['127.0.0.1', '::1']);
$is_super_admin = isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'super_admin';

if (!$is_localhost && !$is_super_admin) {
    die('Access Denied: Development environment or Super Admin only.');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $db = new Database();
    $user = null;
    
    if (isset($_POST['role'])) {
        $role = $_POST['role'];
        $db->query("SELECT * FROM users WHERE role = :role LIMIT 1");
        $db->bind(':role', $role);
        $user = $db->single();
    } elseif (isset($_POST['username'])) {
        $username = $_POST['username'];
        $db->query("SELECT * FROM users WHERE username = :username");
        $db->bind(':username', $username);
        $user = $db->single();
    }

    if ($user) {
        // 1. Clear existing session
        session_unset();
        session_destroy();
        session_start();

        // 2. Set User Session
        $_SESSION['user_id'] = $user->id;
        $_SESSION['user_email'] = $user->email;
        $_SESSION['user_name'] = $user->first_name . ' ' . $user->last_name;
        $_SESSION['user_role'] = $user->role;
        $_SESSION['username'] = $user->username;
        
        // 3. Set Admin Session (if applicable)
        // This ensures compatibility with admin pages that might check these specific keys
        if (in_array($user->role, ['admin', 'super_admin', 'league_manager', 'fixtures_manager', 'super_fantasy_manager', 'finance_manager'])) {
            $_SESSION['admin_user_id'] = $user->id;
            $_SESSION['admin_user_email'] = $user->email;
            $_SESSION['admin_user_name'] = $user->first_name . ' ' . $user->last_name;
            $_SESSION['admin_user_role'] = $user->role;
        }

        // 4. Redirect based on role
        if (in_array($user->role, ['admin', 'super_admin', 'league_manager', 'fixtures_manager', 'super_fantasy_manager', 'finance_manager'])) {
            header('Location: admin/dashboard.php');
        } else {
            header('Location: app/index.php');
        }
        exit();
    } else {
        die("User not found.");
    }
}

// Fallback
header('Location: index.php');
exit();
?>