<?php
header('Content-Type: text/html; charset=UTF-8');
require_once 'config.php';

error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/error.log');

echo "<html><head><style>
    body { font-family: Arial, sans-serif; margin: 20px; }
    .section { margin: 20px 0; padding: 10px; border: 1px solid #ccc; }
    .response { white-space: pre-wrap; }
    h2 { color: #333; }
</style></head><body>";

try {
    // Test message
    $test_message = "Hello, this is a test message";
    
    // Try to get a chat response
    $messages = [
        [
            'is_user' => true,
            'text' => $test_message
        ]
    ];
    
    $ch = curl_init();
    
    $url = "https://api.abacus.ai/api/v0/getChatResponse";
    $url .= "?deploymentToken=" . urlencode(DEPLOYMENT_TOKEN);
    $url .= "&deploymentId=" . urlencode(DEPLOYMENT_ID);
    
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => "messages=" . urlencode(json_encode($messages)),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/x-www-form-urlencoded',
            'Accept: application/json'
        ]
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
    echo "<div class='section'>";
    echo "<h2>API Request Details</h2>";
    echo "URL: " . htmlspecialchars($url) . "<br>";
    echo "Messages: " . htmlspecialchars(json_encode($messages)) . "<br>";
    echo "HTTP Code: " . htmlspecialchars($httpCode) . "<br>";
    echo "</div>";
    
    if ($response === false) {
        throw new Exception('Curl error: ' . curl_error($ch));
    }
    
    echo "<div class='section'>";
    echo "<h2>Raw Response</h2>";
    echo "<pre class='response'>" . htmlspecialchars($response) . "</pre>";
    echo "</div>";
    
    $responseData = json_decode($response, true);
    if ($responseData === null) {
        throw new Exception("Failed to parse response: " . json_last_error_msg());
    }
    
    if (isset($responseData['result']['messages'])) {
        foreach ($responseData['result']['messages'] as $message) {
            if ($message['is_user'] === false) {
                $original = $message['text'];
                $formatted = formatResponse($original);
                
                echo "<div class='section'>";
                echo "<h2>Original Bot Response</h2>";
                echo "<pre class='response'>" . htmlspecialchars($original) . "</pre>";
                echo "</div>";
                
                echo "<div class='section'>";
                echo "<h2>Formatted Bot Response (HTML)</h2>";
                echo "<pre class='response'>" . htmlspecialchars($formatted) . "</pre>";
                echo "</div>";
                
                echo "<div class='section'>";
                echo "<h2>Formatted Bot Response (Rendered)</h2>";
                echo $formatted;
                echo "</div>";
                
                break;
            }
        }
    }
    
    curl_close($ch);
    
} catch (Exception $e) {
    echo "<div class='section'>";
    echo "<h2>Error</h2>";
    echo "Error: " . htmlspecialchars($e->getMessage()) . "<br>";
    echo "Stack trace:<br><pre>" . htmlspecialchars($e->getTraceAsString()) . "</pre>";
    echo "</div>";
}

function formatResponse($text) {
    // Format numbered headings with bold
    $text = preg_replace('/\*\*(\d+)\.\s*([^*]+)\*\*/', '<h3 style="margin: 15px 0; font-weight: bold;">$1. $2</h3>', $text);
    
    // Format other bold text
    $text = preg_replace('/\*\*([^*]+)\*\*/', '<strong>$1</strong>', $text);
    
    // Format bullet points
    $text = preg_replace('/^\s*•\s+/m', '<br>• ', $text);
    
    // Format numbered lists
    $text = preg_replace('/^\s*(\d+)\.\s+/m', '<br>$1. ', $text);
    
    // Add paragraph breaks
    $text = '<p style="margin: 10px 0;">' . $text . '</p>';
    
    // Clean up multiple breaks
    $text = preg_replace('/<br\s*\/?>\s*<br\s*\/?>/i', '<br>', $text);
    
    return $text;
}

echo "</body></html>";
?>