<?php
require_once('Agro_Curl.php');

preg_match("/^agrobr-app02\.*/", gethostname(), $matches);

$now = new \Datetime;
try {
    if (count($matches)>0) {
        $curl = new Agro_Curl('agronet.agrobrasilseguros.com.br', 'https');
    } else {
        $curl = new Agro_Curl('agronet.local', 'http');
    }

    $curl->setUrl('/sinistro2/liquidacao/enviarrelatoriospagamentosrealizados');
    $body = [];

    if (!empty($argv[1])) {
        if (empty($argv[2])) {
            throw new Exception("Necessário informar data de início e data de fim do período desejado.\nO formato da data deve ser 'Y-m-d', ex: 2025-05-01.");
        }
        
        $dateTimeIni = DateTime::createFromFormat('Y-m-d', $argv[1]);
        $dateTimeFim = DateTime::createFromFormat('Y-m-d', $argv[2]);
        
        if (!$dateTimeIni || !$dateTimeFim) {
            throw new Exception("Datas informadas estão erradas. Devem seguir o formato 'Y-m-d', ex: 2025-05-01.");
        }

        if ($dateTimeIni > $dateTimeFim) {
            throw new Exception("Data de início deve ser anteiror a data final.");
        }

        $body = [
            'dataInicio' => $argv[1],
            'dataFim' => $argv[2],
        ];
    }

    $curl->doRequest('POST', $body);

    $result = $curl->getResult();
    $result = $now->format('Y-m-d H:i:s') . ": ".$result->mensagem." \n";
} catch (\Exception $e) {
    $result = $now->format('Y-m-d H:i:s') . ': ' . $e->getMessage() . '. ' . $e->getTraceAsString() ."\n";
}


echo $result;