<?php
// Secure token check to prevent unauthorized execution on production
if (($_GET['token'] ?? '') !== 'nabeh_test_elevenlabs_1298') {
    http_response_code(403);
    die('Unauthorized access');
}

require_once dirname(__DIR__) . '/app/bootstrap.php';

use App\Services\GeminiService;
use App\Models\ChatbotRule;
use App\Core\Database;

header('Content-Type: text/plain; charset=utf-8');

echo "=== Starting ElevenLabs Audio Response Diagnostics ===\n\n";

// 1. Load active rule and extract ElevenLabs configuration
$rules = Database::select("SELECT * FROM chatbot_rules WHERE trigger_type = 'gemini_ai' AND is_active = 1 LIMIT 1");
$rule = !empty($rules) ? $rules[0] : null;

if ($rule) {
    echo "✅ [Database] Found active rule for Company ID: {$rule['company_id']}\n";
    // Check if keys are defined in the database rule
    $elApiKey = !empty($rule['elevenlabs_api_key']) ? \App\Core\Security::decrypt($rule['elevenlabs_api_key']) : null;
    $elVoiceId = $rule['elevenlabs_voice_id'] ?? null;
} else {
    echo "ℹ️ [Database] No active rule found. Checking environment variables.\n";
    $elApiKey = null;
    $elVoiceId = null;
}

// Fallback to .env configuration if database values are empty
if (empty($elApiKey)) {
    $elApiKey = getenv('ELEVENLABS_API_KEY');
    echo "ℹ️ [Config] ElevenLabs API Key loaded from environment variable (.env).\n";
} else {
    echo "ℹ️ [Config] ElevenLabs API Key loaded from active chatbot rule.\n";
}

if (empty($elVoiceId)) {
    $elVoiceId = getenv('ELEVENLABS_VOICE_ID') ?: 'pNInz6obpgDQGcFmaJgB'; // Default to Adam
    echo "ℹ️ [Config] ElevenLabs Voice ID loaded from environment/default: {$elVoiceId}\n";
} else {
    echo "ℹ️ [Config] ElevenLabs Voice ID loaded from active chatbot rule: {$elVoiceId}\n";
}

// Allow override via query parameters for testing
if (!empty($_GET['key_override'])) {
    $elApiKey = trim($_GET['key_override']);
    echo "ℹ️ [Config] ElevenLabs API Key overridden via GET parameter.\n";
}
if (!empty($_GET['voice_override'])) {
    $elVoiceId = trim($_GET['voice_override']);
    echo "ℹ️ [Config] ElevenLabs Voice ID overridden via GET parameter.\n";
}

if (empty($elApiKey)) {
    echo "❌ [Config] ElevenLabs API Key is missing. Diagnostics stopped.\n";
    exit(1);
}

echo "ℹ️ [Config] API Key length: " . strlen($elApiKey) . ", starts with: " . substr($elApiKey, 0, 6) . "..., ends with: " . substr($elApiKey, -4) . "\n";

// 2. Execute Test Voice Generation using ElevenLabs
echo "\n--- Generating Speech with ElevenLabs ---\n";
$testText = "مرحباً بك! أنا مساعدك الذكي من نبيه، كيف يمكنني مساعدتك اليوم؟";
echo "Text to generate: \"{$testText}\"\n";

// Test general authentication by querying ElevenLabs models list
echo "\n--- Testing ElevenLabs General Authentication (/v1/models) ---\n";
$modelsUrl = 'https://api.elevenlabs.io/v1/models';
$chModels = curl_init($modelsUrl);
curl_setopt($chModels, CURLOPT_RETURNTRANSFER, true);
curl_setopt($chModels, CURLOPT_HTTPHEADER, [
    'xi-api-key: ' . $elApiKey
]);
$modelsResponse = curl_exec($chModels);
$modelsHttpCode = curl_getinfo($chModels, CURLINFO_HTTP_CODE);
curl_close($chModels);

echo "Models API HTTP Status Code: {$modelsHttpCode}\n";
echo "Models API Response: " . substr($modelsResponse, 0, 300) . "\n\n";

// Execute ElevenLabs TTS directly in this test script to get detailed error logs
$url = 'https://api.elevenlabs.io/v1/text-to-speech/' . $elVoiceId;

$payload = json_encode([
    'text' => $testText
]);

echo "Sending API request to: {$url}...\n";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'xi-api-key: ' . $elApiKey
]);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);

echo "HTTP Status Code: {$httpCode}\n";
if ($curlError) {
    echo "cURL Error: {$curlError}\n";
}

if ($httpCode === 200) {
    echo "✅ [ElevenLabs] Speech generation successful!\n";
    echo "ℹ️ [ElevenLabs] Audio size: " . strlen($response) . " bytes\n";
    
    // Save to test file
    $outputPath = __DIR__ . '/test_elevenlabs_out.mp3';
    file_put_contents($outputPath, $response);
    echo "✅ [ElevenLabs] Audio successfully written to: " . basename($outputPath) . "\n";
} else {
    echo "❌ [ElevenLabs] Speech generation failed.\n";
    echo "Response: " . $response . "\n";
}

echo "\n=== Diagnostics Complete ===\n";
