<?php

namespace App\Services;

class TTSService
{
    /**
     * Convert text to speech using Google Translate TTS API (Free/No authentication required).
     * Returns the MP3 audio file content base64-encoded.
     *
     * @param string $text Arabic text to convert (e.g. "رمز التحقق الخاص بك هو 5 4 2 1")
     * @return string|null Base64 encoded audio string or null on failure
     */
    public static function textToSpeechArabic(string $text): ?string
    {
        try {
            $encodedText = urlencode($text);
            $url = "https://translate.google.com/translate_tts?ie=UTF-8&client=tw-ob&tl=ar&q={$encodedText}";

            $ch = curl_init($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 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36');
            curl_setopt($ch, CURLOPT_TIMEOUT, 10);
            
            $audioBinary = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
            curl_close($ch);

            if ($httpCode !== 200 || empty($audioBinary)) {
                error_log("[TTS Service Error] Failed to fetch audio from Google TTS. HTTP Code: {$httpCode}");
                return null;
            }

            // Verify if the response is actually audio
            if (strpos(strtolower($contentType), 'audio') === false && strlen($audioBinary) < 1000) {
                error_log("[TTS Service Error] Response content-type was not audio: {$contentType}. Body: " . substr($audioBinary, 0, 100));
                return null;
            }

            return base64_encode($audioBinary);
        } catch (\Exception $e) {
            error_log("[TTS Service Exception] " . $e->getMessage());
            return null;
        }
    }
}
