<?php
require_once __DIR__ . '/../vendor/autoload.php';
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') exit;
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo "درخواست نامعتبر است.";
    exit;
}
$message = $_POST['message'] ?? '';
$apiKey = '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';
$url = 'https://openrouter.ai/api/v1/chat/completions';
$data = [
    'model' => 'openai/gpt-3.5-turbo',
    'messages' => [
        ['role' => 'user', 'content' => $message]
    ]
];
$options = [
    'http' => [
        'header'  => "Content-Type: application/json\r\nAuthorization: Bearer {$apiKey}",
        'method'  => 'POST',
        'content' => json_encode($data),
    ],
];
$response = file_get_contents($url, false, stream_context_create($options));
$json = json_decode($response, true);
$output = $json['choices'][0]['message']['content'] ?? '';
require_once __DIR__ . '/assets/Parsedown.php';
$parsedown = new Parsedown();
echo $parsedown->text($output);
exit;
?>
