<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Receipt AI</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
  	<style>
		table {
		  border-collapse: collapse;
		}

		table, th, td {
		  border: 1px solid black;
		}
</style>

  </head>


  <body>
  	<div class="px-4 py-5 my-5 text-center">
 
    <h1 class="display-5 fw-bold text-body-emphasis">Receipt AI</h1>
    <div class="col-lg-6 mx-auto">
      
    	<form  method="post" enctype="multipart/form-data">
		  <input type="file" name="fileToUpload" id="fileToUpload" class="btn btn-outline-secondary btn-lg px-4 gap-3">
		  <input type="submit" value="Upload Image" name="submit" class="btn btn-primary btn-lg px-4">
		</form>	

    </div>
  </div>
    	


    

<div class="container text-center">
  <div class="row">
 
    <div class="col-sm-4">
    <!-- <div class="col-sm-8">col-sm-8</div> 
  </div>-->




<?php
ini_set('display_errors', 1); 
ini_set('display_startup_errors', 1); 
error_reporting(E_ALL);

require __DIR__ . '/vendor/autoload.php';
use OpenAI;
use Google\Cloud\Vision\V1\ImageAnnotatorClient;
use Google\Cloud\Vision\VisionClient;

putenv("GOOGLE_APPLICATION_CREDENTIALS=FireworksDigitalDevelopment-4b023518c824.json");
$openaiKey = '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';

if(isset($_POST['submit'])){
	$target_dir = "img/";
	$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
      } else {
        echo "Sorry, there was an error uploading your file.";
      }
    echo "<img src='".$target_file."' style='width:350px;'><br></div>";
    
    $imageAnnotator = new ImageAnnotatorClient();
    $vision = new VisionClient([
        'projectId' => 'fireworks-digital-development',
        'keyFilePath' => 'FireworksDigitalDevelopment-4b023518c824.json'
    ]);


    $image = fopen($target_file, 'r');
    $response = $imageAnnotator->textDetection($image);
    $jsonResponse = $response->serializeToJsonString();

    $resFile = "visionjson/res_".time().".txt";
    file_put_contents($resFile, $jsonResponse);
    $client = OpenAI::client($openaiKey);

    $response = $client->files()->upload([
        'purpose' => 'fine-tune',
        'file' => fopen($resFile, 'r'),
    ]);
    $fileid = $response->id;
 
    $response = $client->threads()->createAndRun([
	    'assistant_id' => 'asst_QrQ7JIOI2wDOAjKy554UerJ6',
	    'model' => 'gpt-3.5-turbo',
	    'thread' => [
	        'messages' => [
	            [
	                'role' => 'user',
	                'content' => "return only the json result",
	                'attachments' => [
	                    [
	                        'file_id' => $fileid,
	                        'tools' => [
	                            [
	                                'type' => 'file_search',
	                            ]
	                        ]
	                    ]
	                ]
	            ],
	        ],
	    ],
	]);

    $threadId = $response->threadId;
    //echo $threadId;
    sleep(3);
    $maxRetries = 10;
    $attempts = 0;
    $assistantMessage = null;

    while ($attempts < $maxRetries) {
        // Step 4: Fetch the latest messages from the thread
        $responseMessages = $client->threads()->messages()->list($threadId, [
            'limit' => 1, // We only want the most recent message
        ]);

        // Step 5: Extract the assistant's message
        foreach ($responseMessages['data'] as $message) {
            if ($message['role'] === 'assistant') {
                $assistantMessage = $message['content'];
                break 2; // Exit both loops once we find the assistant's response
            }
        }

        // Step 6: If no assistant response, wait before retrying
        if ($assistantMessage === null) {
            sleep(3); // Wait for 3 seconds before retrying (adjust if needed)
        }

        $attempts++;
    }
    echo '<div class="col-sm-8">';
    // Step 7: Display the assistant's response
   	
    $merchant= "";
    $receipt="";
    $receipt_date="";;
    $amount="";


    if ($assistantMessage) {
        $gptResultRaw = $assistantMessage[0]['text']['value'];
        //var_dump($gptResultRaw);
        $gptResultRaw = json_decode($gptResultRaw);
        $merchant= $gptResultRaw->merchant_name;
        $receipt=$gptResultRaw->receipt_no;
        $receipt_date=$gptResultRaw->receipt_date;
        $amount=$gptResultRaw->amount;
        //$gptResult = array();
        
    } else {
       echo "OpenAI Timeout";
    }

}

?>
<?php if(isset($_POST['submit'])){?>
<table class="table">
<tr><td style="width:150px;">Thread ID</td><td id='threadid'><?=$threadId?></td></tr>
<tr><td style="width:150px;">Merchant</td><td id='merchant'><?=$merchant?></td></tr>
<tr><td>Receipt ID</td><td id='receipt'><?php echo $receipt; ?></td></tr>
<tr><td>Receipt Date</td><td id='receipt_date'><?=$receipt_date?></td></tr>
<tr><td>Amount</td><td id='amount'><?=$amount?></td></tr>
<!-- <tr><td>Location</td><td id='amount'><?=$ocr_location?></td></tr> -->

</table>
<?php }?>
		</div>
	</div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
  </body>
</html>