<?php
#show all errors
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('max_execution_time', 1200);
putenv('TESSDATA_PREFIX=/usr/share/tesseract-ocr/4.00/tessdata/');
error_reporting(E_ALL);

require 'vendor/autoload.php';

use thiagoalessio\TesseractOCR\TesseractOCR;

header('Content-Type: application/json');

// Check if Imagick extension is loaded
if (!extension_loaded('imagick')) {
    echo json_encode(['status' => 'error', 'message' => 'Imagick extension not installed']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_FILES['pdf']) && $_FILES['pdf']['error'] === UPLOAD_ERR_OK) {
        $pdf_path = $_FILES['pdf']['tmp_name'];
        error_log('Ricevuto PDF: ' . $pdf_path . ' - size: ' . filesize($pdf_path));
        if (!file_exists($pdf_path)) {
            error_log('PDF non trovato!');
        }
        $pdfFilePath = $_FILES['pdf']['tmp_name'];
        $outputDir = 'output_images';

        // Ensure the script has permission to create directories
        if (!is_writable($outputDir)) {
            var_dump($outputDir);
            echo json_encode(['status' => 'error', 'message' => 'Permission denied to create directory']);
            exit;
        }

        // Convert PDF to images
        error_log('Inizio conversione PDF');
        $images = convertPdfToImages($pdfFilePath, $outputDir);
        error_log('Fine conversione PDF, inizio OCR');

        // Initialize TesseractOCR
        $ocr = new TesseractOCR();

        $result = [];
        // Read text from each image
        foreach ($images as $image) {
            $imageSize = filesize($image);
            error_log('OCR: dimensione immagine ' . $image . ' = ' . $imageSize . ' bytes');
            error_log('OCR: inizio su ' . $image . ' at ' . date('H:i:s'));
            //echo 'OCR: inizio su ' . $image . ' at ' . date('H:i:s') . "\n";
            //exit;
            $text = (new TesseractOCR($image))
                ->lang('ita')
                ->timeout(160)
                ->run();
            error_log('OCR: fine su ' . $image . ' at ' . date('H:i:s'));
            $result[] = [
                'image' => $image,
                'text' => $text
            ];
        }
        error_log('Fine OCR');
        // Extract required information
        $extractedData = extractInformation($result);

        echo json_encode(['status' => 'success', 'data' => $extractedData]);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Invalid file upload']);
    }
} else {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method']);
}

function convertPdfToImages($pdfFilePath, $outputDir)
{
    $imagick = new Imagick();
    $imagick->setResolution(150, 150);
    $imagick->readImage($pdfFilePath . '[0]');
    $imagick->setImageFormat('png');

    $images = [];
    foreach ($imagick as $index => $image) {
        $width = $image->getImageWidth();
        $height = $image->getImageHeight();
        $cropY = (int)($height * 0.25);
        $cropHeight = (int)($height * 0.70); // 100% - 25% sopra - 5% sotto = 70% (include il footer con protocollo)
        $image->cropImage($width, $cropHeight, 0, $cropY);
        $image->setImagePage(0, 0, 0, 0);
        $image->setImageType(Imagick::IMGTYPE_GRAYSCALE);
        $imagePath = $outputDir . '/page-' . $index . '.png';
        $image->writeImage($imagePath);
        $images[] = $imagePath;
    }
    return $images;
}

// Function to extract course name, employee name, and release date
function extractInformation($ocrResults)
{
    $courseName = '';
    $employeeName = '';
    $releaseDate = '';

    foreach ($ocrResults as $result) {
        $text = $result['text'];
        // Extract employee name    
        if (preg_match('/Conferito a\s+([A-Z\s\'À-ÖØ-öø-ÿ]+)(?=\s|$)/', $text, $matches)) {
            $employeeName = trim($matches[1]);
        }

        // Extract release date
        //- Periodo della formazione: dal 11/10/2024 al 23/10/2024 we need to extract the date after "al"
        if (preg_match('/Periodo della formazione: dal \d{2}\/\d{2}\/\d{4} al (\d{2}\/\d{2}\/\d{4})/', $text, $matches)) {
            $releaseDate = $matches[1];
        }
        //Se è vuoto $releaseDate prendere Periodo della formazione: il 04/11/2024
        if (preg_match('/Periodo della formazione: .. (\d{2}\/\d{2}\/\d{4})/', $text, $matches)) {
            $releaseDate = $matches[1];
        }

        // Extract course name
        //Protocollo: 547A.51026628.MO.14806 we need to extract only the first 4 characters after "Protocollo: "
        if (preg_match('/Protocollo:\s*([A-Z0-9]{4})/i', $text, $matches)) {
            $courseName = $matches[1];
        }

        // Se non trova il protocollo, prova con la mansione
        if (empty($courseName) && preg_match('/Mansione:\s*([A-Z\s]+?)(?:\n|$)/i', $text, $matches)) {
            $courseName = trim($matches[1]);
        }
    }

    return [
        'course_name' => $courseName,
        'employee_name' => $employeeName,
        'release_date' => $releaseDate
    ];
}
