<?php
ini_set('display_errors', 1); 
ini_set('display_startup_errors', 1); 
error_reporting(E_ALL);
require __DIR__ . '/vendor/autoload.php';
use OpenAI;

$openaiKey = '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';
$assistantId= 'asst_XzHoaVqwC8N6l0WGHNmCa5cI';
$client = OpenAI::client($openaiKey);

require "library.php";

if(isset($_GET['message'])){
    if($_GET['message'] == ""){
        echo "No message";exit;
    }
    $message  = $_GET['message'];
    
    
    if(isset($_GET['thread_id']) && $_GET['thread_id'] != ""){

        $threadId = $_GET['thread_id'];

        // Send a message to the assistant in the existing thread
        $message = $client->threads()->messages()->create($threadId, [
            'role' => 'user',
            'content' => $message
        ]);

        // Run the assistant to process the message
        $run = $client->threads()->runs()->create($threadId, [
            'assistant_id' => $assistantId
        ]);

        do {
            sleep(3); // Avoid excessive API calls
            $runStatus = $client->threads()->runs()->retrieve($threadId, $run['id']);
        } while ($runStatus['status'] !== 'completed');
       
    }else{

        
        $response = $client->threads()->createAndRun([
            'assistant_id' => $assistantId,
            'model' => 'gpt-4o-mini',
            'thread' => [
                'messages' => [
                    [
                        'role' => 'user',
                        'content' => $message,
                    ],
                ],
            ],
        ]); 
        $threadId = $response->threadId;
        try{
            do {
                sleep(3); // Avoid excessive API calls
                $runStatus = $client->threads()->runs()->retrieve($threadId, $response->id);
            } while ($runStatus['status'] !== 'completed');
        } catch (\Exception $e) {
            //error_log("Error retrieving run status: " . $e->getMessage());
        }   
        
    }
    
    //sleep(3);
    $assistantMessage = loopGetResponse($threadId);
     
    
    $result = array();
   
    $searchPlace = 0;
    if ($assistantMessage) {
        //var_dump($gptResultRaw);exit;
        $resObj = json_decode($assistantMessage);

       
        
        $result['thread_id'] = $threadId;
        $result['message'] = $resObj->message;
        $aiQuery = "";
        if(isset($resObj->query) && $resObj->query != null){
            $aiQuery = $resObj->query;
            if($aiQuery != ""){
                $searchPlace = 1;
            }else{
                $result['query'] = $aiQuery;
                echo json_encode($result);exit;
            }
        }else{
            if(isset($resObj->places) && $resObj->places != null){
                $result['places'] = $resObj->places;
                echo json_encode($result);exit;
            }else{
                $result['query'] = "";
                echo json_encode($result);exit;
            }
            
        }
       /* $result['thread_id'] = $threadId;
        $result['message'] = $resObj->message;
        $result['query'] = $aiQuery;
        echo json_encode($result);exit;*/



         //echo $gptResultRaw;
    } else{
        
        $readThread = loopGetResponse($threadId);

           if($readThread == false){
                echo "OpenAI Timeout: ".$threadId;exit;
           }else{
                $resObj = json_decode($readThread);

               $result['thread_id'] = $threadId;
                $result['message'] = $resObj->message;
                $aiQuery = "";
                if(isset($resObj->query) && $resObj->query != null){
                    $aiQuery = $resObj->query;
                    $searchPlace = 1;
                }else{
                    if(isset($resObj->places) && $resObj->places != null){
                        $result['places'] = $resObj->places;
                        echo json_encode($result);exit;
                    }else{
                        $result['query'] = "";
                        echo json_encode($result);exit;
                    }
                    
                }
                /*$result['thread_id'] = $threadId;
                $result['message'] = $resObj->message;
                $result['query'] = $aiQuery;
                echo json_encode($result);exit;*/
           }
        
    }

    if($searchPlace == 1){
        $apiKey = "AIzaSyAq1ODKKCVgTT3yvuqrsSIL8biDjhNu8NM";

        $results = searchPlaces($aiQuery);
        $jsonResponse = json_encode($results);
        $resFile = "placejson/res_".time().".txt";
        file_put_contents($resFile, $jsonResponse);
        $response = $client->files()->upload([
            'purpose' => 'fine-tune',
            'file' => fopen($resFile, 'r'),
        ]);
        $fileid = $response->id;
       
        $response = $client->threads()->messages()->create($threadId, [
            'role' => 'user',
            'content' => $aiQuery.",remember result in json format",
            'attachments' => [
                [
                    'file_id' => $fileid,
                    'tools' => [
                        [
                            'type' => 'file_search',
                        ]
                    ]
                ]
            ]
        ]);

        // Run the assistant to process the message
        $run = $client->threads()->runs()->create($threadId, [
            'assistant_id' => $assistantId
        ]);

        do {
            sleep(3); // Avoid excessive API calls
            $runStatus = $client->threads()->runs()->retrieve($threadId, $run['id']);
        } while ($runStatus['status'] !== 'completed');

        $assistantMessage = loopGetResponse($threadId);

        if ($assistantMessage) {
       
       
        $resObjList = json_decode($assistantMessage);
    

        if($resObjList == false){
             $allResult = array();
                $allResult['thread_id'] = $threadId;
                $allResult['message'] = $assistantMessage;
                $allResult['places'] = array(); 
                echo json_encode($allResult);exit;
        }
        $locationArray = array();
        $allResult = array();
        $allResult['thread_id'] = $threadId;
        $allResult['message'] = $resObjList->message;
        $allResult['places'] = $resObjList->places;
        echo json_encode($allResult);exit;



         //echo $gptResultRaw;
        } else{
            
            $readThread = loopGetResponse($threadId);
            

            if($readThread == false ){
                echo "OpenAI Timeout: ".$threadId;exit;
            }else{
             $resObjList = json_decode($readThread);
                //var_dump($gptResultRaw);

                if(!$resObjList->message){
                    var_dump($resObjList);exit;
                }
                $locationArray = array();
                $allResult = array();
                $allResult['thread_id'] = $threadId;
                $allResult['message'] = $resObjList->message;
                $allResult['places'] = $resObjList->places;
                echo json_encode($allResult);exit;
            }
            
        }

    }

}



