<?php

function generate_token(): string
{
    return bin2hex(random_bytes(32));
}

function authenticate(PDO $pdo): array
{
    $auth_header = null;

    if (function_exists('getallheaders')) {
        $headers = getallheaders();
        $auth_header = $headers['Authorization'] ?? null;
    }

    if (!$auth_header && isset($_SERVER['HTTP_AUTHORIZATION'])) {
        $auth_header = $_SERVER['HTTP_AUTHORIZATION'];
    }

    if (!$auth_header) {
        json_response(false, 'Missing Authorization header.', [], 401);
    }

    if (!preg_match('/Bearer\s(\S+)/', $auth_header, $matches)) {
        json_response(false, 'Invalid Authorization format.', [], 401);
    }

    $token = trim($matches[1]);

    $stmt = $pdo->prepare("
        SELECT 
            u.id,
            u.company_id,
            u.role,
            u.first_name,
            u.last_name,
            u.email,
            u.status,
            c.rsp_id
        FROM api_tokens t
        JOIN users u ON u.id = t.user_id
        LEFT JOIN companies c ON c.id = u.company_id
        WHERE t.token = ?
        AND t.expires_at > NOW()
        LIMIT 1
    ");

    $stmt->execute([$token]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        json_response(false, 'Invalid or expired token.', [], 401);
    }

    if ($user['status'] !== 'active') {
        json_response(false, 'User account inactive.', [], 403);
    }

    /*
        Platform admin may not belong to company.
        All other roles must have valid company + rsp.
    */

    /* Super Admin full bypass */
    if ($user['role'] === 'super_admin') {
        return $user;
    }
    
    /* Other roles must belong to company + RSP */
    if (empty($user['company_id']) || empty($user['rsp_id'])) {
        json_response(false, 'User not linked to valid RSP.', [], 403);
    }

    return $user;
}