<?php

namespace Source\Models;

use Source\Conn\DataLayer;
use NFePHP\NFe\Tools;
use NFePHP\Common\Certificate;
use NFePHP\NFe\Common\Standardize;
use NFePHP\DA\NFe\Danfe;

class DocNFe extends DataLayer
{

    public function searchDoc(array $data)
    {

        $result = $this->db()->from('company')
            ->join('certificate', function($join){
                $join->on('certificate_id_company', 'company_id');
            })
            ->where('certificate_trash')->is('0')
            ->andWhere('company_id')->is($data['id'])
            ->limit(1)
            ->select()
            ->all();

        if($result){
            foreach($result as $r){

                $ciencia_automatica = $r->company_ciencia_operacao;

                $start_date = new \DateTime($r->company_ult_date_nfe_primary);
                $since_start = $start_date->diff(new \DateTime(date('Y-m-d H:i:s')));
                $minutes = $since_start->days * 24 * 60;
                $minutes += $since_start->h * 60;
                $minutes += $since_start->i;

                $array_r = ['.', '-', '/'];
                $array_c = ['', '', ''];
                if($minutes < '60'){
                    $this->call(
                        '200',
                        'Ops',
                        '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
                        "error",
                        "Intervalo de busca inoperante"
                    )->back(["count" => 0]);
                    return;
                }

                $arr = [
                    "atualizacao" => date('Y-m-d H:i:s'),
                    "tpAmb" => intval(1),
                    "razaosocial" => $r->company_name,
                    "cnpj" => str_replace($array_r, $array_c, $r->company_cpf_cnpj),
                    "siglaUF" => $r->company_uf,
                    "schemes" => "PL_009_V4",
                    "versao" => '4.00',
                    "tokenIBPT" => "",
                    "CSC" => "",
                    "CSCid" => "",
                    "proxyConf" => [
                        "proxyIp" => "",
                        "proxyPort" => "",
                        "proxyUser" => "",
                        "proxyPass" => ""
                    ]
                ];

                $configJson = json_encode($arr);
                $pfxcontent = file_get_contents('shared/certificado/'.$r->certificate_file);

                $tools = new Tools($configJson, Certificate::readPfx($pfxcontent, $r->certificate_password));
                $tools->model('55');
                $tools->setEnvironment(1);

                $ultNSU = $r->company_nsu_nfe_primary;
                $maxNSU = $ultNSU;
                $loopLimit = 12;
                $iCount = 0;
                while ($ultNSU <= $maxNSU) {
                    $iCount++;
                    if ($iCount >= $loopLimit) {
                        break;
                    }

                    try {
                        $resp = $tools->sefazDistDFe($ultNSU);
                        $dom1 = new \DOMDocument();
                        $dom1->loadXML($resp);
                        $node1      = $dom1->getElementsByTagName('retDistDFeInt')->item(0);
                        $cStat1     = $node1->getElementsByTagName('cStat')->item(0)->nodeValue;
                        $xMotivo1   = $node1->getElementsByTagName('xMotivo')->item(0)->nodeValue;


                        if($cStat1 == '656'){
                            $form_company['company_ult_date_nfe_primary'] = date('Y-m-d H:i:s');
                            $this->db()->update('company')->where('company_id')->is($data['id'])->set($form_company);
                            $this->call(
                                '200',
                                'Ops',
                                '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
                                "error",
                                "Houve um problema.".$xMotivo1
                            )->back(["count" => 0]);
                            return;
                        }

                        if($cStat1 == '489'){
                            $form_company['company_ult_date_nfe_primary'] = date('Y-m-d H:i:s');
                            $this->db()->update('company')->where('company_id')->is($data['id'])->set($form_company);
                            $this->call(
                                '200',
                                'Ops',
                                '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
                                "error",
                                "Houve um problema.".$xMotivo1
                            )->back(["count" => 0]);
                            return;
                        }
                    } catch (\Exception $e) {
                        $this->call(
                            '200',
                            'Ops',
                            '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
                            "error",
                            "Houve um problema. ".$e->getMessage()
                        )->back(["count" => 0]);
                        return;
                    }


                    $dom = new \DOMDocument();
                    $dom->loadXML($resp);
                    $node       = $dom->getElementsByTagName('retDistDFeInt')->item(0);
                    $tpAmb      = $node->getElementsByTagName('tpAmb')->item(0)->nodeValue;
                    $verAplic   = $node->getElementsByTagName('verAplic')->item(0)->nodeValue;
                    $cStat      = $node->getElementsByTagName('cStat')->item(0)->nodeValue;
                    $xMotivo    = $node->getElementsByTagName('xMotivo')->item(0)->nodeValue;
                    $dhResp     = $node->getElementsByTagName('dhResp')->item(0)->nodeValue;
                    $ultNSU     = $node->getElementsByTagName('ultNSU')->item(0)->nodeValue;
                    $maxNSU     = $node->getElementsByTagName('maxNSU')->item(0)->nodeValue;
                    $lote   = $node->getElementsByTagName('loteDistDFeInt')->item(0);
                    if (empty($lote)) {
                        continue;
                    }

                    $docs = $lote->getElementsByTagName('docZip');
                    foreach ($docs as $doc) {
                        $numnsu = $doc->getAttribute('NSU');
                        $schema = $doc->getAttribute('schema');
                        $content = gzdecode(base64_decode($doc->nodeValue));
                        $tipo = substr($schema, 0, 6);

                        $xml_correto = simplexml_load_string($content);


                        $form_zip['zip_id_company'] = $data['id'];
                        $form_zip['zip_doc'] = base64_encode($content);
                        $form_zip['zip_status'] = '0';
                        $this->db()->insert($form_zip)->into('zip');
                    }

                    if ($ultNSU == $maxNSU) {
                        break; //CUIDADO para não deixar seu loop infinito !!
                    }
                    sleep(2);
                }
                $form_company['company_nsu_nfe_primary'] = $ultNSU;
                $form_company['company_ult_date_nfe_primary'] = date('Y-m-d H:i:s');
                $this->db()->update('company')->where('company_id')->is($data['id'])->set($form_company);

                $this->call(
                    '200',
                    'Parabéns',
                    '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
                    "ok",
                    "Consulta realizada com sucesso"
                )->back(["count" => 0, "ciencia" => $ciencia_automatica]);
                return;
            }

        }
    }

