<?php
/**
 * Simple test endpoint for TTS system
 * Tests basic functionality without Google Cloud API
 */

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;
}

// Security validation
require_once 'security_config.php';

function validateApiAccess() {
    $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;
    }
    
    if (!in_array($userAgent, ALLOWED_USER_AGENTS)) {
        http_response_code(403);
        echo json_encode(['success' => false, 'message' => 'Invalid user agent']);
        exit;
    }
}

// Validate API access
validateApiAccess();

// 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'] ?? '';

// Validate input
if (empty($text)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Text parameter is required']);
    exit;
}

// Audio storage configuration
const AUDIO_DIR = '../audio/';

/**
 * Generate safe filename for MP3 files
 */
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';
}

/**
 * Check if audio directory exists and is writable
 */
function ensureAudioDirectory() {
    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');
    }
}

try {
    // Ensure audio directory exists
    ensureAudioDirectory();
    
    // 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 (simulated)',
            'filename' => $fileName,
            'cached' => true,
            'test_mode' => true
        ]);
        exit;
    }
    
    // Simulate audio generation (create empty file for testing)
    $dummyContent = "This is a test MP3 file for: " . $text;
    
    if (file_put_contents($filePath, $dummyContent) === false) {
        throw new Exception('Failed to save test file');
    }
    
    // Set appropriate file permissions
    chmod($filePath, 0644);
    
    // Log successful generation
    error_log("TTS Test: Generated {$fileName} for text: " . substr($text, 0, 100) . "...");
    
    echo json_encode([
        'success' => true,
        'message' => 'Test file generated successfully',
        'filename' => $fileName,
        'size' => filesize($filePath),
        'cached' => false,
        'test_mode' => true,
        'note' => 'This is a test file, not real audio. Configure Google API key for actual TTS.'
    ]);
    
} catch (Exception $e) {
    error_log("TTS Test Error: " . $e->getMessage());
    
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Test failed: ' . $e->getMessage(),
        'test_mode' => true
    ]);
}
?>