<?php
require_once '../config/jwt.php';

function getBearerToken() {
    $headers = getallheaders();

    if (!isset($headers['Authorization'])) return null;

    if (preg_match('/Bearer\s(\S+)/', $headers['Authorization'], $matches)) {
        return $matches[1];
    }

    return null;
}

function auth() {
    $token = getBearerToken();

    if (!$token) {
        http_response_code(401);
        echo json_encode(["error" => "Unauthorized"]);
        exit;
    }

    $data = verifyJWT($token);

    if (!$data) {
        http_response_code(401);
        echo json_encode(["error" => "Token tidak valid"]);
        exit;
    }

    return $data;
}