    public function manifestaConsulta(array $data)
    {
        $explode_nfs = explode(',', $data['nfs']);

        if($data['inicio'] == '0'){
            unset($_SESSION['retorno_manifestacao']);
        }

        $result = $this->db()->from('company')
            ->join('certificate', function($join){
                $join->on('certificate_id_company', 'company_id');
            })
            ->join('doc', function($join){
                $join->on('doc_id_company', 'company_id');
            })
            ->where('certificate_trash')->is('0')
            ->andWhere('doc_id')->is($explode_nfs[$data['inicio']])
            ->limit(1)
            ->select()
            ->all();

        if($data['code'] == ''){
            $this->call(
                '200',
                'Ops',
                '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
                "error",
                "É necessário setar o evento."
            )->back(["count" => 0]);
            return;
        }

        if($result){
            foreach($result as $r){
                $array_r = ['.', '-', '/'];
                $array_c = ['', '', ''];

                $arr = [
                    "atualizacao" => date('Y-m-d H:i:s'),
                    "tpAmb" => intval(1),
                    "razaosocial" => $r->company_name,
                    "cnpj" => str_replace($array_r, $array_c, $r->company_cpf_cnpj),
                    "siglaUF" => $r->company_uf,
                    "schemes" => "PL_009_V4",
                    "versao" => '4.00',
                    "tokenIBPT" => "",
                    "CSC" => "",
                    "CSCid" => "",
                    "proxyConf" => [
                        "proxyIp" => "",
                        "proxyPort" => "",
                        "proxyUser" => "",
                        "proxyPass" => ""
                    ]
                ];

                $configJson = json_encode($arr);
                $pfxcontent = file_get_contents('shared/certificado/'.$r->certificate_file);


                $inicio = $data['inicio'] + 1;
                try{
                    $tools = new Tools($configJson, Certificate::readPfx($pfxcontent, $r->certificate_password));
                    $tools->model('55');

                    $chNFe = $r->doc_chave;
                    $tpEvento = $data['code'];
                    $xJust = $data['descricao'];
                    $nSeqEvento = 1;

                    $response = $tools->sefazManifesta($chNFe,$tpEvento,$xJust,$nSeqEvento);

                    $st = new Standardize($response);
                    $arr = $st->toArray();


                    if($arr['retEvento']['infEvento']['cStat'] == '573'){
                        $_SESSION['retorno_manifestacao'] .= '<p>CHAVE: '.$arr['retEvento']['infEvento']['chNFe'].' - MOTIVO: '.$arr['retEvento']['infEvento']['xMotivo'].'</p>';
                        $this->call(
                            '200',
                            'Ops',
                            '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
                            "info",
                            "Operação sendo processada"
                        )->back(["count" => $inicio, "retorno" => $_SESSION['retorno_manifestacao']]);
                        return;
                    }

                    if($arr['retEvento']['infEvento']['cStat'] == '135'){
                        if($data['code'] == '210210'){
                            $nfe_form['doc_status_manifestacao'] = '1';
                        }elseif($data['code'] == '210200'){
                            $nfe_form['doc_status_manifestacao'] = '2';
                        }elseif($data['code'] == '210220'){
                            $nfe_form['doc_status_manifestacao'] = '3';
                        }elseif($data['code'] == '210240'){
                            $nfe_form['doc_status_manifestacao'] = '4';
                        }
                        $this->db()->update('doc')->where('doc_id')->is($r->doc_id)->set($nfe_form);

                        $_SESSION['retorno_manifestacao'] .= '<p>CHAVE: '.$arr['retEvento']['infEvento']['chNFe'].' - MOTIVO: '.$arr['retEvento']['infEvento']['xMotivo'].'</p>';
                        $this->call(
                            '200',
                            'Ops',
                            '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
                            "info",
                            "Operação sendo processada"
                        )->back(["count" => $inicio, "retorno" => $_SESSION['retorno_manifestacao']]);
                        return;
                    }

                    $_SESSION['retorno_manifestacao'] .= '<p>CHAVE: '.$arr['retEvento']['infEvento']['chNFe'].' - MOTIVO: '.$arr['retEvento']['infEvento']['xMotivo'].'</p>';
                    $this->call(
                        '200',
                        'Ops',
                        '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
                        "info",
                        "Operação sendo processada"
                    )->back(["count" => $inicio, "retorno" => $_SESSION['retorno_manifestacao']]);
                    return;

                }catch (\Exception $e){
                    $_SESSION['retorno_manifestacao'] .= '<p>CHAVE: '.$r->doc_chave.' - MOTIVO: '.$e->getMessage().'</p>';
                    $this->call(
                        '200',
                        'Ops',
                        '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
                        "info",
                        "Operação sendo processada"
                    )->back(["count" => $inicio, "retorno" => $_SESSION['retorno_manifestacao']]);
                    return;
                }
            }
        }
    }

