<?php

class Seguro_Model_CAR extends Agro_Db_Table_Abstract {

    private $url;
    private $curl;

    public function __construct()
    {
        if (empty(CAR_API_URL)) {
            throw new Exception("API do CAR não configurada.");
        }

        $this->url = CAR_API_URL;
        $this->curl = curl_init();
        curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, false);
    }


    public function find(string $lat, string $long): array
    {
        curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($this->curl, CURLOPT_URL, $this->url . "find?lat={$lat}&long={$long}");
        $retorno = curl_exec($this->curl);
        return !$retorno ? [] : (array) json_decode($retorno, true);
    }

    public function downloadCoordinates(): void
    {
        ini_set('output_buffering', 'off');
        ini_set('zlib.output_compression', false);

        header("Content-Type: application/x-bzip2");
        header("Content-Disposition: attachment; filename=coordenadas.json.bz2");
        header("Location: " . $this->url . "download_coordinates");

        curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, false);
        curl_setopt($this->curl, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($this->curl, CURLOPT_TIMEOUT, 0);
        curl_setopt($this->curl, CURLOPT_CONNECTTIMEOUT, 0);
        curl_setopt($this->curl, CURLOPT_LOW_SPEED_LIMIT, 1);
        curl_setopt($this->curl, CURLOPT_LOW_SPEED_TIME, 0);
        curl_setopt($this->curl, CURLOPT_BUFFERSIZE, 1024 * 1024);
        curl_setopt($this->curl, CURLOPT_WRITEFUNCTION, function($ch, $data) {
            echo $data;

            if (function_exists('fastcgi_finish_request')) {
                fastcgi_finish_request();
            } else {
                flush();
            }

            return strlen($data);
        });

        curl_exec($this->curl);
        
        if (curl_errno($this->curl)) {
            throw new Exception("Erro: " . curl_error($this->curl));
        }

        curl_close($this->curl);
    }

    public function coordinatesFileInfo(): array
    {
        curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($this->curl, CURLOPT_URL, $this->url . "coordinates_file_info");
        $retorno = curl_exec($this->curl);
        return !$retorno ? [] : (array) json_decode($retorno, true);
    }
}