<?php

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";

            // Google Cloud Vision API setup
            putenv('GOOGLE_APPLICATION_CREDENTIALS=./files/client_secret_487656227230-n4mbhim3pnvl3ih9s281fqi715k3vab0.apps.googleusercontent.com.json'); // Path to your service account key file
            $imageAnnotator = new ImageAnnotatorClient();

            // Perform OCR
            $image = file_get_contents($target_file);
            $response = $imageAnnotator->textDetection($image);
            $texts = $response->getTextAnnotations();

            // Extract specific fields (you'll need to adjust this logic based on your image layout)
            $AllTexts = $extracted_data;
            $extracted_data = extractDataFromText($texts);
            
    if (preg_match('/Date:\s*(\d{4}-\d{2}-\d{2})/', $texts, $matches)) {
        $extracted_data ['date'] = $matches[1];
    } else {
        $extracted_data ['date'] = null;
    }

    if (preg_match('/Weight:\s*([\d\.]+)/', $texts, $matches)) {
        $extracted_data ['weight'] = $matches[1];
    } else {
        $extracted_data ['weight'] = null;
    }

    if (preg_match('/Total Weight:\s*([\d\.]+)/', $texts, $matches)) {
        $extracted_data ['total_weight'] = $matches[1];
    } else {
        $extracted_data ['total_weight'] = null;
    }

    if (preg_match('/Registration:\s*([\w\d]+)/', $texts, $matches)) {
        $extracted_data ['registration'] = $matches[1];
    } else {
        $extracted_data ['registration'] = null;
    }

    if (preg_match('/Code:\s*([\w\d]+)/', $texts, $matches)) {
        $data['code'] = $matches[1];
    } else {
        $data['code'] = null;
    }

    return $extracted_data;
        

            // 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['date'], 
                              $extracted_data['weight'], 
                              $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 = [
        'date' => '',
        'weight' => '',
        'total_weight' => '',
        'registration' => '',
        'code' => ''
    ];

    // Implement your logic here to find and extract the data fields
    // You can use regular expressions, string manipulation, or analyze the 
    // bounding box information from $texts to locate the data.

    // Example (replace with your actual extraction logic):
    foreach ($texts as $text) {
        if (strpos($text->getDescription(), 'Date:') !== false) {
            $extracted_data['date'] = trim(str_replace('Date:', '', $text->getDescription()));
        } // ... and so on for other fields
    }

    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">
    <input type="submit" value="Upload Image" name="submit">
</form>