<?php
// api/eleven_voices.php
declare(strict_types=1);

require_once __DIR__ . '/config.php';

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Content-Type');
header('Access-Control-Allow-Methods: GET, OPTIONS');

function out(int $code, array $payload): never {
  http_response_code($code);
  echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
  exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(204); exit; }

if (!defined('ELEVEN_API_KEY') || ELEVEN_API_KEY === '') {
  out(400, ['ok'=>false, 'error'=>'ELEVENLABS_API_KEY manquante (ENV non vu par PHP).']);
}

$refresh   = isset($_GET['refresh']) && $_GET['refresh'] === '1';
$cacheDir  = __DIR__ . '/cache';
$cacheFile = $cacheDir . '/eleven_voices.json';
$ttl       = 300;
@mkdir($cacheDir, 0775, true);

if (!$refresh && is_file($cacheFile) && (time() - filemtime($cacheFile) < $ttl)) {
  $raw = file_get_contents($cacheFile);
  $json = json_decode($raw, true);
  if (is_array($json)) out(200, ['ok'=>true, 'provider'=>'elevenlabs', 'cached'=>true, 'voices'=>$json, 'ttl'=>$ttl]);
}

$ch = curl_init('https://api.elevenlabs.io/v1/voices');
curl_setopt_array($ch, [
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_HTTPHEADER => [
    'accept: application/json',
    'xi-api-key: ' . ELEVEN_API_KEY
  ]
]);
$body = curl_exec($ch);
$err  = curl_error($ch);
$code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($err) out(502, ['ok'=>false, 'error'=>'Erreur réseau: '.$err]);
if ($code === 401 || $code === 403) out($code, ['ok'=>false, 'error'=>'Clé ElevenLabs invalide ou non autorisée.']);
if ($code < 200 || $code >= 300) out($code, ['ok'=>false, 'error'=>'HTTP '.$code, 'body'=>$body]);

$data = json_decode($body, true);
$voices = [];
if (isset($data['voices']) && is_array($data['voices'])) {
  foreach ($data['voices'] as $v) {
    $id   = $v['voice_id'] ?? null;
    $name = $v['name'] ?? null;
    if (!$id || !$name) continue;
    $labels = $v['labels'] ?? [];
    $preview = $v['preview_url'] ?? ($v['samples'][0]['preview_url'] ?? null);
    $voices[] = [
      'id'          => $id,
      'name'        => $name,
      'category'    => $v['category'] ?? null,
      'labels'      => $labels,
      'preview_url' => $preview
    ];
  }
}

file_put_contents($cacheFile, json_encode($voices, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
out(200, ['ok'=>true, 'provider'=>'elevenlabs', 'cached'=>false, 'voices'=>$voices, 'ttl'=>$ttl]);
