<?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_Jj3UwoVh5qAan5z3XB2ZBOD9';
$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{
        $resFile = "https://app.tgt.wtf/chat/products/res_products.txt";
        $response = $client->files()->upload([
            'purpose' => 'fine-tune',
            'file' => fopen($resFile, 'r'),
        ]);
        $fileid = $response->id;
        
        $response = $client->threads()->createAndRun([
            'assistant_id' => $assistantId,
            'model' => 'gpt-4o-mini',
            'thread' => [
                'messages' => [
                    [
                        'role' => 'user',
                        'content' => $message,
                        'attachments' => [
                            [
                                'file_id' => $fileid,
                                'tools' => [
                                    [
                                        'type' => 'file_search',
                                    ]
                                ]
                            ]
                        ]
                    ],
                ],
            ],
        ]); 
        $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();
   
    $productListing = 0;
    if ($assistantMessage) {
        //var_dump($gptResultRaw);exit;
        $resObj = json_decode($assistantMessage);

       
        $result['thread_id'] = $threadId;
        $result['message'] = $resObj->message;
        $aiQuery = "";
        if(isset($resObj->productsid_recommended) && $resObj->productsid_recommended != null){
            $aiQuery = $resObj->productsid_recommended; 
        }
        $result['thread_id'] = $threadId;
        $result['message'] = $resObj->message;
        $result['productsid_recommended'] = $aiQuery;
        $result['preferences'] = $resObj->preferences;
        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->productsid_recommended) && $resObj->productsid_recommended != null){
                    $aiQuery = $resObj->productsid_recommended;
                }
                $result['thread_id'] = $threadId;
                $result['message'] = $resObj->message;
                $result['productsid_recommended'] = $aiQuery;
                $result['preferences'] = $resObj->preferences;
                
                echo json_encode($result);exit;
           }
        
    }


}