    public function manifesta(array $data)
    {
        $explode_nfs = explode(',', $data['nfs']);

        if($data['inicio'] == '0'){
            unset($_SESSION['retorno_manifestacao']);
        }

        $result = $this->db()->from('company')
            ->join('certificate', function($join){
                $join->on('certificate_id_company', 'company_id');
            })
            ->join('doc', function($join){
                $join->on('doc_id_company', 'company_id');
            })
            ->where('certificate_trash')->is('0')
            ->andWhere('doc_id')->is($explode_nfs[$data['inicio']])
            ->limit(1)
            ->select()
            ->all();

        if($data['code'] == ''){
            $this->call(
                '200',
                'Ops',
                '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
                "error",
                "É necessário setar o evento."
            )->back(["count" => 0]);
            return;
        }

        if($result){
            foreach($result as $r){
                $array_r = ['.', '-', '/'];
                $array_c = ['', '', ''];

                $arr = [
                    "atualizacao" => date('Y-m-d H:i:s'),
                    "tpAmb" => intval(1),
                    "razaosocial" => $r->company_name,
                    "cnpj" => str_replace($array_r, $array_c, $r->company_cpf_cnpj),
                    "siglaUF" => $r->company_uf,
                    "schemes" => "PL_009_V4",
                    "versao" => '4.00',
                    "tokenIBPT" => "",
                    "CSC" => "",
                    "CSCid" => "",
                    "proxyConf" => [
                        "proxyIp" => "",
                        "proxyPort" => "",
                        "proxyUser" => "",
                        "proxyPass" => ""
                    ]
                ];

                $configJson = json_encode($arr);
                $pfxcontent = file_get_contents('shared/certificado/'.$r->certificate_file);


                $inicio = $data['inicio'] + 1;
                try{
                    $tools = new Tools($configJson, Certificate::readPfx($pfxcontent, $r->certificate_password));
                    $tools->model('55');

                    $chNFe = $r->doc_chave;
                    $tpEvento = $data['code'];
                    $xJust = $data['descricao'];
                    $nSeqEvento = 1;

                    $response = $tools->sefazManifesta($chNFe,$tpEvento,$xJust,$nSeqEvento);

                    $st = new Standardize($response);
                    $arr = $st->toArray();


                    if($arr['retEvento']['infEvento']['cStat'] == '573'){
                        $_SESSION['retorno_manifestacao'] .= '<p>CHAVE: '.$arr['retEvento']['infEvento']['chNFe'].' - MOTIVO: '.$arr['retEvento']['infEvento']['xMotivo'].'</p>';
                        $this->call(
                            '200',
                            'Ops',
                            '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
                            "info",
                            "Operação sendo processada"
                        )->back(["count" => $inicio, "retorno" => $_SESSION['retorno_manifestacao']]);
                        return;
                    }

                    if($arr['retEvento']['infEvento']['cStat'] == '135'){
                        if($data['code'] == '210210'){
                            $nfe_form['doc_status_manifestacao'] = '1';
                        }elseif($data['code'] == '210200'){
                            $nfe_form['doc_status_manifestacao'] = '2';
                        }elseif($data['code'] == '210220'){
                            $nfe_form['doc_status_manifestacao'] = '3';
                        }elseif($data['code'] == '210240'){
                            $nfe_form['doc_status_manifestacao'] = '4';
                        }
                        $this->db()->update('doc')->where('doc_id')->is($r->doc_id)->set($nfe_form);

                        $_SESSION['retorno_manifestacao'] .= '<p>CHAVE: '.$arr['retEvento']['infEvento']['chNFe'].' - MOTIVO: '.$arr['retEvento']['infEvento']['xMotivo'].'</p>';
                        $this->call(
                            '200',
                            'Ops',
                            '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
                            "info",
                            "Operação sendo processada"
                        )->back(["count" => $inicio, "retorno" => $_SESSION['retorno_manifestacao']]);
                        return;
                    }

                    $_SESSION['retorno_manifestacao'] .= '<p>CHAVE: '.$arr['retEvento']['infEvento']['chNFe'].' - MOTIVO: '.$arr['retEvento']['infEvento']['xMotivo'].'</p>';
                    $this->call(
                        '200',
                        'Ops',
                        '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
                        "info",
                        "Operação sendo processada"
                    )->back(["count" => $inicio, "retorno" => $_SESSION['retorno_manifestacao']]);
                    return;

                }catch (\Exception $e){
                    $_SESSION['retorno_manifestacao'] .= '<p>CHAVE: '.$r->doc_chave.' - MOTIVO: '.$e->getMessage().'</p>';
                    $this->call(
                        '200',
                        'Ops',
                        '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
                        "info",
                        "Operação sendo processada"
                    )->back(["count" => $inicio, "retorno" => $_SESSION['retorno_manifestacao']]);
                    return;
                }
            }
        }
    }

