<?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_CfxsYXP15SzsBXo2SEhP84Jf';*/
$openaiKey = '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';
$assistantId= 'asst_zdWZvECh0eDXyIqksBagCakp';

$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'];

        if (strpos(strtolower($message), "more") !== false) {
            $fileContent = file_get_contents("placejson/".$threadId.".txt");
            
            if($fileContent != false && $fileContent != ""){
                $message .= ", get the matched location place_id from this list:".file_get_contents("placejson/".$threadId.".txt");


                $response = $client->chat()->create([
                    'model' => 'gpt-4.1', // or 'gpt-3.5-turbo'
                    'messages' => [
                                    ['role' => 'system', 'content' => "User will tell you what location he want, and you will get the place_id from the JSON list, that user provide, reply with only the place_id matched, without other explanation"],
                                    ['role' => 'user', 'content' => $message]
                                ]

                ]);
                $place_id = $response['choices'][0]['message']['content'];


                $placeContent = placeDetails($place_id);

                $jsonResponse = json_encode($placeContent);

                $response = $client->chat()->create([
                'model' => 'gpt-4.1', // or 'gpt-3.5-turbo'
                'messages' => [
                    ['role' => 'system', 'content' => "You are a restaurent, cafe recommender. When a user provides you with information about a restaurent or cafe, your task is read the place user's reviews and suggest reasons for why this place would be a great fit for user, focusing on providing a detailed, friendly, and thoughtful explanation. The JSON provided is from system, do not mentioned they provide this location when reply the user. Describe about Place Name, City, pro and con,what’s popular here,highlight popular aspects,what to avoid: Mention any common complaints,open time today,current opening hours, and budget, and user reviews.


            # Steps

            1. **Understand User Preferences:** Identify any preferences or specific interests the user might have based on the place they mention or other contextual clues.
            2. **Analyze the Place:** Read carefully the information provided about the place to understand its key features and attractions.
            3. **Reason Selection:** Determine the main reasons that the place aligns well with the user's preferences and interests.
            4. **Friendly Explanation:** Elaborate on these reasons with a warm and engaging tone, highlighting unique aspects of the place.
            5. **Assure and Encourage:** Conclude with a note of assurance that this place is a great pick, and encourage experiencing its offerings.

            # Output Format

            - Provide a friendly and detailed paragraph that explains why the place is recommended.
            - Use conversational language to engage the user.
            - Mention specific attributes or features of the place as they relate to potential interests of the user.


            # Notes

            - Always tailor the recommendations to align with mentions or clues about user interests.
            - Keep the tone positive, warm, and engaging to enhance user interaction and interest.
            - Be considerate of cultural and individual diversity to avoid making assumptions."],
                    ['role' => 'user', 'content' => $message]
                ]
                
                ]);

                // Output the response
                 

                $allResult = array();
                $allResult['thread_id'] = $threadId;
                $allResult['message'] = $response['choices'][0]['message']['content'];                       
                echo json_encode($allResult);exit;




            }
        }


        

        // 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(2); // 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-4.1',
            'thread' => [
                'messages' => [
                    [
                        'role' => 'user',
                        'content' => $message,
                    ],
                ],
            ],
        ]); 
        $threadId = $response->threadId;
        try{
            do {
                sleep(2); // 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;
    $placeDetails = 0;
    if ($assistantMessage) {
        //var_dump($gptResultRaw);exit;
        $resObj = json_decode($assistantMessage);

        //var_dump($resObj);
        
        $result['thread_id'] = $threadId;
        if(!$resObj){
            var_dump($assistantMessage);exit; 
        }
        $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->place_id) && $resObj->place_id != null){
            $placeDetails = 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;*/



         //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->place_id) && $resObj->place_id != null){
                    $placeDetails = 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;*/
           }
        
    }
    $apiKey = "AIzaSyAq1ODKKCVgTT3yvuqrsSIL8biDjhNu8NM";
    if($searchPlace == 1){
        

        $placesResponse = searchPlaces($aiQuery);
        $resList =array();
        foreach($placesResponse as $placesItem){
            $resSend = array();
            $resSend['place_id'] = $placesItem['place_id'];
            $resSend['name'] = $placesItem['name'];
            $resList[] = $resSend;
        }
        

        $jsonResponse = json_encode($resList);
        $resFile = "placejson/".$threadId.".txt";
        file_put_contents($resFile, $jsonResponse);

        /*$resFile = "placejson/res_".time().".txt";
        file_put_contents($resFile, $jsonResponse);

        $response = $client->files()->upload([
            'purpose' => 'fine-tune',
            'file' => fopen($resFile, 'r'),
        ]);
        $fileid = $response->id;
        //var_dump($fileid);
        $response = $client->threads()->messages()->create($threadId, [
            'role' => 'user',
            'content' => "locations in this file,list down the top 10 suggested with the #PlacesOutputFormat, with pro and con too. with this preferences:".$aiQuery,
            '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(2); // Avoid excessive API calls
            $runStatus = $client->threads()->runs()->retrieve($threadId, $run['id']);
        } while ($runStatus['status'] !== 'completed');

        $assistantMessage = loopGetResponse($threadId);
*/

        $response = $client->chat()->create([
            'model' => 'gpt-3.5-turbo', // or 'gpt-3.5-turbo'
            'response_format'=>[
              "type"=> "json_object"
            ],
            'messages' => [
                ['role' => 'system', 'content' => 'You are an intelligent and friendly Lifestyle Location Recommender. Your primary function is to assist users in finding suitable places based on their preferences. User will send you JSON with list of location. Choose 5 of the location that suitable, and tell user the location summary, pro and con,with longer sentense, in this format

        {
          "message": "Here are some cheap restaurants we suggest for you",
          "places": [
            {
              "title": "Bear Furry House",
              "summary": "Highly praised for its grooming services and the care they show to pets.",
              "place_id": "ChIJMWbeGr1NzDER0SSVmuzdNEM",
              "image_ref": "places/ChIJ48UkXKVNzDERTayA_Psb7jc/photos/AVzFdbmGHxCUyvyKMtWl1QMDIamz2chqQT2oQcW9fvzipTE1AtNPMtwyqKg1ybevOp940unzJ8L5nqVX53vlOMOlxMBXf5DGfIVi-4WmnHvIlkWttPPfAy1K5irvzkKyIVuRoUU_VvD-9MI0De0xFvrr8v3lrBL3AYL12j9S",
              "phone": "036781921",
              "pro": "Something good",
              "con": "Something bad",
            }
          ]
        }'],
                ['role' => 'user', 'content' => $jsonResponse]
            ]
            
          ]);

          // Output the response
        $assistantMessage = $response['choices'][0]['message']['content'];

       // var_dump($jsonResponse,$assistantMessage);
        if ($assistantMessage) {
       
       
        $resObjList = json_decode($assistantMessage);
    

        if($resObjList == false){
            $allResult = array();
            $allResult['thread_id'] = $threadId;
            $allResult['message'] = $assistantMessage;
            $allResult['query'] = $aiQuery;
            $allResult['places'] = array(); 
            echo json_encode($allResult);exit;
        }
        $placesResult =array();

        $placesSuggested = $resObjList->places;
        foreach($placesSuggested as $placeSuggest){
            $placesResultItem =array();
            $placesResultItem['place_id'] = $placeSuggest->place_id;
            $placesResultItem['title'] = $placeSuggest->title;
            $placesResultItem['summary'] = $placeSuggest->summary;
            $placesResultItem['pro'] = $placeSuggest->pro;
            $placesResultItem['con'] = $placeSuggest->con;
            foreach($placesResponse as $resItem){
                if($resItem['place_id'] == $placeSuggest->place_id){
                    $placesResultItem['image_ref'] = $resItem['image'];
                    if (isset($resItem['phone'])) {
                        $placesResultItem['phone'] = $resItem['phone'];
                    }else{
                        $placesResultItem['phone'] = "";
                    }
                    
                }
            }
            $placesResult[] = $placesResultItem;
        }
        $resObjList->places = $placesResult;

        //var_dump($resObjList);exit;
        $locationArray = array();
        $allResult = array();
        $allResult['thread_id'] = $threadId;
        $allResult['message'] = $resObjList->message;
        $allResult['query'] = $aiQuery;
        $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['query'] = $aiQuery;
                $allResult['places'] = $resObjList->places;
                echo json_encode($allResult);exit;
            }
            
        }

    }else if($placeDetails == 1){
        $placeContent = placeDetails($resObj->place_id);
        $jsonResponse = json_encode($placeContent);
        $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' => "place details in this file, follow #ExpandLocationDetails. Say out its Place Name, City, pro and con,what’s popular here,highlight popular aspects,what to avoid: Mention any common complaints,open time today,current opening hours, and budget, and user's reviews, in 'message' parameter",
            '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;              
                echo json_encode($allResult);exit;
        }
        //var_dump($resObjList);exit;
        $locationArray = array();
        $allResult = array();
        $allResult['thread_id'] = $threadId;
        $allResult['message'] = $resObjList->message;
       
        echo json_encode($allResult);exit;
    }

    }

}



