<?php

namespace classes;
require_once WD . '/modules/ocrSpace/ocrSpace_c.php';

use Exception;
use interfaces\ocr_space_i;
use ocrSpace\ocrSpace_c;

class ocr_space implements ocr_space_i
{
    /**
     * The configuration of the module
     * @var ocrSpace_c
     */
    public ocrSpace_c $config;
    /**
     * API URL
     * @var string
     */
    private string $api_url = 'https://api.ocr.space/parse/image';


    public function __construct()
    {
        $this->config = new ocrSpace_c();
    }


    /**
     * @inheritDoc
     */
    public function requireModuleEnabled(): void
    {
        if (!(bool)$this->config->enabled->getVariableValue()) {
            throw new Exception('OCR Space module is not enabled.');
        }
    }


    /**
     * @inheritDoc
     * @throws Exception If the module is not enabled or if there is an error in the API request
     * @throws Exception If the API response cannot be parsed
     */
    public function get_ocr_result(string $base64_image): array
    {
        $this->requireModuleEnabled();
        if (empty($base64_image)) {
            throw new Exception('Base64 image string cannot be empty.');
        }

        $formData = [
            'base64Image' => $base64_image,
            'isOverlayRequired' => 'true',
            'scale' => 'true',
            'detectOrientation' => 'true',
            'language' => 'eng',
            'OCREngine' => '2'
        ];

        $options = [
            'http' => [
                'method' => 'POST',
                'header' => [
                    'apikey: ' . $this->config->api_key->getVariableValue(),
                    'Content-Type: application/x-www-form-urlencoded'
                ],
                'content' => http_build_query($formData)
            ]
        ];

        $context = stream_context_create($options);
        $result = file_get_contents($this->api_url, false, $context);

        if ($result === false) {
            throw new Exception('Failed to get OCR result from API.');
        }

        $response = json_decode($result, true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new Exception('Failed to parse OCR API response.');
        }

        return $response;
    }
}