    public function download(array $data)
    {
        $explode_nfs = explode(',', $data['nfs']);

        if($data['inicio'] == '0'){
            unset($_SESSION['retorno_download']);
        }

        $result = $this->db()->from('company')
            ->join('certificate', function($join){
                $join->on('certificate_id_company', 'company_id');
            })
            ->join('doc', function($join){
                $join->on('doc_id_company', 'company_id');
            })
            ->where('certificate_trash')->is('0')
            ->andWhere('doc_id')->is($explode_nfs[$data['inicio']])
            ->limit(1)
            ->select()
            ->all();

        if($result){
            foreach($result as $r){
                $array_r = ['.', '-', '/'];
                $array_c = ['', '', ''];

                $arr = [
                    "atualizacao" => date('Y-m-d H:i:s'),
                    "tpAmb" => intval(1),
                    "razaosocial" => $r->company_name,
                    "cnpj" => str_replace($array_r, $array_c, $r->company_cpf_cnpj),
                    "siglaUF" => $r->company_uf,
                    "schemes" => "PL_009_V4",
                    "versao" => '4.00',
                    "tokenIBPT" => "",
                    "CSC" => "",
                    "CSCid" => "",
                    "proxyConf" => [
                        "proxyIp" => "",
                        "proxyPort" => "",
                        "proxyUser" => "",
                        "proxyPass" => ""
                    ]
                ];

                $configJson = json_encode($arr);
                $pfxcontent = file_get_contents('shared/certificado/'.$r->certificate_file);


                $inicio = $data['inicio'] + 1;
                try{
                    $tools = new Tools($configJson, Certificate::readPfx($pfxcontent, $r->certificate_password));
                    $tools->model('55');
                    $tools->setEnvironment(1);

                    $chave = $r->doc_chave;

                    $response = $tools->sefazDownload($chave);

                    $ste = new Standardize($response);
                    $arr = $ste->toArray();

                    if($arr['cStat'] == '138'){

                        $zip = $arr['loteDistDFeInt']['docZip'];
                        $xml = gzdecode(base64_decode($zip));

                        $xml_correto = simplexml_load_string($xml);

                        if(isset($xml_correto->NFe)){
                            $form_nfe['doc_mod'] = $xml_correto->NFe->infNFe->ide->mod;
                            $form_nfe['doc_code'] = $xml_correto->NFe->infNFe->ide->cNF;
                            $form_nfe['doc_nat_op'] = $xml_correto->NFe->infNFe->ide->natOp;
                            $form_nfe['doc_serie'] = $xml_correto->NFe->infNFe->ide->serie;
                            $form_nfe['doc_num'] = $xml_correto->NFe->infNFe->ide->nNF;
                            $form_nfe['doc_serie'] = $xml_correto->NFe->infNFe->ide->serie;

                            $explode_data_ini = explode('T', $xml_correto->NFe->infNFe->ide->dhEmi);
                            $form_nfe['doc_date_emi'] = $explode_data_ini['0'].'-'.substr($explode_data_ini['1'],0,8);
                            $explode_data_sai = explode('T', $xml_correto->NFe->infNFe->ide->dhEmi);
                            $form_nfe['doc_date_sai'] = $explode_data_sai['0'].'-'.substr($explode_data_sai['1'],0,8);

                            if($xml_correto->NFe->infNFe->emit->CNPJ){
                                $form_nfe['doc_emit_documento'] = $xml_correto->NFe->infNFe->emit->CNPJ;
                            }else{
                                $form_nfe['doc_emit_documento'] = $xml_correto->NFe->infNFe->emit->CPF;
                            }
                            $form_nfe['doc_emit_nome'] = $xml_correto->NFe->infNFe->emit->xNome;
                            $form_nfe['doc_emit_fantasia'] = $xml_correto->NFe->infNFe->emit->xFant;
                            $form_nfe['doc_emit_ie'] = $xml_correto->NFe->infNFe->emit->IE;

                            if($xml_correto->NFe->infNFe->dest->CNPJ){
                                $form_nfe['doc_dest_documento'] = $xml_correto->NFe->infNFe->dest->CNPJ;
                            }else{
                                $form_nfe['doc_dest_documento'] = $xml_correto->NFe->infNFe->dest->CPF;
                            }
                            $form_nfe['doc_dest_nome'] = $xml_correto->NFe->infNFe->dest->xNome;
                            $form_nfe['doc_dest_ie'] = $xml_correto->NFe->infNFe->dest->IE;

                            $form_nfe['doc_valor'] = $xml_correto->NFe->infNFe->total->ICMSTot->vNF;
                            $form_nfe['doc_valor_trib'] = $xml_correto->NFe->infNFe->total->ICMSTot->vTotTrib;
                            $form_nfe['doc_valor_base_icms'] = $xml_correto->NFe->infNFe->total->ICMSTot->vBC;
                            $form_nfe['doc_valor_icms'] = $xml_correto->NFe->infNFe->total->ICMSTot->vICMS;
                            $form_nfe['doc_valor_frete'] = $xml_correto->NFe->infNFe->total->ICMSTot->vFrete;
                            $form_nfe['doc_valor_seguro'] = $xml_correto->NFe->infNFe->total->ICMSTot->vSeg;
                            $form_nfe['doc_valor_desconto'] = $xml_correto->NFe->infNFe->total->ICMSTot->vDesc;

                            $form_nfe['doc_uf_inicio'] = $xml_correto->NFe->infNFe->emit->enderEmit->UF;
                            $form_nfe['doc_uf_final'] = $xml_correto->NFe->infNFe->dest->enderDest->UF;

                            $form_nfe['doc_status'] = '0';
                            $form_nfe['doc_status_download'] = '1';
                            $form_nfe['doc_chave'] = $xml_correto->protNFe->infProt->chNFe;
                            $form_nfe['doc_file'] = base64_encode($xml);

                            $this->db()->update('doc')->where('doc_id')->is($r->doc_id)->set($form_nfe);

                            $_SESSION['retorno_download'] .= '<p>CHAVE: '.$chave.' - MOTIVO: '.$arr['xMotivo'].'</p>';
                            $this->call(
                                '200',
                                'Ops',
                                '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
                                "info",
                                "Operação sendo processada"
                            )->back(["count" => $inicio, "retorno" => $_SESSION['retorno_download']]);
                            return;
                        }
                    }
                    if($arr['cStat'] == '653'){
                        $_SESSION['retorno_download'] .= '<p>CHAVE: '.$chave.' - MOTIVO: '.$arr['xMotivo'].'</p>';
                        $this->call(
                            '200',
                            'Ops',
                            '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
                            "info",
                            "Operação sendo processada"
                        )->back(["count" => $inicio, "retorno" => $_SESSION['retorno_download']]);
                        return;
                    }



                    $_SESSION['retorno_manifestacao'] .= '<p>CHAVE: '.$arr['retEvento']['infEvento']['chNFe'].' - MOTIVO: '.$arr['retEvento']['infEvento']['xMotivo'].'</p>';
                    $this->call(
                        '200',
                        'Ops',
                        '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
                        "info",
                        "Operação sendo processada"
                    )->back(["count" => $inicio, "retorno" => $_SESSION['retorno_download']]);
                    return;

                }catch (\Exception $e){
                    $_SESSION['retorno_download'] .= '<p>CHAVE: '.$r->doc_chave.' - MOTIVO: '.$e->getMessage().'</p>';
                    $this->call(
                        '200',
                        'Ops',
                        '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
                        "info",
                        "Operação sendo processadaa"
                    )->back(["count" => $inicio, "retorno" => $_SESSION['retorno_download']]);
                    return;
                }
            }
        }
    }

