<?php
// echo 123;
// exit();

putenv("GOOGLE_APPLICATION_CREDENTIALS=" . __DIR__ . '/test-ocr-388123-ffabaf2c769c.json');

# Includes the autoloader for libraries installed with composer
require __DIR__ . '/vendor/autoload.php';

# Imports the Google Cloud client library
use Google\Cloud\DocumentAI\V1\DocumentProcessorServiceClient;
use Google\Cloud\DocumentAI\V1\RawDocument;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $targetDir = "uploads/";
    $originalName = $_FILES["fileToUpload"]["name"];
    $extension = pathinfo($originalName, PATHINFO_EXTENSION);
    $newName = uniqid() . '.' . $extension; // Generate a unique name
    $targetFile = $targetDir . $newName;
    $uploadOk = 1;
    $pdfFileType = strtolower($extension);

    // Check if file is a PDF
    if ($pdfFileType != "pdf") {
        echo "Sorry, only PDF files are allowed.";
        $uploadOk = 0;
    }

    // Check if file already exists
    if (file_exists($targetFile)) {
        echo "Sorry, file already exists.";
        $uploadOk = 0;
    }

    /*// Check file size
    if ($_FILES["fileToUpload"]["size"] > 500000) {
        echo "Sorry, your file is too large.";
        $uploadOk = 0;
    }*/

    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
    } else {
        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $targetFile)) {

            $projectId = 'test-ocr-388123'; # Your Google Cloud Platform project ID
            $location = 'us'; # Your Processor Location
            // $processor = '8f2c7ed42230fea8'; # Your Processor ID

            if($_POST['UC'] == 'Eversource')
            {
                $processor = '39b4e8ced71d1806';
            }
            else if($_POST['UC'] == 'National Grid')
            {

                $processor = 'afa693e155c7f57f'; # Your Processor ID
            }
            

            # Create Client
            $client = new DocumentProcessorServiceClient();

            # Local File Path
            //$documentPath = 'NH_ES_Bill.pdf';
            $documentPath = $targetFile;

            # Read in File Contents
            $handle = fopen($documentPath, 'rb');
            $contents = fread($handle, filesize($documentPath));
            fclose($handle);

            # Load File Contents into RawDocument
            $rawDocument = new RawDocument([
                'content' => $contents,
                'mime_type' => 'application/pdf'
            ]);

            # Fully-qualified Processor Name
            $name = $client->processorName($projectId, $location, $processor);

            # Make Processing Request
            $response = $client->processDocument($name, [
                'rawDocument' => $rawDocument
            ]);

            # Print Document Text
            //printf('Document Text: %s', $response->getDocument()->getText());
            //printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString());
            
            $entities = json_decode($response->serializeToJsonString())->document->entities;

            $entityData = array();

            foreach ($entities as $key => $value) {
                $entityData[$value->type] = $value->mentionText;
            }

        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }
}

?>

<!DOCTYPE html>
<html>
<body style="text-align: center;">
    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-data">
        <select name="UC">
            <option value="Eversource">Eversource</option>
            <option value="National Grid">National Grid</option>
        </select>
        <input type="file" name="fileToUpload" id="fileToUpload">
        <input type="submit" value="Upload PDF" name="submit">
    </form>

    <?php if( !empty($entityData) ){ ?>
    <table border="1" cellpadding="1" cellspacing="1" style="margin-left: auto;margin-right: auto;">
        <tr>
            <td>Account Number</td>
            <td><?= $entityData['Account_Number'] ?></td>
        </tr>
        <tr>
            <td>Address</td>
            <td><?= $entityData['address'] ?></td>
        </tr>
        <tr>
            <td>Contact Name</td>
            <td><?= $entityData['contact_name'] ?></td>
        </tr>
        <tr>
            <td>Meter Number</td>
            <td><?= $entityData['meter_number'] ?></td>
        </tr>
        <tr>
            <td>First Month</td>
            <td><?= $entityData['first_month'] ?></td>
        </tr>
        <tr>
            <td>Second Month</td>
            <td><?= $entityData['second_month'] ?></td>
        </tr>
        <tr>
            <td>Third Month</td>
            <td><?= $entityData['third_month'] ?></td>
        </tr>
        <tr>
            <td>Fourth Month</td>
            <td><?= $entityData['fourth_month'] ?></td>
        </tr>
        <tr>
            <td>Fifth Month</td>
            <td><?= $entityData['fifth_month'] ?></td>
        </tr>
        <tr>
            <td>Sixth Month</td>
            <td><?= $entityData['sixth_month'] ?></td>
        </tr>
        <tr>
            <td>Seventh Month</td>
            <td><?= $entityData['seventh_month'] ?></td>
        </tr>
        <tr>
            <td>Eight Month</td>
            <td><?= $entityData['eight_month'] ?></td>
        </tr>
        <tr>
            <td>Nineth Month</td>
            <td><?= $entityData['nineth_month'] ?></td>
        </tr>
        <tr>
            <td>Tenth Month</td>
            <td><?= $entityData['tenth_month'] ?></td>
        </tr>
        <tr>
            <td>Eleventh Month</td>
            <td><?= $entityData['eleventh_month'] ?></td>
        </tr>
        <tr>
            <td>Twelveth Month</td>
            <td><?= $entityData['twelveth_month'] ?></td>
        </tr>
        <tr>
            <td>Thirteenth Month</td>
            <td><?= $entityData['thirtheen_month'] ?></td>
        </tr>
        <tr>
            <td>Subtotal Delivery Services</td>
            <td><?= $entityData['subtotal_delivery_services'] ?></td>
        </tr>
        <tr>
            <td>Subtotal Supplier Services</td>
            <td><?= $entityData['subtotal_supplier_services'] ?></td>
        </tr>
    </table>
    <?php } ?>
</body>
</html>