<?php
// This middleware script is included in protected API endpoints.
// It validates the JWT and makes the user's data available.

$user = new User();
$user_id = $user->getUserIdFromToken();

if (!$user_id) {
    http_response_code(401); // Unauthorized
    echo json_encode(['message' => 'Unauthorized. A valid token is required.']);
    exit();
}

// Token is valid, fetch user data to make it available to the endpoint
$authenticated_user = $user->findById($user_id);

if (!$authenticated_user) {
    http_response_code(401); // Unauthorized
    echo json_encode(['message' => 'Unauthorized. User not found.']);
    exit();
}

$authenticated_user_data = $authenticated_user; // Make user data available in the including script
?>