<?php

namespace Source\Models;
use Source\Conn\DataLayer;

class KeyNFCe extends DataLayer
{
    public function insert(array $forms)
    {
        if(in_array('', $forms)){
            $this->call(
                '200',
                'Ops',
                '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
                "error",
                "Email e Razão Social precisam ser preenchidos"
            )->back(["count" => 0]);
            return;
        }

        $explodeKey = explode(PHP_EOL, $forms['texto']);

        if($_SESSION[SESSION]->user_nivel == '1'){
            if(count($explodeKey) > get_balance(ID_LOG)){
                $this->call(
                    '200',
                    'Ops',
                    '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
                    "error",
                    "Você não tem saldo para solicitar essa quantidade de chaves"
                )->back(["count" => 0]);
                return;
            }
        }

        for($x=0;$x<count($explodeKey);$x++){

            if($x == '0'){
                $createBatch['lote_id_company']     = $forms['xml_id_company'];
                $createBatch['lote_date_hour']      = date('Y-m-d H:i:s');
                $createBatch['lote_status']         = '0';
                $createBatch['lote_trash']          = '0';
                $createBatch['lote_id_user']        = ID_LOG;
                $createBatch['lote_type']           = $forms['lote_type'];
                $this->db()->insert($createBatch)->into('lote');


                $idLote = $this->lastRegistro('lote', 'lote_id', 'lote_id');
            }

            $chave = trim($explodeKey[$x]);

            $create['xml_chave']            = $chave;
            $create['xml_status']           = '0';
            $create['xml_trash']            = '0';
            $create['xml_type']             = $forms['lote_type'];
            $create['xml_id_company']       = $forms['xml_id_company'];
            $create['xml_id_lote']          = $idLote;
            $create['xml_id_user']          = ID_LOG;

            if($chave != ''){
                $this->db()->insert($create)->into('xml');
            }
        }

        $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]);
        return;
    }

    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('lote')->join('company', function($join){
            $join->on('lote_id_company', 'company_id');
        })->where('lote_trash')->is(0)->andWhere('lote_id_user')->is(ID_LOG)->andWhere('lote_type')->is(65);

        $query = $this->db()->from('lote')->join('company', function($join){
            $join->on('lote_id_company', 'company_id');
        })->where('lote_trash')->is(0)->andWhere('lote_id_user')->is(ID_LOG)->andWhere('lote_type')->is(65);




        if($forms['data_inicial'] != '' && $forms['data_final'] != ''){
            $queryPaginator = $queryPaginator->andWhere('lote_date_hour')->between($forms['data_inicial'], $forms['data_final']);
            $query = $query->andWhere('lote_date_hour')->between($forms['data_inicial'], $forms['data_final']);
        }
        if($forms['status'] != ''){
            $queryPaginator = $queryPaginator->andWhere('lote_status')->is($forms['status']);
            $query = $query->andWhere('lote_status')->is($forms['status']);
        }

        $resPaginator = $queryPaginator->select()->all();
        $result = $query->orderBy('lote_id')
            ->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){
                if($r->lote_status == '0'){
                    $r->lote_status = 'PENDENTE';
                    $temp = '';
                    $dateEnd = '';
                }elseif($r->lote_status == '1'){
                    $r->lote_status = 'BAIXADO';

                    $firstDate  = new \DateTime($r->lote_date_init_download);
                    $secondDate = new \DateTime($r->lote_date_hour_end);
                    $intVl      = $firstDate->diff($secondDate);

                    $temp = (($intVl->d * 24) + $intVl->h).':'.$intVl->i;

                    $dateEnd = format_datetime_br($r->lote_date_hour_end);
                }else{
                    $r->lote_status = 'CANCELADO';
                    $temp = '';
                    $dateEnd = '';
                }
                $r->lote_temp = $temp;
                $r->lote_date_hour_end = $dateEnd;
                $r->lote_date_hour = format_datetime_br($r->lote_date_hour);
                $r->lote_date_init_download = format_datetime_br($r->lote_date_init_download);
                $rows['data'][] = $r;
            }

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

    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;
    }

    public function selectKey(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('xml')->where('xml_trash')->is(0)->andWhere('xml_id_user')->is(ID_LOG)->andWhere('xml_id_lote')->is($data['id_lote']);

        $query = $this->db()->from('xml')->where('xml_trash')->is(0)->andWhere('xml_id_user')->is(ID_LOG)->andWhere('xml_id_lote')->is($data['id_lote']);




        if($forms['chave'] != ''){
            $queryPaginator = $queryPaginator->andWhere('xml_chave')->is($forms['chave']);
            $query = $query->andWhere('xml_chave')->is($forms['chave']);
        }
        if($forms['status'] != ''){
            $queryPaginator = $queryPaginator->andWhere('xml_status')->is($forms['status']);
            $query = $query->andWhere('xml_status')->is($forms['status']);
        }

        $resPaginator = $queryPaginator->select()->all();
        $result = $query->orderBy('xml_id')
            ->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){
                if($r->xml_status == '0'){
                    $r->xml_status = 'PENDENTE';
                }elseif($r->xml_status == '1'){
                    $r->xml_status = 'DOWNLOAD';
                }else{
                    $r->lote_status = 'ERRO';
                }
                $rows['data'][] = $r;
            }

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

    public function zip(array $forms)
    {
        $explodeIdLote = explode(',', $forms['id']);

        $result = $this->db()->from('xml')
            ->join('lote', function($join){
                $join->on('lote_id', 'xml_id_lote');
            })
            ->where('xml_status')->in([1])
            ->andWhere('xml_id')->in($explodeIdLote)
            ->andWhere('xml_id_user')->is(ID_LOG)
            ->select()
            ->all();

        $zip = new \ZipArchive();

        $count = '0';
        if($result){
            $name_zip = rand(1000000,9999999);
            $arqZip = 'shared/temp/'.$name_zip.'.zip';
            $zip->open($arqZip, \ZipArchive::CREATE);
            foreach($result as $r){
                $Filename = "shared/xml/lote$r->xml_id_lote/{$r->xml_arquivo}";
                $zip->addFile($Filename, $r->xml_arquivo);
            }
            $this->call(
                '200',
                'Parabéns',
                '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
                "ok",
                "Operação realizada com sucesso."
            )->back(["nome_arquivo" => $name_zip.'.zip']);
            return;
        }

        $this->call(
            '200',
            'Ops',
            '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
            "error",
            "Houve um problema no processamento da solicitação."
        )->back(["count" => 0]);
        return;
    }
}