<?php
/**
 * Google Cloud Text-to-Speech API Integration - Clean Version
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, X-API-Key, User-Agent');

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

try {
    // Load security config
    require_once 'security_config.php';
    
    // Validate API access using the function from security_config.php
    validateApiAccess();
    
    // Get input parameters
    $text = $_POST['text'] ?? '';
    $language = $_POST['language'] ?? 'en-US';
    $voice = $_POST['voice'] ?? 'en-US-Neural2-F';
    
    // Validate input
    if (empty($text)) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Text parameter is required']);
        exit;
    }
    
    if (strlen($text) > 5000) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Text too long (max 5000 characters)']);
        exit;
    }
    
    // Google Cloud TTS API Configuration
    define('GOOGLE_TTS_API_KEY', 'AIzaSyDIYTPVytTt0yVVOIaeAWLk1UJnSsU5chE');
    define('GOOGLE_TTS_ENDPOINT', 'https://texttospeech.googleapis.com/v1/text:synthesize');
    
    // Audio storage configuration
    define('AUDIO_DIR', '../audio/');
    define('MAX_CACHE_SIZE_MB', 500);
    
    // Generate safe filename
    function generateFileName($text) {
        $cleanText = trim(strtolower($text));
        $encodedText = urlencode($cleanText);
        
        // Limit filename length
        $maxLength = 200;
        if (strlen($encodedText) > $maxLength) {
            $encodedText = substr($encodedText, 0, $maxLength);
        }
        
        return $encodedText . '.mp3';
    }
    
    // Ensure audio directory exists
    if (!is_dir(AUDIO_DIR)) {
        if (!mkdir(AUDIO_DIR, 0755, true)) {
            throw new Exception('Cannot create audio directory');
        }
    }
    
    if (!is_writable(AUDIO_DIR)) {
        throw new Exception('Audio directory is not writable');
    }
    
    // Generate filename
    $fileName = generateFileName($text);
    $filePath = AUDIO_DIR . $fileName;
    
    // Check if file already exists
    if (file_exists($filePath)) {
        echo json_encode([
            'success' => true,
            'message' => 'Audio file already exists',
            'filename' => $fileName,
            'cached' => true
        ]);
        exit;
    }
    
    // Call Google Cloud TTS API
    if (empty(GOOGLE_TTS_API_KEY) || GOOGLE_TTS_API_KEY === 'YOUR_API_KEY_HERE') {
        throw new Exception('Google Cloud TTS API key not configured');
    }
    
    $url = GOOGLE_TTS_ENDPOINT . '?key=' . GOOGLE_TTS_API_KEY;
    
    // Prepare request data
    $requestData = [
        'input' => ['text' => $text],
        'voice' => [
            'languageCode' => $language,
            'name' => $voice
        ],
        'audioConfig' => [
            'audioEncoding' => 'MP3',
            'speakingRate' => 1.0,
            'pitch' => 0.0,
            'volumeGainDb' => 0.0,
            'sampleRateHertz' => 24000
        ]
    ];
    
    // Make HTTP request to Google TTS API
    $options = [
        'http' => [
            'header' => [
                'Content-Type: application/json',
                'User-Agent: ensi-tts-service/1.0'
            ],
            'method' => 'POST',
            'content' => json_encode($requestData),
            'timeout' => 30
        ]
    ];
    
    $context = stream_context_create($options);
    $response = file_get_contents($url, false, $context);
    
    if ($response === false) {
        throw new Exception('Failed to call Google TTS API');
    }
    
    $responseData = json_decode($response, true);
    
    if (!isset($responseData['audioContent'])) {
        $errorMsg = $responseData['error']['message'] ?? 'Unknown API error';
        throw new Exception('Google TTS API error: ' . $errorMsg);
    }
    
    $audioData = base64_decode($responseData['audioContent']);
    
    // Save to file
    if (file_put_contents($filePath, $audioData) === false) {
        throw new Exception('Failed to save audio file');
    }
    
    // Set appropriate file permissions
    chmod($filePath, 0644);
    
    // Log successful generation
    error_log("TTS: Generated {$fileName} for text: " . substr($text, 0, 100) . "...");
    
    echo json_encode([
        'success' => true,
        'message' => 'Audio file generated successfully',
        'filename' => $fileName,
        'size' => filesize($filePath),
        'cached' => false
    ]);
    
} catch (Exception $e) {
    error_log("TTS Generation Error: " . $e->getMessage());
    
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Failed to generate audio: ' . $e->getMessage()
    ]);
} catch (Error $e) {
    error_log("TTS Generation Fatal Error: " . $e->getMessage());
    
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Fatal error: ' . $e->getMessage()
    ]);
}
?>