<?php

ini_set('display_errors', 1);
error_reporting(E_ALL);

require 'vendor/autoload.php'; // Include Google Cloud Vision library

use Google\Cloud\Vision\V1\ImageAnnotatorClient;

// Database credentials
$servername = "ns1.jadex.co.za";
$username = "andtech01_andrew";
$password = "Jadex02641!";
$dbname = "andtech01_ocr_google";

// Connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['image'])) {
    $image_file = $_FILES['image'];

    // Validation (add more robust checks)
    if ($image_file['error'] === UPLOAD_ERR_OK) {
        $target_dir = "uploads/";
        $target_file = $target_dir . basename($image_file["name"]);

        if (move_uploaded_file($image_file["tmp_name"], $target_file)) {
            echo "Image uploaded successfully.\n";
            $credentialsPath = 'files/ocr-jadexsystem-5d99e46fd1ce.json';

            // Check if the file exists
            if (!file_exists($credentialsPath)) {
                die("Error: Credentials file not found at: " . $credentialsPath);
            } else {
                echo "Credentials file found! <br>"; // Confirmation message
            }
            // Google Cloud Vision API setup
            putenv('GOOGLE_APPLICATION_CREDENTIALS=files/ocr-jadexsystem-5d99e46fd1ce.json'); // Path to your service account key file
            echo "Reached this point";
            $imageAnnotator = new ImageAnnotatorClient();
            echo "Google yes";
            // Perform OCR
            $image = file_get_contents($target_file);
            $response = $imageAnnotator->textDetection($image);
            $texts = $response->getTextAnnotations();
            
            // Extract specific fields 
            $extracted_data = extractDataFromText($texts);
            $AllTexts = json_encode($extracted_data); // Convert to string
            
            // Insert data into the database
            $sql = "INSERT INTO extracted_text (alltext, ticketdate, grossweight, total_weight, registration, code) 
                    VALUES (?, ?, ?, ?, ?, ?)";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("ssssss", 
                                $AllTexts,
                                $extracted_data['ticketdate'], 
                                $extracted_data['grossweight'], 
                                $extracted_data['total_weight'], 
                                $extracted_data['registration'], 
                                $extracted_data['code']);

            if ($stmt->execute()) {
                echo "New record created successfully";
            } else {
                echo "Error: " . $sql . "<br>" . $conn->error;
            }

            $stmt->close();

            $imageAnnotator->close();
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    } else {
        echo "Error uploading image: " . $image_file['error'];
    }
}

$conn->close();

// Function to extract specific data fields from OCR text
function extractDataFromText($texts) {
    $extracted_data = [
        'ticketdate' => '',
        'grossweight' => '',
        'total_weight' => '',
        'registration' => '',
        'code' => ''
    ];

    // Loop through each detected text block
    foreach ($texts as $text) {
        $description = $text->getDescription();

        if (preg_match('/Date:\s*(\d{4}-\d{2}-\d{2})/', $description, $matches)) {
            $extracted_data['ticketdate'] = $matches[1];
        } 
        if (preg_match('/Weight:\s*([\d\.]+)/', $description, $matches)) {
            $extracted_data['grossweight'] = $matches[1];
        } 
        if (preg_match('/Total Weight:\s*([\d\.]+)/', $description, $matches)) {
            $extracted_data['total_weight'] = $matches[1];
        } 
        if (preg_match('/Registration:\s*([\w\d]+)/', $description, $matches)) {
            $extracted_data['registration'] = $matches[1];
        } 
        if (preg_match('/Code:\s*([\w\d]+)/', $description, $matches)) {
            $extracted_data['code'] = $matches[1];
        } 
    }

    return $extracted_data;
}

?>

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="image" id="image"><br>
    <input type="submit" value="Upload Image" name="submit">
</form>