    public function processDoc(array $data)
    {
        $result = $this->db()->from('zip')
            ->where('zip_id_company')->is($data['id'])
            ->andWhere('zip_status')->is(0)
            ->limit($data['final'])
            ->offset($data['inicio'])
            ->select()
            ->all();

        if($result){
            foreach($result as $r){

                $ide[] = $r->zip_id;

                $xml_correto = simplexml_load_string(base64_decode($r->zip_doc));

                if(isset($xml_correto->xEvento)){
                    $resultTypeEvent = $this->db()->from('tipo_evento')
                        ->where('tipo_evento_code')->is($xml_correto->tpEvento)
                        ->limit(1)
                        ->select()
                        ->all();
                    if(!$resultTypeEvent){
                        $form_tipo_evento['tipo_evento_code'] = $xml_correto->tpEvento;
                        $form_tipo_evento['tipo_evento_descricao'] = $xml_correto->xEvento;
                        $this->db()->insert($form_tipo_evento)->into('tipo_evento');
                    }

                    $form_evento['eventos_id_company'] = $data['id'];
                    $form_evento['eventos_chave'] = $xml_correto->chNFe;
                    $form_evento['eventos_code_evento'] = $xml_correto->tpEvento;
                    $form_evento['eventos_desc_evento'] = $xml_correto->xEvento;
                    $explode_data = explode('T', $xml_correto->dhEvento);
                    $form_evento['eventos_data'] = $explode_data['0'].'-'.substr($explode_data['1'],0,8);
                    $form_evento['eventos_prot'] = $xml_correto->nProt;
                    $form_evento['eventos_file'] = $r->zip_doc;

                    $resultEventOne = $this->db()->from('eventos')
                        ->where('eventos_id_company')->is($data['id'])
                        ->andWhere('eventos_prot')->is($xml_correto->nProt)
                        ->limit(1)
                        ->select()
                        ->all();

                    if(!$resultEventOne){
                        $this->db()->insert($form_evento)->into('eventos');
                    }
                }

                if(isset($xml_correto->evento)){
                    $resultTypeEvent = $this->db()->from('tipo_evento')
                        ->where('tipo_evento_code')->is($xml_correto->evento->infEvento->tpEvento)
                        ->limit(1)
                        ->select()
                        ->all();
                    if(!$resultTypeEvent){
                        $form_tipo_evento['tipo_evento_code'] = $xml_correto->evento->infEvento->tpEvento;
                        $form_tipo_evento['tipo_evento_descricao'] = $xml_correto->evento->infEvento->detEvento->descEvento;
                        $this->db()->insert($form_tipo_evento)->into('tipo_evento');
                    }

                    $form_evento['eventos_id_company'] = $data['id'];
                    $form_evento['eventos_chave'] = $xml_correto->evento->infEvento->chNFe;
                    $form_evento['eventos_code_evento'] = $xml_correto->evento->infEvento->tpEvento;
                    $form_evento['eventos_desc_evento'] = $xml_correto->evento->infEvento->detEvento->descEvento;
                    $explode_data = explode('T', $xml_correto->evento->infEvento->dhEvento);
                    $form_evento['eventos_data'] = $explode_data['0'].'-'.substr($explode_data['1'],0,8);
                    $form_evento['eventos_prot'] = $xml_correto->evento->infEvento->detEvento->nProt;
                    $form_evento['eventos_file'] = $r->zip_doc;

                    $resultEventTwo = $this->db()->from('eventos')
                        ->where('eventos_id_company')->is($data['id'])
                        ->andWhere('eventos_prot')->is($xml_correto->evento->infEvento->detEvento->nProt)
                        ->limit(1)
                        ->select()
                        ->all();

                    if(!$resultEventTwo){
                        $this->db()->insert($form_evento)->into('eventos');
                    }
                }


                if(isset($xml_correto->NFe)){
                    $form_nfe['doc_id_company'] = $data['id'];
                    $form_nfe['doc_mod'] = '55';
                    $form_nfe['doc_code'] = $xml_correto->NFe->infNFe->ide->cNF;
                    $form_nfe['doc_nat_op'] = $xml_correto->NFe->infNFe->ide->natOp;
                    $form_nfe['doc_serie'] = $xml_correto->NFe->infNFe->ide->serie;
                    $form_nfe['doc_num'] = $xml_correto->NFe->infNFe->ide->nNF;
                    $form_nfe['doc_serie'] = $xml_correto->NFe->infNFe->ide->serie;

                    $explode_data_ini = explode('T', $xml_correto->NFe->infNFe->ide->dhEmi);
                    $form_nfe['doc_date_emi'] = $explode_data_ini['0'].'-'.substr($explode_data_ini['1'],0,8);
                    if(isset($xml_correto->NFe->infNFe->ide->dhSaiEnt)){
                        $explode_data_sai = explode('T', $xml_correto->NFe->infNFe->ide->dhSaiEnt);
                        $form_nfe['doc_date_sai'] = $explode_data_sai['0'].'-'.substr($explode_data_sai['1'],0,8);
                    }else{
                        $form_nfe['doc_date_sai'] = $explode_data_ini['0'].'-'.substr($explode_data_ini['1'],0,8);
                    }


                    if($xml_correto->NFe->infNFe->emit->CNPJ){
                        $form_nfe['doc_emit_documento'] = $xml_correto->NFe->infNFe->emit->CNPJ;
                    }else{
                        $form_nfe['doc_emit_documento'] = $xml_correto->NFe->infNFe->emit->CPF;
                    }
                    $form_nfe['doc_emit_nome'] = $xml_correto->NFe->infNFe->emit->xNome;
                    $form_nfe['doc_emit_fantasia'] = $xml_correto->NFe->infNFe->emit->xFant;
                    $form_nfe['doc_emit_ie'] = $xml_correto->NFe->infNFe->emit->IE;

                    if($xml_correto->NFe->infNFe->dest->CNPJ){
                        $form_nfe['doc_dest_documento'] = $xml_correto->NFe->infNFe->dest->CNPJ;
                    }else{
                        $form_nfe['doc_dest_documento'] = $xml_correto->NFe->infNFe->dest->CPF;
                    }
                    $form_nfe['doc_dest_nome'] = $xml_correto->NFe->infNFe->dest->xNome;
                    $form_nfe['doc_dest_ie'] = $xml_correto->NFe->infNFe->dest->IE;

                    $form_nfe['doc_valor'] = $xml_correto->NFe->infNFe->total->ICMSTot->vNF;
                    $form_nfe['doc_valor_trib'] = $xml_correto->NFe->infNFe->total->ICMSTot->vTotTrib;
                    $form_nfe['doc_valor_base_icms'] = $xml_correto->NFe->infNFe->total->ICMSTot->vBC;
                    $form_nfe['doc_valor_icms'] = $xml_correto->NFe->infNFe->total->ICMSTot->vICMS;
                    $form_nfe['doc_valor_frete'] = $xml_correto->NFe->infNFe->total->ICMSTot->vFrete;
                    $form_nfe['doc_valor_seguro'] = $xml_correto->NFe->infNFe->total->ICMSTot->vSeg;
                    $form_nfe['doc_valor_desconto'] = $xml_correto->NFe->infNFe->total->ICMSTot->vDesc;

                    $form_nfe['doc_uf_inicio'] = $xml_correto->NFe->infNFe->emit->enderEmit->UF;
                    $form_nfe['doc_uf_final'] = $xml_correto->NFe->infNFe->dest->enderDest->UF;

                    $form_nfe['doc_status'] = '0';
                    $form_nfe['doc_status_download'] = '1';
                    $form_nfe['doc_status_manifestacao'] = '1';
                    $form_nfe['doc_chave'] = $xml_correto->protNFe->infProt->chNFe;
                    $form_nfe['doc_file'] = $r->zip_doc;

                    $resultDoc = $this->db()->from('doc')
                        ->where('doc_id_company')->is($data['id'])
                        ->andWhere('doc_chave')->is($form_nfe['doc_chave'])
                        ->limit(1)
                        ->select()
                        ->all();


                    if(!$resultDoc){
                        $this->db()->insert($form_nfe)->into('doc');
                    }else{
                        $this->db()->update('doc')->where('doc_chave')->is($form_nfe['doc_chave'])->set($form_nfe);
                    }
                }elseif(isset($xml_correto->vNF)){
                    $form_nfe['doc_id_company'] = $data['id'];
                    $form_nfe['doc_status'] = '0';
                    $form_nfe['doc_mod'] = '55';
                    $form_nfe['doc_status_download'] = '0';
                    $form_nfe['doc_status_manifestacao'] = '0';
                    $form_nfe['doc_chave'] = $xml_correto->chNFe;

                    if($xml_correto->CNPJ){
                        $form_nfe['doc_dest_documento'] = $xml_correto->CNPJ;
                    }else{
                        $form_nfe['doc_dest_documento'] = $xml_correto->CPF;
                    }
                    $form_nfe['doc_dest_nome'] = $xml_correto->xNome;
                    $form_nfe['doc_dest_ie'] = $xml_correto->IE;

                    $explode_data_ini = explode('T', $xml_correto->dhEmi);
                    $form_nfe['doc_date_emi'] = $explode_data_ini['0'].'-'.substr($explode_data_ini['1'],0,8);

                    $form_nfe['doc_valor'] = $xml_correto->vNF;

                    $resultDocResumo = $this->db()->from('doc')
                        ->where('doc_id_company')->is($data['id'])
                        ->andWhere('doc_chave')->is($form_nfe['doc_chave'])
                        ->limit(1)
                        ->select()
                        ->all();


                    if(!$resultDocResumo){
                        $this->db()->insert($form_nfe)->into('doc');
                    }
                }
                unset($form_nfe);
                $this->conn()->disconnect();
            }
            $form_doc['zip_status'] = '1';
			$this->db()->update('zip')->where('zip_id')->in($ide)->set($form_doc);
            $this->call(
                '200',
                'Ops',
                '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
                "info",
                "Ainda aguarde"
            )->back(["count" => $inicio]);
            return;
        }

        $resultManifesta = $this->db()->from('doc')
            ->where('doc_id_company')->is($data['id'])
            ->andWhere('doc_status_manifestacao')->is(0)
            ->select()
            ->all();
        $returnManifesta = '';
        $retornoInfo = 'nada';
        if($resultManifesta){
            $retornoInfo = 'tudo';
            foreach($resultManifesta as $r){
                $returnManifesta .= $r->doc_id.',';
            }
        }
        $this->call(
            '200',
            'Parabéns',
            '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
            "ok",
            "Operação realizada com sucesso."
        )->back(["count" => 0, "ids" => substr($returnManifesta,0,-1), "tipo" => $retornoInfo]);
        return;
    }

