<?php

class ControllerPaymentPaymentAddress extends Controller
{

    public function index($setting)
    {

        $language = $this->language->load('payment/payment_address');
        $this->data = array_merge($this->data, $language);

        $this->load->dmodel('checkout/order');
        $this->load->helper('ftr_validacao');

        $this->data['scripts'] = array(
            'catalog/view/theme/vista/js/page.payment_address.js',
        );

        $this->app();

        if (isset($setting['display_cpf'])) {
            $this->data['display_cpf'] = $setting['display_cpf'];
        }

        if(isset($setting['display_titular'])){
          $this->data['display_titular'] = $setting['display_titular'];
        }else{
          $this->data['display_titular'] = true;
        }

        if(isset($setting['load_customer_info']) && $setting['load_customer_info']){
            $this->data['firstname'] = $this->customer->getFirstName();
            $this->data['lastname'] = $this->customer->getLastName();
            $this->data['email'] = $this->customer->getEmail();

            //$this->data['text_info_customer'] = $this->data['text_info_customer'].' '.$this->customer->getFirstName().' '.$this->customer->getLastName();

            if (strpos($this->customer->getDataNascimento(), '0000') === false) {
                $this->data['data_nascimento'] = ftr_geral::formatDate($this->customer->getDataNascimento(), 'br');
            } else {
                $this->data['data_nascimento'] = '';
            }

            $this->data['cpf'] = $this->customer->getCpf();
            $this->data['cnpj'] = $this->customer->getCnpj();
            $this->data['razao_social'] = $this->customer->getRazaoSocial();
            $this->data['inscricao_estadual'] = $this->customer->getInscricaoEstadual();

            if (!empty(trim($this->customer->getCelular()))) {
                $type_payment_phone = Type_PaymentPhone::Tp_Celular;
                $this->data['numero_telefone'] = $this->customer->getCelular();
            } else if (!empty(trim($this->customer->getTelephone()))) {
                $type_payment_phone = Type_PaymentPhone::Tp_Telefone;
                $this->data['numero_telefone'] = $this->customer->getTelephone();
            } else if (!empty(trim($this->customer->getFax()))) {
                $type_payment_phone = Type_PaymentPhone::Tp_Fax;
                $this->data['numero_telefone'] = $this->customer->getFax();
            } else {
                $type_payment_phone = Type_PaymentPhone::Tp_Telefone;
                $this->data['numero_telefone'] = '';
            }

            if (!empty(trim($this->customer->getCpf()))) {
                $this->data['tipo_pessoa'] = Type_CadastroPessoa::Tp_Fisico;
            } else {
                $this->data['tipo_pessoa'] = Type_CadastroPessoa::Tp_Juridico;
            }

            $this->load->model('account/address');
            $shipping_address = $this->model_account_address->getAddress($this->session->data['shipping_address_id']);

            $this->data['shipping_postcode'] = $shipping_address['postcode'];
            $this->data['shipping_address_1'] = $shipping_address['address_1'];
            $this->data['shipping_numero'] = $shipping_address['numero'];
            $this->data['shipping_complemento'] = $shipping_address['complemento'];
            $this->data['shipping_address_2'] = $shipping_address['address_2'];
            $this->data['codigo_municipio'] = $shipping_address['codigo_municipio'];
            $this->data['city'] = $shipping_address['city'];
            $this->data['shipping_zone'] = $shipping_address['zone'];
            $this->data['shipping_zone_id'] = $shipping_address['zone_id'];
        } else {

            $type_payment_phone = Type_PaymentPhone::Tp_Telefone;
        }

        $payment_phones = array();
        foreach (Type_PaymentPhone::getEnumList() as $key => $payment_phone) {
            $payment_phones[] = array(
                'value' => $key,
                'description' => $payment_phone,
                'select' => ftr_geral::isSelected($key, $type_payment_phone, Type_PaymentPhone::Tp_Celular)
            );
        }

        $this->data['payment_phones_text'] = ftr_geral::getDescriptionToTypes($payment_phones);
        $this->data['payment_phones_select'] = $type_payment_phone;
        $this->data['payment_phones'] = $payment_phones;
        $this->data['tipo_pessoas'] = Type_CadastroPessoa::getEnumListConst();
        $this->data['type_payment_phones'] = Type_PaymentPhone::getTypeForJs();
        $this->data['Type_CadastroPessoa'] = $this->load->typeForTwig('Type_CadastroPessoa');
        $this->data['Type_CadastroPessoaJs'] = Type_CadastroPessoa::getTypeForJs();

        if (isset($this->request->post['zone_id'])) {
            $zone_id = $this->request->post['zone_id'];
        } elseif (isset($this->session->data['shipping_zone_id']) && ($this->session->data['shipping_zone_id'] != 'undefined') && ($this->session->data['shipping_zone_id'] != '')) {
            $zone_id = $this->session->data['shipping_zone_id'];
        } else {
            $zone_id = $this->config->get('config_zone_id');
        }

        $this->load->dmodel('localisation/ibge');
        $this->data['cities'] = $this->dmodel_localisation_ibge->getMunicipios($zone_id);

        $this->load->model('localisation/zone');
        $this->data['states'] = $this->model_localisation_zone->getZonesByCountryId(Type_PaisId::Tp_Brasil);

        $this->data['captcha_tpl'] = $this->getChild('payment/captcha');

        if (isset($setting['Type_PaymentOption'])) {
          $typepaymentOption = '_'.$setting['Type_PaymentOption'];
        } else {
          $typepaymentOption = '';
        }

        if (isset($setting['infos_antifraude'])) {
            $this->data['infos_antifraude'] = $setting['infos_antifraude'];
        } else {
            $this->data['infos_antifraude'] = false;
        }

        $payment_name = isset($setting['payment_name']) ? $setting['payment_name'] : '';

        if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/payment/'.$payment_name.'/payment_address'.$typepaymentOption.'.twig')) {
            $this->template = $this->config->get('config_template') . '/template/payment/'.$payment_name.'/payment_address'.$typepaymentOption.'.twig';
        } else {
            $this->template = 'default/template/payment/payment_address.twig';
        }

