<?php

namespace Source\Models;

use Source\Conn\DataLayer;

class Consult 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_consulta_date_hour']      = date('Y-m-d H:i:s');
                $createBatch['lote_consulta_status']         = '0';
                $createBatch['lote_consulta_trash']          = '0';
                $createBatch['lote_consulta_id_user']        = ID_LOG;
                $this->db()->insert($createBatch)->into('lote_consulta');


                $idLote = $this->lastRegistro('lote_consulta', 'lote_consulta_id', 'lote_consulta_id');
            }

            $explodeKeyDados = explode(';', trim($explodeKey[$x]));
            $create['item_consulta_id_user'] = ID_LOG;
            $create['item_consulta_status']  = '0';
            $create['item_consulta_id_lote'] = $idLote;
            $create['item_consulta_cnpj']    = $explodeKeyDados['0'];
            $create['item_consulta_ie']    = $explodeKeyDados['1'];
            $create['item_consulta_uf']    = $explodeKeyDados['2'];
            $create['item_consulta_trash'] = '0';
            if(!in_array('', $create)){
                $this->db()->insert($create)->into('item_consulta');
            }
        }

        $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_consulta')->where('lote_consulta_trash')->is(0)->andWhere('lote_consulta_id_user')->is(ID_LOG);

        $query = $this->db()->from('lote_consulta')->where('lote_consulta_trash')->is(0)->andWhere('lote_consulta_id_user')->is(ID_LOG);




        if($forms['data_inicial'] != '' && $forms['data_final'] != ''){
            $queryPaginator = $queryPaginator->andWhere('lote_consulta_date_hour')->between(str_replace('T', ' ', $forms['data_inicial']), str_replace('T', ' ', $forms['data_final']));
            $query = $query->andWhere('lote_consulta_date_hour')->between(str_replace('T', ' ', $forms['data_inicial']), str_replace('T', ' ', $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_consulta_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_consulta_status == '0'){
                    $r->lote_consulta_status = 'PENDENTE';
                    $temp = '';
                    $dateEnd = '';
                }elseif($r->lote_consulta_status == '1'){
                    $r->lote_status = 'BAIXADO';

                    $firstDate  = new \DateTime($r->lote_consulta_date_hour);
                    $secondDate = new \DateTime($r->lote_consulta_date_hour_end);
                    $intVl      = $firstDate->diff($secondDate);

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

                    $dateEnd = format_datetime_br($r->lote_consulta_date_hour_end);
                }else{
                    $r->lote_consulta_status = 'CANCELADO';
                    $temp = '';
                    $dateEnd = '';
                }
                $r->lote_temp = $temp;
                $r->lote_consulta_date_hour_end = $dateEnd;
                $r->lote_consulta_date_hour = format_datetime_br($r->lote_consulta_date_hour);
                $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('item_consulta')->where('item_consulta_trash')->is(0)->andWhere('item_consulta_id_user')->is(ID_LOG)->andWhere('item_consulta_id_lote')->is($data['id_lote']);

        $query = $this->db()->from('item_consulta')->where('item_consulta_trash')->is(0)->andWhere('item_consulta_id_user')->is(ID_LOG)->andWhere('item_consulta_id_lote')->is($data['id_lote']);




        if($forms['cnpj'] != ''){
            $queryPaginator = $queryPaginator->andWhere('item_consulta_cnpj')->like('%'.$forms['cnpj'].'%');
            $query = $query->andWhere('item_consulta_cnpj')->like('%'.$forms['cnpj'].'%');
        }
        if($forms['ie'] != ''){
            $queryPaginator = $queryPaginator->andWhere('item_consulta_ie')->like('%'.$forms['ie'].'%');
            $query = $query->andWhere('item_consulta_ie')->like('%'.$forms['ie'].'%');
        }
        if($forms['status'] != ''){
            $queryPaginator = $queryPaginator->andWhere('item_consulta_status')->is($forms['status']);
            $query = $query->andWhere('item_consulta_status')->is($forms['status']);
        }

        $resPaginator = $queryPaginator->select()->all();
        $result = $query->orderBy('item_consulta_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->item_consulta_status == '0'){
                    $r->item_consulta_status = 'PENDENTE';
                }elseif($r->item_consulta_status == '1'){
                    $r->item_consulta_status = 'BAIXADO';
                }elseif($r->item_consulta_status == '2'){
                    $r->item_consulta_status = 'CANCELADO';
                }else{
                    $r->item_consulta_status = 'ERRO';
                }


                $rows['data'][] = $r;
            }

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