<?php
// includes/auth.php
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/database.php';

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

/**
 * Attempt to login the user.
 * @param string $email
 * @param string $password
 * @return array ['success' => bool, 'message' => string, 'role' => string|null]
 */
function loginUser($email, $password) {
    $pdo = getDatabaseConnection();

    // Brute-force throttle: 5 failures / 10 min per email+IP
    if (throttle_check($pdo, $email)) {
        return ['success' => false, 'message' => 'Too many failed attempts. Please wait 10 minutes and try again.'];
    }

    $stmt = $pdo->prepare("SELECT id, name, email, password, role FROM users WHERE email = ?");
    $stmt->execute([$email]);
    $user = $stmt->fetch();

    if ($user && password_verify($password, $user['password'])) {
        throttle_clear($pdo, $email);

        // Prevent Session Fixation
        session_regenerate_id(true);

        $_SESSION['user_id'] = $user['id'];
        $_SESSION['user_name'] = $user['name'];
        $_SESSION['user_role'] = $user['role'];

        return ['success' => true, 'message' => 'Login successful', 'role' => $user['role']];
    }

    throttle_record($pdo, $email);
    return ['success' => false, 'message' => 'Invalid email or password'];
}

/**
 * Check if the user is logged in.
 * @return bool
 */
function isLoggedIn() {
    return isset($_SESSION['user_id']);
}

/**
 * Check if the user has a specific role.
 * @param string $role
 * @return bool
 */
function hasRole($role) {
    return isset($_SESSION['user_role']) && $_SESSION['user_role'] === $role;
}

/**
 * Require login. Redirects to login page if not logged in.
 */
function requireLogin() {
    if (!isLoggedIn()) {
        header('Location: ' . APP_URL . '/admin/login.php');
        exit;
    }
}

/**
 * Require a specific role. Redirects if unauthorized.
 * @param string|array $roles
 */
function requireRole($roles) {
    requireLogin();
    
    if (!is_array($roles)) {
        $roles = [$roles];
    }

    if (!in_array($_SESSION['user_role'], $roles)) {
        // If logged in but unauthorized, send them to their respective dashboard
        $role = $_SESSION['user_role'];
        if ($role === 'ADMIN') header('Location: ' . APP_URL . '/admin/dashboard.php');
        elseif ($role === 'ORGANIZER') header('Location: ' . APP_URL . '/organizer/dashboard.php');
        elseif ($role === 'FINANCE') header('Location: ' . APP_URL . '/finance/dashboard.php');
        else header('Location: ' . APP_URL . '/');
        exit;
    }
}

/**
 * Logout the user.
 */
function logoutUser() {
    session_unset();
    session_destroy();
    header('Location: ' . APP_URL . '/admin/login.php');
    exit;
}
