<?php
/**
 * Debug script to test TTS functionality step by step
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

echo json_encode([
    'step' => 1,
    'message' => 'Basic PHP execution working',
    'php_version' => phpversion(),
    'timestamp' => date('Y-m-d H:i:s')
]);

// Test if security_config.php exists
try {
    if (file_exists('security_config.php')) {
        require_once 'security_config.php';
        echo json_encode([
            'step' => 2,
            'message' => 'security_config.php loaded successfully',
            'api_key_defined' => defined('API_KEY')
        ]);
    } else {
        echo json_encode([
            'step' => 2,
            'error' => 'security_config.php not found'
        ]);
    }
} catch (Exception $e) {
    echo json_encode([
        'step' => 2,
        'error' => $e->getMessage()
    ]);
}

// Test audio directory
try {
    $audioDir = '../audio/';
    $audioDirExists = is_dir($audioDir);
    $audioDirWritable = is_writable($audioDir);
    
    echo json_encode([
        'step' => 3,
        'message' => 'Audio directory test',
        'directory' => $audioDir,
        'exists' => $audioDirExists,
        'writable' => $audioDirWritable,
        'absolute_path' => realpath($audioDir)
    ]);
} catch (Exception $e) {
    echo json_encode([
        'step' => 3,
        'error' => $e->getMessage()
    ]);
}

// Test Google API endpoint accessibility
try {
    $apiKey = 'AIzaSyDIYTPVytTt0yVVOIaeAWLk1UJnSsU5chE';
    $testUrl = 'https://texttospeech.googleapis.com/v1/text:synthesize?key=' . $apiKey;
    
    // Test if we can reach Google API (just check URL format)
    echo json_encode([
        'step' => 4,
        'message' => 'Google API test',
        'api_key_length' => strlen($apiKey),
        'api_url' => 'https://texttospeech.googleapis.com/v1/text:synthesize',
        'curl_available' => function_exists('curl_init'),
        'file_get_contents_available' => function_exists('file_get_contents')
    ]);
} catch (Exception $e) {
    echo json_encode([
        'step' => 4,
        'error' => $e->getMessage()
    ]);
}

echo json_encode([
    'step' => 'final',
    'message' => 'Debug script completed successfully'
]);
?>