<?php
// includes/livekit_token.php
require_once __DIR__ . '/auth.php';

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

function jwt_hs256(array $header, array $payload, string $secret): string {
  $h = b64url_encode(json_encode($header, JSON_UNESCAPED_SLASHES));
  $p = b64url_encode(json_encode($payload, JSON_UNESCAPED_SLASHES));
  $sig = hash_hmac('sha256', $h.'.'.$p, $secret, true);
  return $h.'.'.$p.'.'.b64url_encode($sig);
}

function livekit_mint_token(string $identity, string $name, string $room, array $grants): string {
  $cfg = app_config();
  $apiKey = $cfg['livekit']['api_key'];
  $apiSecret = $cfg['livekit']['api_secret'];
  if (!$apiKey || !$apiSecret) throw new Exception("LiveKit API key/secret not configured");

  $now = time();
  $header = ['alg'=>'HS256','typ'=>'JWT'];
  $payload = [
    'iss' => $apiKey,
    'sub' => $identity,
    'name' => $name,
    'nbf' => $now - 5,
    'iat' => $now,
    'exp' => $now + 60*60*6,
    'video' => array_merge(['room'=>$room], $grants),
  ];
  return jwt_hs256($header, $payload, $apiSecret);
}
