<?php
declare(strict_types=1);

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');

function respond(int $status,array $data): never{
 http_response_code($status);
 echo json_encode($data,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
 exit;
}

$teacher=!empty($_SESSION['user_id']) && in_array((string)($_SESSION['user_role']??''),['teacher','admin'],true);
$student=!empty($_SESSION['student_id']);

if(!$teacher && !$student){
 respond(401,['ok'=>false,'message'=>'Vui lòng đăng nhập.']);
}

$config=__DIR__.'/../config/azure_speech.php';
if(!is_file($config)){
 respond(500,['ok'=>false,'message'=>'Không tìm thấy cấu hình Azure Speech.']);
}

$cfg=require $config;
$key=trim((string)($cfg['key']??''));
$region=strtolower(trim((string)($cfg['region']??'')));

if($key===''||$region===''){
 respond(500,['ok'=>false,'message'=>'Thiếu Azure Key hoặc Region.']);
}

$url="https://{$region}.api.cognitive.microsoft.com/sts/v1.0/issueToken";

$ch=curl_init($url);
curl_setopt_array($ch,[
 CURLOPT_POST=>true,
 CURLOPT_POSTFIELDS=>'',
 CURLOPT_RETURNTRANSFER=>true,
 CURLOPT_HTTPHEADER=>[
   'Ocp-Apim-Subscription-Key: '.$key,
   'Content-Length: 0'
 ],
 CURLOPT_TIMEOUT=>15,
 CURLOPT_SSL_VERIFYPEER=>true,
 CURLOPT_SSL_VERIFYHOST=>2,
]);

$token=curl_exec($ch);
$http=(int)curl_getinfo($ch,CURLINFO_HTTP_CODE);
$err=curl_error($ch);
curl_close($ch);

if($token===false||$http!==200){
 respond(502,[
  'ok'=>false,
  'message'=>'Không lấy được Azure Speech Token.',
  'http_status'=>$http,
  'curl_error'=>$err
 ]);
}

respond(200,[
 'ok'=>true,
 'token'=>$token,
 'region'=>$region,
 'expires_in'=>600
]);
