<?php
// Batasi panjang teks agar Google TTS tidak error
$text = isset($_GET['text']) ? $_GET['text'] : '';
$lang = $_GET['lang'] ?? 'id';

if ($text) {
    // Google TTS hanya menerima sampai ±200 karakter
    if (strlen($text) > 200) {
        $text = substr($text, 0, 200);
    }

    $url = 'https://translate.google.com/translate_tts?ie=UTF-8&tl=' . urlencode($lang) .
           '&q=' . urlencode($text) . '&client=tw-ob';

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'User-Agent: Mozilla/5.0' // agar Google tidak menolak
    ]);

    $audio = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($audio && $http_code === 200) {
        header('Content-Type: audio/mpeg');
        echo $audio;
    } else {
        http_response_code(500);
        echo "Gagal mengambil audio dari Google.";
    }
} else {
    http_response_code(400);
    echo "Parameter 'text' tidak ditemukan.";
}
?>