    /**
     * @param array $data
     * @return void
     */
    public function search(array $data): void{
        $jSONsEARCH['type'] = 'ok';
        $jSONsEARCH['info'] = $data;
        $_SESSION[$data['action']] = $jSONsEARCH;
        echo json_encode($jSONsEARCH);
        return;
    }

    /**
     * @param array $data
     * @return void
     */
    public function searchRead(array $data): void{
        unset($_SESSION[$data['action']]['info']['search']);
        echo json_encode($_SESSION[$data['action']]);
        return;
    }

    /**
     * @param array $data
     * @return void
     */
    public function select(array $data): void
    {
        $start = ($data['pageNo'] * $data['size']) - $data['size'];
        if (empty($data['size'])){
            $max = '300';
        }else{
            $max = $data['size'];
        }

        $forms = $_SESSION[$data['action']]['info'];


        $queryPaginator = $this->db()->from('doc')
            ->join('company', function($join){
                $join->on('company_id', 'doc_id_company');
            })->where('doc_mod')->is(55)->andWhere('company_id_user')->is(ID_LOG);

        $query = $this->db()->from('doc')
            ->join('company', function($join){
                $join->on('company_id', 'doc_id_company');
            })->where('doc_mod')->is(55)->andWhere('company_id_user')->is(ID_LOG);




        if($forms['id_empresa'] != ''){
            $queryPaginator = $queryPaginator->andWhere('doc_id_company')->is($forms['id_empresa']);
            $query = $query->andWhere('doc_id_company')->is($forms['id_empresa']);
        }
        if($forms['data_inicial'] != '' && $forms['data_final'] != ''){
            $queryPaginator = $queryPaginator->andWhere('doc_date_emi')->between($forms['data_inicial'],$forms['data_final']);
            $query = $query->andWhere('doc_date_emi')->between($forms['data_inicial'],$forms['data_final']);
        }
        if($forms['emitente'] != ''){
            $queryPaginator = $queryPaginator->andWhere('doc_emit_nome')->like('%'.$forms['emitente'].'%');
            $query = $query->andWhere('doc_emit_nome')->like('%'.$forms['emitente'].'%');
        }
        if($forms['chave'] != ''){
            $queryPaginator = $queryPaginator->andWhere('doc_chave')->is($forms['chave']);
            $query = $query->andWhere('doc_chave')->is($forms['chave']);
        }
        if(empty($data['sort'])){
            $data['sort'] = 'doc_id';
        }
        if(empty($data['sort_dir'])){
            $data['sort_dir'] = 'desc';
        }

        $resPaginator = $queryPaginator->select()->all();
        $result = $query->orderBy($data['sort'], $data['sort_dir'])
            ->limit($data['size'])
            ->offset($start)
            ->select()
            ->all();


        if($result){
            $page = ceil(count($resPaginator) / $max);
            $rows['last_page'] = $page;
            $rows['quantify'] = count($resPaginator);
            foreach($result as $r){
                $r->doc_date_emi = format_datetime_br($r->doc_date_emi);
                if($r->doc_date_sai != ''){
                    $r->doc_date_sai = format_datetime_br($r->doc_date_sai);
                }

                $r->doc_valor = 'R$ '.format_money($r->doc_valor);
                $r->doc_valor_trib = 'R$ '.format_money($r->doc_valor_trib);
                $r->doc_valor_base_icms = 'R$ '.format_money($r->doc_valor_base_icms);
                $r->doc_valor_icms = 'R$ '.format_money($r->doc_valor_icms);
                $r->doc_valor_frete = 'R$ '.format_money($r->doc_valor_frete);
                $r->doc_valor_seguro = 'R$ '.format_money($r->doc_valor_seguro);
                $r->doc_valor_desconto = 'R$ '.format_money($r->doc_valor_desconto);
                if($r->doc_status == '0'){
                    $r->doc_status = 'NÃO';
                }else{
                    $r->doc_status = 'SIM';
                }

                if($r->doc_status_download == '0'){
                    $r->doc_status_download = 'NÃO';
                }else{
                    $r->doc_status_download = 'SIM';
                }

                if($r->doc_status_manifestacao == '0'){
                    $r->doc_status_manifestacao = 'NÃO';
                }elseif($r->doc_status_manifestacao == '1'){
                    $r->doc_status_manifestacao = 'CIÊNCIA OPERAÇÃO';
                }elseif($r->doc_status_manifestacao == '2'){
                    $r->doc_status_manifestacao = 'CONFIRMAÇÃO OPERAÇÃO';
                }elseif($r->doc_status_manifestacao == '3'){
                    $r->doc_status_manifestacao = 'DESCONHECIMENTO OPERAÇÃO';
                }elseif($r->doc_status_manifestacao == '4'){
                    $r->doc_status_manifestacao = 'NÃO REALIZADA';
                }
                $rows['data'][] = $r;
            }

            echo json_encode($rows);
            return;
        }else{
            $rows['last_page'] = '0';
            $rows['quantify'] = '0';
            echo json_encode($rows);
            return;
        }
    }

