<?php
/**
 * Simplified TTS Generation for testing
 */

// Enable error reporting
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;
}

try {
    // Security validation
    require_once 'security_config.php';
    
    $apiKey = $_SERVER['HTTP_X_API_KEY'] ?? '';
    $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    
    if ($apiKey !== API_KEY) {
        http_response_code(403);
        echo json_encode(['success' => false, 'message' => 'Invalid API key']);
        exit;
    }
    
    // Check if user agent contains allowed patterns
    $validUserAgent = false;
    foreach (ALLOWED_USER_AGENTS as $allowedAgent) {
        if (strpos($userAgent, $allowedAgent) !== false) {
            $validUserAgent = true;
            break;
        }
    }
    
    if (!$validUserAgent) {
        http_response_code(403);
        echo json_encode(['success' => false, 'message' => 'Invalid user agent: ' . $userAgent]);
        exit;
    }
    
    // Only allow POST requests
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        http_response_code(405);
        echo json_encode(['success' => false, 'message' => 'Method not allowed']);
        exit;
    }
    
    // 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
    $googleApiKey = 'AIzaSyDIYTPVytTt0yVVOIaeAWLk1UJnSsU5chE';
    $audioDir = '../audio/';
    
    // Generate filename
    $cleanText = trim(strtolower($text));
    $encodedText = urlencode($cleanText);
    $maxLength = 200;
    if (strlen($encodedText) > $maxLength) {
        $encodedText = substr($encodedText, 0, $maxLength);
    }
    $fileName = $encodedText . '.mp3';
    $filePath = $audioDir . $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;
    }
    
    // Make sure audio directory exists
    if (!is_dir($audioDir)) {
        if (!mkdir($audioDir, 0755, true)) {
            throw new Exception('Cannot create audio directory');
        }
    }
    
    // Call Google Cloud TTS API
    $url = 'https://texttospeech.googleapis.com/v1/text:synthesize?key=' . $googleApiKey;
    
    $requestData = [
        'input' => ['text' => $text],
        'voice' => [
            'languageCode' => $language,
            'name' => $voice
        ],
        'audioConfig' => [
            'audioEncoding' => 'MP3',
            'speakingRate' => 1.0,
            'pitch' => 0.0,
            'volumeGainDb' => 0.0,
            'sampleRateHertz' => 24000
        ]
    ];
    
    $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 = isset($responseData['error']['message']) ? $responseData['error']['message'] : 'Unknown API error';
        throw new Exception('Google TTS API error: ' . $errorMsg);
    }
    
    // Save audio file
    $audioData = base64_decode($responseData['audioContent']);
    if (file_put_contents($filePath, $audioData) === false) {
        throw new Exception('Failed to save audio file');
    }
    
    // Set file permissions
    chmod($filePath, 0644);
    
    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()
    ]);
}
?>