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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    // Redirect if accessed directly
    header('Location: login.php');
    exit();
}

$email = trim($_POST['email'] ?? '');
$password = $_POST['password'] ?? '';

if (empty($email) || empty($password)) {
    header('Location: login.php?error=missing_fields');
    exit();
}

$userModel = new User();
$loggedInUser = $userModel->login($email, $password);

if ($loggedInUser) {
    // Login successful, set session variables
    $_SESSION['user_id'] = $loggedInUser->id;
    $_SESSION['user_role'] = $loggedInUser->role;
    $_SESSION['user_name'] = $loggedInUser->first_name;
    $_SESSION['user_email'] = $loggedInUser->email;

    // --- Role-based Redirect ---
    // Define roles that should only access the backend admin panel.
    $admin_roles = ['super_admin', 'admin', 'league_manager', 'fixtures_manager'];

    if (in_array($loggedInUser->role, $admin_roles, true)) {
        // Redirect admin users to the admin backend.
        header('Location: ' . URL_ROOT . '/admin/index.php');
    } else {
        // Redirect front-end users (player, referee, user, etc.) to the app homepage.
        header('Location: index.php');
    }
    exit();
} else {
    // Login failed
    header('Location: login.php?error=invalid_credentials');
    exit();
}
?>