<?php

declare(strict_types=1);

use App\CiotAPI;
use App\MdfeXmlParser;

require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR . 'CiotAPI.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR . 'MdfeXmlParser.php';

$config = require dirname(__DIR__) . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'ciot.php';
$xmlPath = $argv[1] ?? dirname(__DIR__) . DIRECTORY_SEPARATOR . 'XML MDFE TESTE' . DIRECTORY_SEPARATOR . '51.xml';

if (!str_contains($xmlPath, DIRECTORY_SEPARATOR) && !str_contains($xmlPath, '/') && !str_contains($xmlPath, '\\')) {
    $xmlPath = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'XML MDFE TESTE' . DIRECTORY_SEPARATOR . $xmlPath;
}

$parser = new MdfeXmlParser();
$operationData = $parser->parseToCiotPayload($xmlPath);

$ciotApi = new CiotAPI([
    'environment' => $config['environment'],
    'provider_token' => $config['provider_token'],
    'homologation_url' => $config['homologation_url'],
    'production_url' => $config['production_url'],
    'timeout' => $config['timeout'],
    'connect_timeout' => $config['connect_timeout'],
    'log_file' => $config['log_file'],
    'client_certificate_path' => $config['client_certificate_path'],
    'client_certificate_password' => $config['client_certificate_password'],
    'client_certificate_type' => $config['client_certificate_type'],
]);

$response = $ciotApi->emitirCiot($operationData);

echo json_encode([
    'ambiente' => $config['environment'],
    'arquivo_xml' => realpath($xmlPath) ?: $xmlPath,
    'certificado_configurado' => [
        'subject' => $config['certificate_subject'],
        'cnpj' => $config['certificate_cnpj'],
        'thumbprint' => $config['certificate_thumbprint'],
        'arquivo_pfx_informado' => $config['client_certificate_path'] !== null,
    ],
    'payload_extraido_mdfe' => $operationData,
    'resposta_ciot' => $response,
], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) . PHP_EOL;
