<?php

require 'vendor/autoload.php';

use Google\Cloud\Vision\V1\ImageAnnotatorClient;

// Set up Google Cloud Vision client
$vision = new ImageAnnotatorClient([
    'credentials' => 'path/to/your/service-account-key.json', // Replace with actual path
]);

// Process uploaded file
if(isset($_POST["submit"])) {
    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    $uploadOk = 1;
    $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

    // Check if file is a valid image or PDF
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
        && $imageFileType != "gif" && $imageFileType != "pdf") {
        echo "Sorry, only JPG, JPEG, PNG, GIF, and PDF files are allowed.";
        $uploadOk = 0;
    }

    if ($uploadOk == 1) {
        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
            echo "The file " . htmlspecialchars(basename($_FILES["fileToUpload"]["name"])) . " has been uploaded.";

            if ($imageFileType == "pdf") {
                // If the uploaded file is a PDF, use spatie/pdf-to-text to extract text
                $text = \Spatie\PdfToText\Pdf::getText($target_file);
            } else {
                // If the uploaded file is an image, use Google Cloud Vision API
                $imagePath = $target_file;
                $image = file_get_contents($imagePath);

                $response = $vision->textDetection($image);
                $texts = $response->getTextAnnotations();

                $extractedText = $texts[0]->getDescription();

                // Define variables to store extracted information
                $client_name = "";
                $account_number = "";
                $acc_balance = "";
                $created_date = "";

                foreach (explode("\n", $extractedText) as $line) {
                    if (strpos($line, "Client Name:") !== false) {
                        $client_name = trim(str_replace("Client Name:", "", $line));
                    } elseif (strpos($line, "Account Number:") !== false) {
                        $account_number = trim(str_replace("Account Number:", "", $line));
                    } elseif (strpos($line, "Balance:") !== false) {
                        $acc_balance = trim(str_replace("Balance:", "", $line));
                    } elseif (strpos($line, "Date:") !== false) {
                        $created_date = trim(str_replace("Date:", "", $line));
                    }
                }
            }
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }
}

// Clean up resources
if (isset($vision)) {
    $vision->close();
}

?>
