<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

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

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    http_response_code(200);
    exit();
}

require_once 'config.php';

try {
    // Get POST data
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);
    
    if (!isset($data['message'])) {
        throw new Exception("Invalid input - missing message");
    }
    
    // Prepare messages array
    $messages = [
        [
            'is_user' => true,
            'text' => $data['message']
        ]
    ];
    
    // Initialize cURL
    $ch = curl_init();
    
    // Set URL with query parameters
    $url = "https://api.abacus.ai/api/v0/getChatResponse";
    $url .= "?deploymentToken=" . urlencode(DEPLOYMENT_TOKEN);
    $url .= "&deploymentId=" . urlencode(DEPLOYMENT_ID);
    
    error_log("URL: " . $url);
    error_log("Messages: " . json_encode($messages));
    
    // Set cURL options
    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'
        ]
    ]);
    
    // Execute request
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
    error_log("HTTP Code: " . $httpCode);
    error_log("Raw Response: " . $response);
    
    if ($response === false) {
        throw new Exception('Curl error: ' . curl_error($ch));
    }
    
    curl_close($ch);
    
    // Parse response
    $responseData = json_decode($response, true);
    if ($responseData === null) {
        throw new Exception("Failed to parse response: " . json_last_error_msg());
    }
    
    // Check for error in response
    if (!isset($responseData['success']) || $responseData['success'] !== true) {
        throw new Exception($responseData['error'] ?? 'Unknown API error');
    }
    
    // Get bot's response from the messages array
    $botResponse = '';
    if (isset($responseData['result']['messages'])) {
        foreach ($responseData['result']['messages'] as $message) {
            if ($message['is_user'] === false) {
                $botResponse = $message['text'];
                break;
            }
        }
    }
    
    if (empty($botResponse)) {
        throw new Exception("No bot response found in API response");
    }
    
    // Format the response
    $botResponse = formatResponse($botResponse);
    
    // Return success response
    echo json_encode([
        'success' => true,
        'response' => $botResponse,
        'chat_id' => isset($data['chat_id']) ? $data['chat_id'] : null
    ]);
    
} catch (Exception $e) {
    error_log("Error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}


function formatResponse($text) {
    // Format headings với ###
    $text = preg_replace('/###\s*([^\n]+)/', '<h3>$1</h3>', $text);
    
    // Format numbered headings với bold
    $text = preg_replace('/\*\*(\d+)\.\s*([^*]+)\*\*/', '<h3>$1. $2</h3>', $text);
    
    // Format other bold text
    $text = preg_replace('/\*\*([^*]+)\*\*/', '<strong>$1</strong>', $text);
    
    // Format bullet points với proper spacing
    $text = preg_replace('/^\s*-\s+/m', '<br>• ', $text);
    
    // Format numbered lists với proper spacing
    $text = preg_replace('/^\s*(\d+)\.\s+/m', '<br>$1. ', $text);
    
    // Wrap in paragraph for base styling
    $text = '<p>' . $text . '</p>';
    
    // Clean up multiple breaks
    $text = preg_replace('/<br\s*\/?>\s*<br\s*\/?>/i', '<br>', $text);
    
    // Remove any remaining markdown artifacts
    $text = str_replace(['</strong>**', '**<strong>'], ['</strong>', '<strong>'], $text);
    
    return $text;
}
?>