<?php
require_once __DIR__ . '/db.php';

function jwt_encode(array $payload): string {
    $header  = b64u(json_encode(['typ' => 'JWT', 'alg' => 'HS256']));
    $body    = b64u(json_encode($payload));
    $sig     = b64u(hash_hmac('sha256', "$header.$body", JWT_SECRET, true));
    return "$header.$body.$sig";
}

function jwt_decode(string $token): ?array {
    $parts = explode('.', $token);
    if (count($parts) !== 3) return null;
    [$h, $b, $sig] = $parts;
    if (!hash_equals(b64u(hash_hmac('sha256', "$h.$b", JWT_SECRET, true)), $sig)) return null;
    $data = json_decode(base64_decode(strtr($b, '-_', '+/')), true);
    if (!$data || ($data['exp'] ?? 0) < time()) return null;
    return $data;
}

function b64u(string $data): string {
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

function auth_required(): array {
    $h    = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
    $token = preg_match('/Bearer\s+(.+)/i', $h, $m) ? $m[1] : null;
    if (!$token || !($user = jwt_decode($token))) {
        http_response_code(401);
        echo json_encode(['error' => 'Unauthorized']);
        exit;
    }
    return $user;
}
