<?php

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

/**
 *
 */
class Company extends DataLayer
{
    /**
     * @param array $forms
     * @return void
     */
    public function insert(array $forms)
    {
        if($forms['company_email'] == '' || $forms['company_name'] == ''){
            $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;
        }
        $forms['company_trash'] = '0';
        $forms['company_id_user'] = ID_LOG;

        $forms['company_nsu_nfe_primary'] = '0';
        $forms['company_nsu_nfe_secundary'] = '0';
        $forms['company_nsu_nfse_primary'] = '0';

        $forms['company_ult_date_nfe_primary'] = '2010-01-01 00:00:00';
        $forms['company_ult_date_nfe_secundary'] = '2010-01-01 00:00:00';
        $forms['company_ult_date_nfse_primary'] = '2010-01-01 00:00:00';

        $forms['company_ciencia_operacao'] = '0';
        $forms['company_busca_automatica'] = '0';
        $forms['company_intervalo_busca'] = '60';


        if($this->db()->insert($forms)->into('company')){
            $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;
        }

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

    /**
     * @param array $forms
     * @return void
     */
    public function edit(array $forms)
    {
        $id = $forms['id'];
        unset($forms['id']);

        $result = $this->db()->update('company')->where('company_id')->is($id)->andWhere('company_id_user')->is(ID_LOG)->set($forms);

        if($result == '0' || $result == '1'){
            $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;
        }

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

    /**
     * @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('company')->where('company_trash')->is(0)->andWhere('company_id_user')->is(ID_LOG);

        $query = $this->db()->from('company')->where('company_trash')->is(0)->andWhere('company_id_user')->is(ID_LOG);




        if($forms['name'] != ''){
            $queryPaginator = $queryPaginator->andWhere('company_name')->like('%'.$forms['name'].'%');
            $query = $query->andWhere('company_name')->like('%'.$forms['name'].'%');
        }
        if($forms['fantasy'] != ''){
            $queryPaginator = $queryPaginator->andWhere('company_fantasy')->like('%'.$forms['fantasy'].'%');
            $query = $query->andWhere('company_fantasy')->like('%'.$forms['fantasy'].'%');
        }
        if($forms['cpf_cnpj'] != ''){
            $queryPaginator = $queryPaginator->andWhere('company_cpf_cnpj')->like('%'.$forms['cpf_cnpj'].'%');
            $query = $query->andWhere('company_cpf_cnpj')->like('%'.$forms['cpf_cnpj'].'%');
        }
        if($forms['email'] != ''){
            $queryPaginator = $queryPaginator->andWhere('company_email')->like('%'.$forms['email'].'%');
            $query = $query->andWhere('company_email')->like('%'.$forms['email'].'%');
        }
        if($forms['status'] != ''){
            $queryPaginator = $queryPaginator->andWhere('company_status')->is($forms['status']);
            $query = $query->andWhere('company_status')->is($forms['status']);
        }

        $resPaginator = $queryPaginator->select()->all();
        $result = $query->orderBy('company_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->company_status == '0'){
                    $r->company_status = 'ATIVO';
                }else{
                    $r->company_status = 'INATIVO';
                }
                $r->company_ult_date_nfe_primary = format_datetime_br($r->company_ult_date_nfe_primary);
                $rows['data'][] = $r;
            }

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

    /**
     * @param array $data
     * @return void
     */
    public function selectId(array $data): void
    {
        $result = $this->db()->from('company')
            ->where('company_id')->is($data['id'])
            ->andWhere('company_id_user')->is(ID_LOG)
            ->select()
            ->all();

        if($result){
            foreach ($result as $r){
                echo json_encode($r);
            }
            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 $forms
     * @return void
     */
    public function eliminate(array $forms)
    {
        $data['company_trash'] = '1';

        if($this->db()->update('company')->where('company_id')->is($forms['id'])->andWhere('company_id_user')->is(ID_LOG)->set($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(["count" => 0]);
            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;
    }

    /**
     * @param array $forms
     * @return void
     */
    public function searchCertificate(array $forms)
    {
        if(in_array('', $forms)){
            $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;
        }

        $var = '<div class="row">';

        $result = $this->db()->from('certificate')
            ->where('certificate_id_company')->is($forms['id'])
            ->andWhere('certificate_trash')->is(0)
            ->andWhere('certificate_id_user')->is(ID_LOG)
            ->select()
            ->all();
        if($result){
            $count = '0';
            foreach ($result as $r){
                $var .= '<div class="col-lg-3" align="center">';
                $var .= '<img src="../../img/certificado.png" width="50px" /><br />';
                $var .= '<strong>'.$r->certificate_name.'</strong><br />';
                $var .= '<span>CNPJ: <strong>'.$r->certificate_doc.'</strong></span><br />';
                $var .= '<span>Validade: <strong>'.format_date_br($r->certificate_validity).'</strong></span><br />';
                $var .= '<a href="#" class="btn btn-danger" title="Deletar Certificado Digital?" onclick="delete_certificate('.$r->certificate_id.');">X</a>';
                $var .= '</div>';
            }
        }else{
            $count = '1';
        }


        $var .= '</div>';

        $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" => $count, "retorno" => $var]);
        return;
    }

    /**
     * @param array $forms
     * @return void
     */
    public function certificateCreate(array $forms)
    {
        if(!$_FILES['file']){
            $this->call(
                '200',
                'Ops',
                '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
                "error",
                "Não foi possível fazer o upload dos arquivos solicitados!"
            )->back(["count" => 0]);
            return;
        }

        $nameCertificate = md5(date('Y-m-dH:i:s').rand(100,999)).'.pfx';
        if (move_uploaded_file($_FILES['file']['tmp_name'], 'shared/certificado/' . $nameCertificate)) {

            $data['certificate_file'] = $nameCertificate;
            $data['certificate_trash'] = '0';
            $data['certificate_id_user'] = ID_LOG;

            if($this->db()->insert($data)->into('certificate')){
                $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, "id_certificate" => $this->lastRegistro('certificate', 'certificate_id', 'certificate_id')]);
                return;
            }
        } else {
            $this->call(
                '200',
                'Ops',
                '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
                "error",
                "Não foi possível fazer o upload dos arquivos solicitados!"
            )->back(["count" => 0]);
            return;
        }
    }

    /**
     * @param array $forms
     * @return void
     */
    public function certificateUpdate(array $forms)
    {
        if(in_array('', $forms)){
            $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;
        }



        $data['certificate_id_company'] = $forms['id_contato'];
        $data['certificate_password']      = $forms['senha'];

        $result = $this->db()->from('certificate')
            ->where('certificate_id')->is($forms['id'])
            ->select()
            ->all();

        if($result){

            foreach($result as $r){

                $cert = file_get_contents('shared/certificado/'.$r->certificate_file);
                try {
                    $id = $forms['id'];
                    unset($forms['id']);

                    openssl_pkcs12_read($cert, $inf, $forms['senha']);

                    $CertPriv   = array();
                    $CertPriv   = openssl_x509_parse(openssl_x509_read($inf['cert']));

                    $explodeName = explode(':', $CertPriv['subject']['CN']);

                    $data['certificate_name'] = $explodeName['0'];
                    $data['certificate_doc'] = $explodeName['1'];
                    $data['certificate_validity'] = date('Y-m-d', $CertPriv['validTo_time_t']);

                    $result = $this->db()->update('certificate')->where('certificate_id')->is($id)->set($data);

                    if($result == '0' || $result == '1'){
                        $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;
                    }
                } catch (\Exception $e) {
                    unlink('shared/certificado/'.$r->certificate_file);
                    $this->db()->from('certificate')
                        ->where('certificate_id')->is($forms['id'])
                        ->delete();

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

    /**
     * @param array $forms
     * @return void
     */
    public function certificateDelete(array $forms)
    {
        $id = $forms['id'];
        unset($forms['id']);

        $certificado_form['certificate_trash'] = '1';

        $result = $this->db()->update('certificate')->where('certificate_id')->is($id)->andWhere('certificate_id_user')->is(ID_LOG)->set($certificado_form);

        if($result == '0' || $result == '1'){
            $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;
        }

        $this->call(
            '200',
            'Ops',
            '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>',
            "error",
            "Não foi possível fazer o upload dos arquivos solicitados!"
        )->back(["count" => 0]);
        return;
    }
}
