<?php

// ---- CORS HEADERS ----
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

// Handle preflight
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}
require __DIR__ . '/vendor/autoload.php';

use Twilio\Jwt\AccessToken;
use Twilio\Jwt\Grants\VoiceGrant;

$accountSid = 'ACf175c11185835cd2c9f6df2d9e40b805';
$apiKey = 'SKdc17b6b8d7e393d788bd15153f1a1189';
$apiSecret = 'L4B8mgGJrufpzV0l48Qr8ngppO9Y4q5M';
$twimlAppSid = 'AP21fd1db2841bc2b2f548b4be5dbb880d';

$identity = $_GET['identity'] ?? 'agent_100';

$voiceGrant = new VoiceGrant();
$voiceGrant->setOutgoingApplicationSid($twimlAppSid);
$voiceGrant->setIncomingAllow(true);

$token = new AccessToken(
    $accountSid,
    $apiKey,
    $apiSecret,
    3600,
    $identity
);
$token->addGrant($voiceGrant);

header('Content-Type: application/json');
echo json_encode(['token' => $token->toJWT()]);
