<?php

require_once __DIR__ . "/jwt.php";

function getUserFromToken() {

    $auth = '';

    if (isset($_SERVER['HTTP_AUTHORIZATION'])) {
        $auth = $_SERVER['HTTP_AUTHORIZATION'];
    } elseif (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) {
        $auth = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
    } else {
        $headers = function_exists('getallheaders') ? getallheaders() : [];
        if (isset($headers['Authorization'])) {
            $auth = $headers['Authorization'];
        }
    }

    if (!$auth) {
        echo json_encode(["message" => "Unauthorized"]);
        exit;
    }

    if (!preg_match('/Bearer\s(\S+)/', $auth, $matches)) {
        echo json_encode(["message" => "Unauthorized"]);
        exit;
    }

    $token = $matches[1];

    $decoded = JWTService::verify($token);

    if (!$decoded) {
        echo json_encode(["message" => "Unauthorized"]);
        exit;
    }

    /// 🔥 FIX UTAMA DI SINI (support dua format)
    $user_id = $decoded['user_id'] ?? $decoded['id'] ?? null;

    if (!$user_id) {
        echo json_encode(["message" => "Unauthorized"]);
        exit;
    }

    return $user_id;
}