<?php

// API endpoint
$text = $_POST["text"];
$USerID = $_POST["UserID"];

 $text = $_POST["text"];
$USerID = $_POST["UserID"];

$url = 'https://api.openai.com/v1/assistants?order=desc&limit=20';
$api_key = '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';
$asst_ = 'asst_i4ub9YwIuqfcw2cZYuH8IHW8';

$ch = curl_init($url);
$data = '{"model":"gpt-3.5-turbo"}';
// Set cURL options
//curl_setopt($ch, CURLOPT_POST, false);
//curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // استخدام $json_data بدلاً من $data
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Authorization: Bearer ' . $api_key,
	'OpenAI-Beta: assistants=v1'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Execute cURL request
$response = curl_exec($ch);

// Check for errors
if(curl_errno($ch)) {
    echo 'Curl error: ' . curl_error($ch);
}

// Close cURL session
curl_close($ch);

// Handle the response
//echo $response;

$responseArray = json_decode($response, true);

// Check if the response is valid and contains data
if ($responseArray && isset($responseArray['data'])) {
    // Access the first assistant's instructions (assuming there is only one assistant in the response)
    $assistant = $responseArray['data'][0];
    
    // Check if instructions are available
    if (isset($assistant['instructions'])) {
        $instructions = $assistant['instructions'];
        // Now you can use $instructions as needed
       // echo $instructions;
		$Question = " What is qoon ?";
		
		$url = 'https://api.openai.com/v1/completions';
		$instructions = $instructions . "question is " .  $text ." ? Ans:";
		
		$instructions = json_encode($instructions, JSON_UNESCAPED_UNICODE);
		
		$data = '{"model":"gpt-3.5-turbo-instruct","top_p":1,"max_tokens":500,"temperature":0.6,"presence_penalty":1,"frequency_penalty":1,"prompt":'.$instructions.'}';
		//echo $data;

		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // استخدام $json_data بدلاً من $data
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
			'Content-Type: application/json',
			'Authorization: Bearer ' . $api_key
		));
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

		// Execute cURL request
		$response = curl_exec($ch);

		// Check for errors
		if(curl_errno($ch)) {
			echo 'Curl error: ' . curl_error($ch);
		}

		// Close cURL session
		curl_close($ch);

// Handle the response
	//	echo $response;
		
			$data = json_decode($response, true);
//$content = $data['choices'][0]['message']['content'];
$content = $data['choices'][0]['text'];
$message = "DONE";
$status_code = 200;
$success = true;
//$content = "comming soon ...";
//$content = "Sorry updating..";
echo json_encode(array('status_code' => $status_code,'success' => $success ,"data"=>$content,"message"=>$message));
		
		
		
    } else {
        echo "Instructions not available for this assistant.";
    }
} else {
    echo "Invalid or empty response.";
}



?>
