<?php
header('Content-Type: application/json');

// Enable error reporting for debugging
ini_set('display_errors', 1);
error_reporting(E_ALL);

// Load environment variables
/* require_once 'vendor/autoload.php';
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load(); */
$_SESSION['KEY'] = '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';


// Get the API key from environment variable
$api_key = $_SESSION['KEY'];

// Get the POST data
$json = file_get_contents('php://input');
$data = json_decode($json, true);

if (!$data || !isset($data['prompt'])) {
    http_response_code(400);
    echo json_encode([
        'error' => 'Missing prompt in request body'
    ]);
    exit;
}

$prompt = $data['prompt'];

// Configure the API request
$url = 'https://api.openai.com/v1/chat/completions';
$headers = [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $api_key
];

// Prepare the request data
$request_data = [
    'model' => 'gpt-4o-mini', // or 'gpt-3.5-turbo' depending on your needs
    'messages' => [
        [
            'role' => 'system',
            'content' => 'You are a highly-experienced professional in the field you will be asked to explain, who is highly experienced in business and personal development. Provide relevant, comprehensive, well-structured explanations that may use metaphors, similes, or any other explanatory device that will make the subject extremely clear. Use HTML formatting and bold your headings for easier readability.'
        ],
        [
            'role' => 'user',
            'content' => $prompt
        ]
    ],
    'temperature' => 0.7,
    'max_tokens' => 2000
];

// Initialize cURL session
$ch = curl_init($url);

// Set cURL options
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => $headers,
    CURLOPT_POSTFIELDS => json_encode($request_data),
    CURLOPT_SSL_VERIFYPEER => true // Enable SSL verification
]);

try {
    // Execute the request
    $response = curl_exec($ch);
    
    // Check for cURL errors
    if (curl_errno($ch)) {
        throw new Exception('Curl error: ' . curl_error($ch));
    }

    // Get HTTP status code
    $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    // Check for non-200 HTTP response
    if ($http_status !== 200) {
        throw new Exception('API returned status code: ' . $http_status);
    }

    // Decode the response
    $result = json_decode($response, true);

    // Check for JSON decode errors
    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception('JSON decode error: ' . json_last_error_msg());
    }

    // Extract the response text
    if (isset($result['choices'][0]['message']['content'])) {
        echo json_encode([
            'success' => true,
            'response' => $result['choices'][0]['message']['content']
        ]);
    } else {
        throw new Exception('Unexpected API response structure');
    }

} catch (Exception $e) {
    // Log the error (you should implement proper error logging)
    error_log('AI Endpoint Error: ' . $e->getMessage());
    
    // Return error response
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'An error occurred while processing your request',
        'debug_message' => $e->getMessage() // Remove this in production
    ]);
} finally {
    // Close cURL session
    curl_close($ch);
}

// Function to sanitize output (implement as needed)
function sanitizeOutput($text) {
    return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
}
?>