    public function loadEvents(array $data)
    {
        if(in_array('', $data)){
            $this->call(
                '200',
                'Ops',
                '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
                "error",
                "Existem campos em branco"
            )->back(["count" => 0]);
            return;
        }

        $result = $this->db()->from('eventos')
            ->join('doc', function($join){
                $join->on('doc_chave', 'eventos_chave');
            })
            ->join('company', function($join){
                $join->on('company_id', 'doc_id_company');
            })
            ->where('doc_id')->is($data['id_doc'])
            ->andWhere('company_id_user')->is(ID_LOG)
            ->select()
            ->all();

        if($result){
            $table = '<table class="table table-hover table-nomargin table-bordered">';
                $table .= '<thead>
                    <tr>
                        <th colspan="2"></th>
                        <th>Tipo</th>
                        <th>Evento</th>
                        <th>Data Hora</th>
                        <th>Protocolo</th>
                    </tr>
                </thead>
                <tbody>';

                foreach($result as $r){
                    $table .= '<tr>
                        <td><a class="btn btn-blue" title="Ver XML" onclick="load_eventos_xml('.$r->eventos_id.');"><i class="fa fa-search"></i></a></td>
                        <td><a class="btn btn-brown" title="Download XML" onclick="download_eventos_xml('.$r->eventos_id.');"><i class="fa fa-download"></i></a></td>
                        <td>'.$r->eventos_desc_evento.'</td>
                        <td>'.$r->eventos_code_evento.'</td>
                        <td>'.format_datetime_br($r->eventos_data).'</td>
                        <td>'.$r->eventos_prot.'</td>
                    </tr>';
                }
            $table .= '</tbody></table>';

            $this->call(
                '200',
                'Parabéns',
                '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
                "ok",
                "Operação realizada com sucesso."
            )->back(["retorno" => $table]);
            return;
        }
        $this->call(
            '200',
            'Ops',
            '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
            "error",
            "Sem informações"
        )->back(["count" => 0]);
        return;
    }

    public function loadEventsXML(array $data)
    {
        if(in_array('', $data)){
            $this->call(
                '200',
                'Ops',
                '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
                "error",
                "Existem campos em branco"
            )->back(["count" => 0]);
            return;
        }

        $result = $this->db()->from('eventos')
            ->where('eventos_id')->is($data['id_doc'])
            ->select()
            ->all();

        if($result){
            foreach($result as $r){
                $string = base64_decode($r->eventos_file);

                $var = '<pre>'. htmlentities($string). '</pre>';
            }
            $this->call(
                '200',
                'Parabéns',
                '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
                "ok",
                "Operação realizada com sucesso."
            )->back(["retorno" => $var]);
            return;
        }
        $this->call(
            '200',
            'Ops',
            '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
            "error",
            "Sem informações"
        )->back(["count" => 0]);
        return;
    }

