<?php
header('Content-Type: application/json');
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');

try {
    $apiUrl = 'https://api.abacus.ai/api/v0/createChatSession';
    
    // Log configuration
    error_log("Testing Abacus API connection...");
    error_log("API URL: " . $apiUrl);
    error_log("Deployment ID: " . DEPLOYMENT_ID);
    
    // Initialize cURL
    $ch = curl_init();
    
    // Set cURL options
    curl_setopt_array($ch, [
        CURLOPT_URL => $apiUrl,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => [
            'Authorization: Bearer ' . API_TOKEN,
            'APIKEY: ' . API_TOKEN,
            'Content-Type: application/json',
            'Accept: application/json'
        ],
        CURLOPT_POSTFIELDS => json_encode([
            'deployment_id' => DEPLOYMENT_ID
        ]),
        CURLOPT_VERBOSE => true,
        CURLOPT_SSL_VERIFYPEER => true
    ]);
    
    // For debug
    $verbose = fopen('php://temp', 'w+');
    curl_setopt($ch, CURLOPT_STDERR, $verbose);
    
    // Execute request
    $response = curl_exec($ch);
    
    // Get debug info
    rewind($verbose);
    $verboseLog = stream_get_contents($verbose);
    error_log("CURL Verbose Log: " . $verboseLog);
    
    if ($response === false) {
        throw new Exception('Curl error: ' . curl_error($ch));
    }
    
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    error_log("HTTP Response Code: " . $httpCode);
    error_log("Raw Response: " . $response);
    
    curl_close($ch);
    
    // Output test results
    echo json_encode([
        'success' => true,
        'http_code' => $httpCode,
        'response' => json_decode($response, true),
        'curl_verbose' => $verboseLog,
        'request_headers' => [
            'Authorization: Bearer ' . substr(API_TOKEN, 0, 10) . '...',
            'APIKEY: ' . substr(API_TOKEN, 0, 10) . '...',
            'Content-Type: application/json',
            'Accept: application/json'
        ],
        'request_body' => [
            'deployment_id' => DEPLOYMENT_ID
        ]
    ], JSON_PRETTY_PRINT);
    
} catch (Exception $e) {
    error_log("Error in test-abacus.php: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ], JSON_PRETTY_PRINT);
}
?>