<?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('localhost', 'http');
    }

    $hoje = new DateTime('now');
    $parametros = ['enviarEmail' => true];

    if (isset($argv[1]) && isset($argv[2])) {
        $d1 = DateTime::createFromFormat('Y-m-d', $argv[1]);
        $d2 = DateTime::createFromFormat('Y-m-d', $argv[2]);

        if (
            !($d1 && $d1->format('Y-m-d') === $argv[1])
            || !($d2 && $d2->format('Y-m-d') === $argv[2])
        ) {
            throw new Exception('Datas informadas não estão no padrão Y-m-d');
        }

        $dataInicio = $argv[1];
        $dataFim = $argv[2];
    }
    
    $parametros['dt_inicio'] = $dataInicio
        ?? (clone $hoje)->modify('first day of this month')->format('Y-m-d');
    $parametros['dt_fim'] = $dataFim
        ?? (clone $hoje)->modify('last day of this month')->format('Y-m-d');

    $curl->setUrl('/relatorio/sinistro/cadastrosmapa');
    $curl->doRequest('POST', $parametros);
    
    $result = $curl->getResult();
    $result = $now->format('Y-m-d H:i:s') . ": " . $result->message . " \n";
} catch (\Exception $e) {
    $result = $now->format('Y-m-d H:i:s') . ': ' . $e->getMessage() . '. ' . $e->getTraceAsString() . "\n";
}

echo $result;