<?php
require_once 'mahamudfutureit_tts_config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    exit('Method not allowed');
}

if (!mahamudfutureit_is_tts_enabled()) {
    http_response_code(503);
    exit('TTS is disabled');
}

$text = isset($_GET['q']) ? trim($_GET['q']) : '';
if (empty($text)) {
    http_response_code(400);
    exit('No text provided');
}

$text = strip_tags($text);
$text = html_entity_decode($text, ENT_QUOTES, 'UTF-8');
$text = preg_replace('/\s+/', ' ', $text);
$text = urlencode($text);

$voice = mahamudfutureit_get_voice_type();
$voice_code = ($voice == 'male') ? 'hi' : 'bn';

$url = "https://translate.google.com/translate_tts?ie=UTF-8&q={$text}&tl={$voice_code}&client=tw-ob";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

$audioData = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode !== 200 || !$audioData) {
    http_response_code(500);
    exit('Failed to generate audio');
}

header('Content-Type: audio/mpeg');
header('Content-Length: ' . strlen($audioData));
header('Cache-Control: public, max-age=86400');
echo $audioData;
?>