        $this->response->setOutput($this->render());

    }

    public function validateEmail($error) {
      if (isset($this->request->post['email']) && (!empty($this->request->post['email']))) {
        if ((utf8_strlen($this->request->post['email']) > 96) || !preg_match('/^[^\@]+@.*\.[a-z]{2,6}$/i', $this->request->post['email']) || !filter_var($this->request->post['email'], FILTER_VALIDATE_EMAIL) || !preg_match('/^[a-zA-Z0-9\._-]+@/', $this->request->post['email'])) {
            $error['email'] = $this->language->get('error_email');
        }
      }
      return $error;
    }

    public function validate()
    {

        $this->load->helper('ftr_validacao');
        $this->language->load('payment/payment_address');
        $this->load->dmodel('checkout/order');

        $error = array();

        $data_atual = new DateTime($this->db->dataAtual(), new DateTimeZone('America/Sao_Paulo'));
        $data_atual = $data_atual->format("Y-m-d");

        if (!$this->debug ) {
            $this->language->load('payment/captcha');

            $google_captcha = $this->config->get('google_recaptcha_site_key') && $this->config->get('google_recaptcha_secret_key') && $this->config->get('wg24_google_recaptcha_status');
            $valid_captcha = $this->ftrgeralregistry->validateCaptcha($google_captcha ? $this->request->post['g-recaptcha-response'] : $this->request->post['captcha']);

            if (!$valid_captcha){
                $google_captcha ? $error['g-recaptcha'] = $this->language->get('t_e_google_captcha') : $error['captcha'] = $this->language->get('t_e_captcha');
            }
        }

        if (isset($this->request->post['customer_data_nascimento']) && ($this->request->post['customer_data_nascimento'])) {
            $validates = $this->validate->execute([
                "customer_data_nascimento" => [
                    'value' => $this->request->post['customer_data_nascimento'] ?? null,
                    'validates' => [
                        [
                            'method' => 'isDate',
                            'condition' => isset($this->request->post['customer_data_nascimento'])
                        ],
                        [
                            'method' => 'isDateSmallerThanToday',
                            'condition' => isset($this->request->post['customer_data_nascimento'])
                        ],
                        [
                            'method' => 'isEmpty',
                            'condition' => !$this->ftrgeralregistry->isApp() && isset($this->request->post['customer_data_nascimento'])
                        ]
                    ],
                    'condition' => isset($this->request->post['customer_data_nascimento'])
                ]
            ], true);
            $error = array_merge($error, $validates);
        }

        if (isset($this->request->post['isHolder']) && ($this->request->post['isHolder']) && (count($error) == 0)) {
            return true;
        }

        $error = $this->validateEmail($error);

        if (isset($this->request->post['data_nascimento']) && (empty(trim($this->request->post['data_nascimento'])))) {
            $error['data_nascimento'] = $this->language->get('error_data_nascimento');
        }

        if (isset($this->request->post['data_nascimento']) && (!empty(trim($this->request->post['data_nascimento'])))) {
            $dataparts = explode("/", $this->request->post['data_nascimento']);
            if (strlen(utf8_decode($this->request->post['data_nascimento'])) > 0) {
                if (sizeof($dataparts) != '3') {
                    $error['data_nascimento'] = $this->language->get('error_data_nascimento');
                } else {
                    if (!checkdate($dataparts[1], $dataparts[0], $dataparts[2])) {
                        $error['data_nascimento'] = $this->language->get('error_data_nascimento');
                    }
                }
            }
        }

        if (isset($this->request->post['pessoa'])) {

            switch ($this->request->post['pessoa']) {
                case Type_CadastroPessoa::Tp_Fisico :
                    if (isset($this->request->post['cpf'])) {
                        $cpf = preg_replace('/([^0-9])/i', '', $this->request->post['cpf']);
                        if ((strlen(utf8_decode($cpf)) < 1) || (strlen(utf8_decode($cpf)) > 14)) {
                            $error['cpf'] = $this->language->get('error_cpf');
                        } elseif (!ftr_validacao::isCpf($cpf)) {
                            $error['cpf'] = $this->language->get('error_cpf');
                        }
                    }
                    break;
                case Type_CadastroPessoa::Tp_Juridico :
                    if (isset($this->request->post['cnpj'])) {
                        $cnpj = preg_replace('/([^0-9])/i', '', $this->request->post['cnpj']);
                        if ((strlen(utf8_decode($cnpj)) < 1) || (strlen(utf8_decode($cnpj)) > 18)) {
                            $error['cnpj'] = $this->language->get('error_cnpj');
                        } else if (!ftr_validacao::isCnpj($cnpj)) {
                            $error['cnpj'] = $this->language->get('error_cnpj');
                        }
                    }

                    if (isset($this->request->post['razao_social']) && (empty(trim($this->request->post['razao_social'])))) {
                        $error['razao_social'] = $this->language->get('error_razao_social');
                    }
                    break;
            }

        } else {
            if (isset($this->request->post['cpf']) && (isset($this->request->post['pessoa']))) {
                $cpf = preg_replace('/([^0-9])/i', '', $this->request->post['cpf']);
                if ((strlen(utf8_decode($cpf)) < 1) || (strlen(utf8_decode($cpf)) > 14)) {
                    $error['cpf'] = $this->language->get('error_cpf');
                } elseif (!ftr_validacao::isCpf($cpf)) {
                    $error['cpf'] = $this->language->get('error_cpf');
                }
            }

            if (isset($this->request->post['cnpj'])) {
                $cnpj = preg_replace('/([^0-9])/i', '', $this->request->post['cnpj']);
                if ((strlen(utf8_decode($cnpj)) < 1) || (strlen(utf8_decode($cnpj)) > 18)) {
                    $error['cnpj'] = $this->language->get('error_cnpj');
                } else if (!ftr_validacao::isCnpj($cnpj)) {
                    $error['cnpj'] = $this->language->get('error_cnpj');
                }
            }

            if (isset($this->request->post['razao_social']) && (empty(trim($this->request->post['razao_social'])))) {
                $error['razao_social'] = $this->language->get('error_razao_social');
            }
        }


        if (isset($this->request->post['tipo_telefone'])) {
            switch ($this->request->post['tipo_telefone']) {
                case Type_PaymentPhone::Tp_Telefone:
                case Type_PaymentPhone::Tp_Fax:
                    $obtem_telefone_sem_mascara = preg_replace('/([^0-9])/i', '', $this->request->post['numero_telefone']);
                    if ((utf8_strlen($obtem_telefone_sem_mascara) != 10)) {
                        $error['numero_telefone'] = $this->language->get('error_telephone');
                    }
                    break;
                case Type_PaymentPhone::Tp_Celular:
                    $obtem_celular_sem_mascara = preg_replace('/([^0-9])/i', '', $this->request->post['numero_telefone']);
                    if ((utf8_strlen($obtem_celular_sem_mascara) != 10 && utf8_strlen($obtem_celular_sem_mascara) != 11)) {
                        $error['numero_telefone'] = $this->language->get('error_telephone');
                    }
                    if ((utf8_strlen($obtem_celular_sem_mascara) > 0) && (utf8_strlen($obtem_celular_sem_mascara) != 10 && utf8_strlen($obtem_celular_sem_mascara) != 11)) {
                        $error['numero_telefone'] = $this->language->get('error_telephone');
                    }
                    break;
            }
        }

        if (isset($this->request->post['address_1']) && (empty(trim($this->request->post['address_1'])))) {
            $error['address_1'] = $this->language->get('error_address_1');
        }

        if (isset($this->request->post['address_2']) && (empty(trim($this->request->post['address_2'])))) {
            $error['address_2'] = $this->language->get('error_address_2');
        }

        if (isset($this->request->post['numero'])) {
            $numero = preg_replace('/([^0-9])/i', '', $this->request->post['numero']);
            if ((utf8_strlen($numero) < 1) || (utf8_strlen($numero) > 6)) {
                $error['numero'] = $this->language->get('error_numero');
            }
        }

        if (isset($this->request->post['codigo_municipio'])) {
            if ((trim($this->request->post['codigo_municipio']) == '') || (utf8_strlen($this->request->post['codigo_municipio']) == 0)) {
                $error['codigo_municipio'] = $this->language->get('error_city');
            }
        }

        if (isset($this->request->post['zone_id'])) {
            if ((trim($this->request->post['zone_id']) == '') || (utf8_strlen($this->request->post['zone_id']) == 0)) {
                $error['zone_id'] = $this->language->get('error_zone');
            }
        }

        if (isset($this->request->post['postcode'])) {
            $postcode = preg_replace('/([^0-9])/i', '', $this->request->post['postcode']);
            if ((utf8_strlen($postcode) < 2) || (utf8_strlen($postcode) > 10)) {
                $error['postcode'] = $this->language->get('error_postcode');
            }
        }


        if ($error) {
            return $error;
        } else {
            return false;
        }

    }

    public function app(){
        if ($this->ftrgeralregistry->isApp()) {
            $this->document->addScriptApp(array(
                'public/js/page-payment_address.js',
                'catalog/view/theme/appmobile/js/jquery.mask.js',
                'public/js/postcode.js'
            ));
            $this->data['scriptsApp'] = json_encode($this->document->getScriptsApp());

            $languageApp = $this->language->load('payment/payment_address');
            $this->data['languageApp'] = json_encode($languageApp);
        }
    }


}
