<?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', 1);
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 {
    $apiUrl = 'https://api.abacus.ai/api/v0/createChatSession';
    
    // 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_SSL_VERIFYPEER => true
    ]);
    
    // Execute request
    $response = curl_exec($ch);
    
    if ($response === false) {
        throw new Exception('Curl error: ' . curl_error($ch));
    }
    
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
    if ($httpCode !== 200) {
        throw new Exception("API returned status code: " . $httpCode . " with response: " . $response);
    }
    
    curl_close($ch);
    
    // Parse response
    $data = json_decode($response, true);
    if (!isset($data['success']) || !$data['success']) {
        throw new Exception("API request failed: " . $response);
    }
    
    // Return response to client
    echo json_encode([
        'success' => true,
        'chat_id' => $data['result']['chatSessionId']
    ]);
    
} catch (Exception $e) {
    error_log("Error in chat-start.php: " . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'error' => $e->getMessage()
    ]);
}
?>