<?php

namespace classes;
require_once WD . '/modules/licenseplaterecognizer/licenseplaterecognizer_c.php';

use Exception;
use interfaces\licenseplaterecognizer_i;
use licenseplaterecognizer\helpers\licenseplaterecognizer_info;
use licenseplaterecognizer\licenseplaterecognizer_c;

class licenseplaterecognizer implements licenseplaterecognizer_i
{
    /**
     * The configuration of the module
     * @var licenseplaterecognizer_c
     */
    public licenseplaterecognizer_c $config;
    /**
     * API URL
     * @var string
     */
    private string $api_url = 'https://vs4sws0kg4sog4ssw8kwowk4.coolify.truckwash.dk'; // Default (cloud): 'https://api.platerecognizer.com'; (without /v1/plate-reader/)';


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


    /**
     * @inheritDoc
     */
    public function requireModuleEnabled(): void
    {
        if (!(bool)$this->config->enabled->getVariableValue()) {
            throw new Exception('licenseplaterecognizer 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 licenseplaterecognizer(string $base64_image): array
    {
        $image_processor = new image_processor();

        //ADD PARAMETER IN REQUEST LIKE regions
        $data = array(
            'upload' => $base64_image,
            //'regions' => 'dk' // Optional
        );

        // Prepare new cURL resource
        //$ch = curl_init('https://api.platerecognizer.com/v1/plate-reader/');
        $ch = curl_init($this->api_url . '/v1/plate-reader/');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLINFO_HEADER_OUT, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2TLS);

        // Set HTTP Header for POST request
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                "Authorization: Token " . $this->config->api_key->getVariableValue()
            )
        );

        // Submit the POST request and close cURL session handle
        $result = curl_exec($ch);
        curl_close($ch);
        // Print the response from the server
        if ($result === false) {
            throw new Exception('Error in API request.');
        }

        $response_data = json_decode($result, true);
        if (isset($response_data['results']) && count($response_data['results']) > 0) {
            return [
                'success' => true,
                'license_plate_number' => $response_data['results'][0]['plate'] ?? null,
                'confidence' => $response_data['results'][0]['score'] ?? null,
                'raw_response' => $response_data,
            ];
        } else {
            return [
                'success' => false,
                'message' => 'No license plate detected.',
                'raw_response' => $response_data,
            ];
        }
    }

    /**
     * @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_usage(): licenseplaterecognizer_info
    {
        // Require the module to be enabled
        $this->requireModuleEnabled();
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $this->api_url . '/info/',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_2TLS,
            CURLOPT_CUSTOMREQUEST => 'GET',
            CURLOPT_HTTPHEADER => array(
                'Authorization: Token ' . $this->config->api_key->getVariableValue()
            ),
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        $response_data = json_decode($response, true);
        if ($response_data === null) {
            throw new Exception('Error parsing API response.');
        }
        return new licenseplaterecognizer_info($response_data);
    }
}