<?php
loadcontroller('base/module');

class ControllerPaymentMatera extends ControllerBaseModule {

    protected $referencePathFile = 'payment/matera';
    protected $arrayJson = ['matera_pix'];
    protected $fieldsToRemoveMask = [
        'matera_pix.valor_minimo' => 'removeMaskToDouble',
        'matera_pix.desconto' => 'removeMaskToDouble',
    ];

    protected function loadData(){
        parent::loadData();
        
        $this->dataVue['token'] = $this->token;
        $this->dataVue['Type_Status'] = Type_Status::getEnumList();
        $this->dataVue['Type_DsimDnao'] = Type_DsimDnao::getEnumList();
        $this->dataVue['Type_Environment'] = Type_Environment::getEnumList();
        $this->dataVue['Type_MarketplaceAdjustmentPrice'] = Type_MarketplaceAdjustmentPrice::getEnumList();
        $this->dataVue['Type_DisplayModuleOption'] = Type_DisplayModuleOption::getEnumList();

        $this->dataVue['configurations'] += [
            // Default Settings 
            'matera_status' => $this->config->get('matera_status'),
            'matera_order' => $this->config->get('matera_order') ?? 0,
            'matera_term_status' => $this->config->get('matera_term_status') ?? 0,
            'matera_api_ambiente' => $this->config->get('matera_api_ambiente') ?? 'sandbox',
            
            // Advanced Settings 
            'matera_discount_status' => $this->config->get('matera_discount_status') ?? Type_Status::Tp_Habilitado,
            'matera_discount_order' => $this->config->get('matera_discount_order') ?? 0,
            'matera_pix' => [
                'status' => Type_Status::Tp_Habilitado,
                'title' => $this->config->get('title') ?? $this->language->get('text_matera_pix'),
                'tipo_desconto' => $this->config->get('tipo_desconto'),
                'expires_at' => $this->config->get('expires_at') ?? 1,
            ],
            
            // Customer infos 
            'matera_account_info' => [],
            'matera_billing_address' => []   
        ];
   
        $fullAccount = $this->model_payment_matera->getFullAccountDB();

        if($fullAccount){

            $response_json = $this->matera->getAccount($fullAccount['cnpj']);

            if($response_json && !isset($response_json->erro)){
                
                $accountFounded = null;
                $billingAddressInfo = [];
                $transaction = [];
                $accountInfo = $response_json->conta;

                foreach ($response_json->transacao as $item) {
                    if ($item->mensagem === "CONTA CADASTRADA") {
                        $accountFounded = $item;
                        break;
                    };
                };

                if ($accountFounded) {
                    $transaction = json_decode($accountFounded->json_envio, true) ?? [];
                    $billingAddressInfo = $transaction['billingAddress'] ?? [];
                };

                $this->dataVue['configurations']['matera_account_info'] = [
                    "cnpj" =>  $accountInfo->cnpj,
                    "account_id" =>  $accountInfo->account_id,
                    "razao_social" =>  $accountInfo->razao_social,
                    "email" =>  $accountInfo->email,
                    "ec_tx_tipo" =>  $accountInfo->ec_tx_tipo,
                    "ec_tx_valor" =>  $accountInfo->ec_tx_valor,   
                    "ec_tx_percentual" =>  $accountInfo->ec_tx_percentual,
                    "ec_tx_percentual_vlr_min" =>  $accountInfo->ec_tx_percentual_vlr_min, 
                    "ec_tx_percentual_vlr_max" =>  $accountInfo->ec_tx_percentual_vlr_max, 
                    "ec_tx_faixa_valor" =>  $accountInfo->ec_tx_faixa_valor
                ];
    
                $this->dataVue['configurations']['matera_billing_address'] = [
                    "logradouro" => $billingAddressInfo['logradouro'],
                    "numero" => $billingAddressInfo['numero'],
                    "cidade" => $billingAddressInfo['cidade'],
                    "estado" => $billingAddressInfo['estado'],
                    "bairro" => $billingAddressInfo['bairro'],
                    "cep" => $billingAddressInfo['cep']
                ];

                $this->model_payment_matera->updateDataDB($this->dataVue['configurations'], $fullAccount);
            };        
        };

        $this->dataVue['order_statuses'] = $this->config->get('processo_venda_status') ? $this->dmodel_proccess_order_to_situation->getProccessStatusAll() : $this->model_localisation_order_status->getOrderStatuses();
    }

    protected function loadModel(){
        parent::loadModel();
        $this->load->type('tipocomum');
        $this->load->dmodel('proccess/order_to_situation');
        $this->load->model('localisation/order_status');
    }

    public function validate() {

        $this->language->load('payment/matera');
        
        extract($this->request->post);

        if (!$matera_term_status) {
            $this->errors['matera_term_status'] = $this->language->get('text_error_term');
        }
        
        if (!$this->errors) {
            $this->model_setting_setting->editSetting($this->fileName, $matera_pix, 0, $this->arrayJson);

            $matera_term_config = [
                'STATUS' => $matera_term_status,
                'CNPJ' => preg_replace('/[^a-zA-Z0-9]/', '', $matera_account_info['cnpj']),
                'IP' => preg_replace('/[^a-zA-Z0-9]/', '', $_SERVER['REMOTE_ADDR']),
                'HTTP_USER_AGENT' => $_SERVER['HTTP_USER_AGENT'],
            ];
    
            $matera_term_hash = base64_encode(json_encode($matera_term_config));

            $data = $this->request->post;

            $data['matera_term'] = $matera_term_hash;

            $fullAccount = $this->model_payment_matera->getFullAccountDB();
            $fullAccount ? $this->model_payment_matera->updateDataDB($data, $fullAccount) : $this->model_payment_matera->saveDataDB($data);

            $this->generateCertificate($data['matera_account_info']['cnpj']);
        }

        return $this->errors;
    }

    public function generateCertificate($data = null){
        parent::loadModel();

        $result = $this->matera->getAccount($data);

        if($result){
            $privateKey = $result->conta->chave_privada;
            $certificate = $result->conta->certificado;

            $privateKeyDescript = Crypto::descriptografarAES256($privateKey, Crypto::CAES256);
            $certificateDescript = Crypto::descriptografarAES256($certificate, Crypto::CAES256);

            $key = base64_decode($privateKeyDescript);
            $certificate = base64_decode($certificateDescript);

            $directory = DIR_SYSTEM . 'library/matera';
            $keyFile = $directory . '/private_key.key';
            $pemFile = $directory . '/certificate.pem';

            try{
                file_put_contents($keyFile, $key);
                file_put_contents($pemFile, $certificate); 
            } catch(Exception $e){
                $this->log->write('Erro ao criar arquivo: '. $e->getMessage());
            }  
        }       
    }

    public function getAccountInfo() {

        if ($this->request->server['REQUEST_METHOD'] == 'POST') {	
            
            $response_json = $this->matera->getAccount($this->request->post);
    
            return $this->response->setOutputJson($response_json);
        }
    }

    public function install() {
        $this->load->model('setting/extension');
        $this->load->model('setting/setting');
        $this->model_setting_extension->install('total', Type_materaConfigs::Tp_NameModule, Type_ExtensionSubType::Tp_TotalizadorAcrescimoDesconto);
    }

    public function uninstall(){
        $this->load->model('setting/extension');
        $this->load->model('payment/matera');
        $this->model_setting_extension->uninstall('total', Type_materaConfigs::Tp_NameModule);
        $this->model_payment_matera->deleteDataDB();
    }
}