<?php
/**
 * TrackPro — Authentication Helper
 */

require_once __DIR__ . '/db.php';

function startSecureSession(): void {
    if (session_status() === PHP_SESSION_NONE) {
        session_set_cookie_params([
            'lifetime' => 0,
            'path'     => '/',
            'secure'   => isset($_SERVER['HTTPS']),
            'httponly'  => true,
            'samesite'  => 'Strict',
        ]);
        session_start();
    }
}

function login(string $username, string $password): array {
    $pdo = getDB();
    $stmt = $pdo->prepare("SELECT * FROM `users` WHERE (`username` = ? OR `email` = ?) AND `is_active` = 1");
    $stmt->execute([$username, $username]);
    $user = $stmt->fetch();

    if (!$user || !password_verify($password, $user['password_hash'])) {
        return ['success' => false, 'error' => 'Invalid credentials'];
    }

    // Regenerate session
    session_regenerate_id(true);
    $_SESSION['user_id']   = $user['id'];
    $_SESSION['username']  = $user['username'];
    $_SESSION['role']      = $user['role'];
    $_SESSION['logged_in'] = true;
    $_SESSION['login_time'] = time();

    // Update last login
    $pdo->prepare("UPDATE `users` SET `last_login` = NOW() WHERE `id` = ?")->execute([$user['id']]);
    auditLog('login', $user['id']);

    return ['success' => true, 'user' => $user];
}

function logout(): void {
    if (isset($_SESSION['user_id'])) {
        auditLog('logout', $_SESSION['user_id']);
    }
    $_SESSION = [];
    if (ini_get('session.use_cookies')) {
        $params = session_get_cookie_params();
        setcookie(session_name(), '', time() - 42000, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
    }
    session_destroy();
}

function requireAuth(array $allowedRoles = []): void {
    startSecureSession();
    if (empty($_SESSION['logged_in']) || empty($_SESSION['user_id'])) {
        header('Location: login.php');
        exit;
    }
    // Session timeout (2 hours)
    if (time() - ($_SESSION['login_time'] ?? 0) > 7200) {
        logout();
        header('Location: login.php?expired=1');
        exit;
    }
    if (!empty($allowedRoles) && !in_array($_SESSION['role'], $allowedRoles)) {
        http_response_code(403);
        echo "Access denied.";
        exit;
    }
}

function currentUser(): ?array {
    if (empty($_SESSION['user_id'])) return null;
    $stmt = getDB()->prepare("SELECT `id`, `username`, `email`, `role`, `last_login` FROM `users` WHERE `id` = ?");
    $stmt->execute([$_SESSION['user_id']]);
    return $stmt->fetch() ?: null;
}

function hasRole(string ...$roles): bool {
    return in_array($_SESSION['role'] ?? '', $roles);
}