    public function downloadEventsXML(array $data)
    {
        if(in_array('', $data)){
            $this->call(
                '200',
                'Ops',
                '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
                "error",
                "Existem campos em branco"
            )->back(["count" => 0]);
            return;
        }

        $result = $this->db()->from('eventos')
            ->where('eventos_id')->is($data['id_doc'])
            ->select()
            ->all();

        if($result){
            foreach($result as $r){
                $nameFile = $r->eventos_chave.'-'.rand(100000,999999).'-event.xml';

                $decoded_file_data = base64_decode($r->eventos_file);

                file_put_contents('shared/temp/'.$nameFile, $decoded_file_data);
            }
            $this->call(
                '200',
                'Parabéns',
                '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
                "ok",
                "Operação realizada com sucesso."
            )->back(["file" => $nameFile]);
            return;
        }
        $this->call(
            '200',
            'Ops',
            '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
            "error",
            "Sem informações"
        )->back(["count" => 0]);
        return;
    }

    public function downloadZip(array $data)
    {
        if(in_array('', $data)){
            $this->call(
                '200',
                'Ops',
                '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
                "error",
                "Existem campos em branco"
            )->back(["count" => 0]);
            return;
        }

        $explode_file = explode(',', $data['id_doc']);


        $resultDoc = $this->db()->from('doc')
            ->join('company', function($join){
                $join->on('company_id', 'doc_id_company');
            })
            ->where('company_id_user')->is(ID_LOG)
            ->andWhere('doc_id')->in($explode_file)
            ->andWhere('doc_status_download')->is(1)
            ->select()
            ->all();

        if($resultDoc){
            $randFolder = rand(100000,999999);
            if(mkdir('shared/temp/'.$randFolder.'/', 0777, true)){
                $zip = new \ZipArchive();
                $arqZip = 'shared/zipex/'.$randFolder.'.zip';
                $zip->open($arqZip, \ZipArchive::CREATE);
                foreach($resultDoc as $r){
                    $nameFile = $r->doc_chave.'-nfe.xml';
                    $decoded_file_data = base64_decode($r->doc_file);
                    file_put_contents('shared/temp/'.$randFolder.'/'.$nameFile, $decoded_file_data);

                    $zip->addFile('shared/temp/'.$randFolder.'/'.$nameFile, $nameFile);
                }
                $zip->close();


                foreach($resultDoc as $r){
                    $nameFile = $r->doc_chave.'-nfe.xml';
                    unlink('shared/temp/'.$randFolder.'/'.$nameFile);
                }

                rmdir('shared/temp/'.$randFolder.'/');
                $linkZip = '<a href="../'.$arqZip.'" class="btn btn-brown" download>BAIXAR OS ARQUIVOS</a>';

                $this->call(
                    '200',
                    'Parabéns',
                    '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
                    "ok",
                    "Documento processado com sucesso"
                )->back(["button" => $linkZip]);
                return;
            }

            $this->call(
                '200',
                'Ops',
                '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
                "error",
                "Sem informações"
            )->back(["count" => 0]);
            return;
        }

        $this->call(
            '200',
            'Ops',
            '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
            "error",
            "Não existem arquivos"
        )->back(["count" => 0]);
        return;
    }

    public function danfe(array $data)
    {
        if(in_array('', $data)){
            $this->call(
                '200',
                'Ops',
                '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
                "error",
                "Existem campos em branco"
            )->back(["count" => 0]);
            return;
        }

        $explode_file = explode(',', $data['id_doc']);




        $resultDoc = $this->db()->from('doc')
            ->join('company', function($join){
                $join->on('company_id', 'doc_id_company');
            })
            ->where('company_id_user')->is(ID_LOG)
            ->andWhere('doc_id')->in($explode_file)
            ->andWhere('doc_status_download')->is(1)
            ->select()
            ->all();

        if($resultDoc){
            $randFolder = rand(100000,999999);
            if(mkdir('shared/temp/'.$randFolder.'/', 0777, true)){
                $zip = new \ZipArchive();
                $arqZip = 'shared/zipex/'.$randFolder.'.zip';
                $zip->open($arqZip, \ZipArchive::CREATE);
                foreach($resultDoc as $r){
                    $nameFile = $r->doc_chave.'-nfe.xml';
                    $nameFilePDF = $r->doc_chave.'-nfe.pdf';
                    $decoded_file_data = base64_decode($r->doc_file);
                    file_put_contents('shared/temp/'.$randFolder.'/'.$nameFile, $decoded_file_data);

                    $xml = file_get_contents('shared/temp/'.$randFolder.'/'.$nameFile);
                    try {
                        $danfe = new Danfe($xml);
                        $danfe->debugMode(false);
                        $danfe->creditsIntegratorFooter('Futura');
                        $pdf = $danfe->render('');

                        file_put_contents('shared/temp/'.$randFolder.'/'.$nameFilePDF, $pdf);
                        $zip->addFile('shared/temp/'.$randFolder.'/'.$nameFilePDF, $nameFilePDF);
                    }catch (InvalidArgumentException $e) {
                        echo "Ocorreu um erro durante o processamento :" . $e->getMessage();
                    }


                }
                $zip->close();


                foreach($resultDoc as $r){
                    $nameFile = $r->doc_chave.'-nfe.xml';
                    $nameFilePDF = $r->doc_chave.'-nfe.pdf';
                    unlink('shared/temp/'.$randFolder.'/'.$nameFile);
                    unlink('shared/temp/'.$randFolder.'/'.$nameFilePDF);
                }

                rmdir('shared/temp/'.$randFolder.'/');
                $linkZip = '<a href="../'.$arqZip.'" class="btn btn-brown" download>BAIXAR OS ARQUIVOS</a>';

                $this->call(
                    '200',
                    'Parabéns',
                    '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
                    "ok",
                    "Documento processado com sucesso"
                )->back(["button" => $linkZip]);
                return;
            }

            $this->call(
                '200',
                'Ops',
                '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
                "error",
                "Sem informações"
            )->back(["count" => 0]);
            return;
        }

        $this->call(
            '200',
            'Ops',
            '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
            "error",
            "Não existem arquivos"
        )->back(["count" => 0]);
        return;
    }
}
