<?php
$loader = $this->registry->get('load');
$loader->controller('base/base');

class ControllerAccountRegisterNew extends ControllerBaseBase
{
    protected $referencePathFile = 'account/register_new';
    protected $debug = false;

    protected function loadStyle()
    {
        $this->document->addStyle("public/css/minimalist.css");
    }

    protected function actionUrls()
    {
        $actionUrl = '';

        if (isset($this->request->get['cml'])) {
            $actionUrl = '&cml=' . $this->request->get['cml'];
        } elseif (isset($this->request->get['debug'])) {
            $actionUrl = '&debug=true';
        }
        if ($this->dataVue['isCheckout']) {
            $actionUrl .= '&checkout=true';
        }

        $this->dataVue['action'] = $this->url->link($this->referencePathFile, $actionUrl, 'SSL');
    }

    protected function loadModel()
    {
        $this->load->model('account/customer');
        $this->load->dmodel('account/customer');
        $this->load->model('account/address');
        $this->load->model('localisation/zone');
        $this->load->model('localisation/country');
        $this->load->dmodel('localisation/ibge');
        $this->load->model('catalog/information');

        parent::loadModel();
    }

    protected function loadData()
    {
        $this->dataVue['mobile_register'] = $this->request->get['mobile_register'] ?? false;

        if (isset($this->request->get['page'])) {
            $this->dataVue['page'] = $this->request->get['page'];
        }

        $this->dataVue['site_key'] = $this->config->get('google_recaptcha_site_key');

        $this->dataVue['google_captcha'] =
            $this->dataVue['site_key']
            && $this->config->get('google_recaptcha_secret_key')
            && $this->config->get('wg24_google_recaptcha_status');

        $this->dataVue['loginredesociais_google_status'] = $this->config->get('loginredesociais_google_status');
        $this->dataVue['loginredesociais_facebook_status'] = $this->config->get('loginredesociais_facebook_status');

        $this->dataVue['perfis'] = [];

        $perfis = Type_PerfilCustomerJuridico::getEnumlist();
        foreach ($perfis as $key => $perfil) {
            $this->dataVue['perfis'][] = [
                'value' => $key,
                'name' => $perfil,
                'selected' => isset($this->request->post['perfil']) && $this->request->post['perfil'] == $key
            ];
        }

        $this->dataVue['contribuintes'] = [];

        $contribuintes = Type_PjContribuoIcms::getEnumlist();
        foreach ($contribuintes as $key => $contribuinte) {
            $this->dataVue['contribuintes'][] = [
                'value' => $key,
                'name' => $contribuinte,
                'selected' => isset($this->request->post['contribuinte']) && $this->request->post['contribuinte'] == $key
            ];
        }

        // INICIO: Cria as variaveis para controle de exibição na .tpl por Dionis Mendanha
        $arrayDataExibir = [
            'fields_register_brazil_status_telefone',
            'fields_register_brazil_status_celular',
            'fields_register_brazil_status_telefone2',
            'fields_register_brazil_status_sexo',
            'fields_register_brazil_status_data_nascimento',
            'fields_register_brazil_status_rg',
            'fields_register_brazil_status_data_nascimento_required'
        ];

        $notRequiredFieldsInMobile = [
            'fields_register_brazil_status_telefone',
            'fields_register_brazil_status_celular',
            'fields_register_brazil_status_data_nascimento_required'
        ];

        foreach ($arrayDataExibir as $dataexibir) {

            //validação feita para que não torne esses campos obrigatorios nos aplicativos
            if (in_array($dataexibir, $notRequiredFieldsInMobile) && $this->ftrgeralregistry->isApp()) {
                $this->dataVue[$dataexibir] = false;
            } else {
                $this->dataVue[$dataexibir] =
                    !ftr_geral::isIsset($this->config->get($dataexibir)) || $this->config->get($dataexibir);
            }
        }
        // FIM: Cria as variaveis para controle de exibição na .tpl por Dionis Mendanha

        $this->dataVue['country_id'] = Type_PaisId::Tp_Brasil;

        $this->dataVue['states'] = $this->model_localisation_zone->getZonesByCountryId(Type_PaisId::Tp_Brasil);

        $this->dataVue['postcode_readonly'] = $this->dataVue['postcode_readonly'] ?? true;

        foreach ($this->request->post as $key => $value) {
            $this->dataVue[$key] = $value;
        }

        // pega o tipo de pessoa para gerar a lista
        if (!isset($this->dataVue['fields_register_brazil_tipo_de_pessoa'])) {
            $this->dataVue['fields_register_brazil_tipo_de_pessoa'] = $this->config->get('fields_register_brazil_tipo_de_pessoa');
        }

        $this->dataVue['fields_register_brazil_tipo_de_pessoa_array'] = [];

        foreach (Type_CadastroPessoa::getEnumList(true) as $key => $value) {
            $this->dataVue['fields_register_brazil_tipo_de_pessoa_array'][] = $key;
        }

        if (!isset($this->dataVue['postcode'])) {
            $this->dataVue['postcode'] = isset($this->session->data['shipping_postcode']) ? $this->session->data['shipping_postcode'] : '';
        }

        if (!isset($this->dataVue['country_id'])) {
            $this->dataVue['country_id'] =
                isset($this->session->data['shipping_country_id']) ? $this->session->data['shipping_country_id'] : Type_PaisId::Tp_Brasil;
        }

        if (!isset($this->dataVue['zone_id'])) {
            $this->dataVue['zone_id'] = isset($this->session->data['shipping_zone_id']) && $this->session->data['shipping_zone_id'] ? $this->session->data['shipping_zone_id'] : $this->config->get('config_zone_id');
        }

        $this->dataVue['zone_name'] = $this->model_localisation_zone->getZone($this->dataVue['zone_id'])['name'];
        $this->dataVue['countries'] = $this->model_localisation_country->getCountries();
        $this->dataVue['cities'] = $this->dmodel_localisation_ibge->getMunicipios($this->dataVue['zone_id']);

        if ($this->config->get('config_account_id')) {

            $information_info = $this->model_catalog_information->getInformation($this->config->get('config_account_id'));

            if ($information_info) {
                $this->dataVue['text_agree'] = sprintf($this->language->get('text_agree'), $this->url->link('information/information', 'information_id=' . $this->config->get('config_account_id'), 'SSL'), $information_info['title'], $information_info['title']);
                $this->dataVue['agree_link'] = $this->url->link('information/information', 'information_id=' . $this->config->get('config_account_id'), 'SSL');
            } else {
                $this->dataVue['text_agree'] = '';
            }
        } else {
            $this->dataVue['text_agree'] = '';
        }

        $this->dataVue['captcha'] = '';

        $this->dataVue['customer_interests_remember'] = (bool) $this->config->get('fields_register_brazil_status_interests');
        $this->dataVue['interests_categories'] = $this->getChildData('account/interests_categories', $this->request->post['categories'] ?? []);
        $this->dataVue['login'] = $this->getChildData('account/login_new', isset($this->request->post) ? $this->request->post : '');
        $this->dataVue['forgotten'] = $this->getChildData('account/forgotten_new');

        $this->dataVue['feedback_whatsapp_isenabled'] = $this->feedback->isEnabled();

        if (isset($this->request->get['cmltoken'])) {
            $id = ftr_geral::cripty($this->request->get['id'], $this->config->get('config_encryption'));
            if ($id == $this->request->get['cmltoken']) {
                $this->getDadosClienteMl($this->request->get['id']);
            }
        }

        $this->dataVue['session_id'] = $this->session->getId();

        $this->dataVue['TypesForJs'] = [
            Type_CadastroPessoa::getTypeForJs()
        ];
    }

    protected function childrens()
    {
        $this->children = [
            'common/header_minimalist'
        ];
    }

    public function index()
    {
        $this->dataVue['isCheckout'] = isset($this->request->get['checkout']) && $this->request->get['checkout'];

        if ($this->customer->isLogged()) {
            if ($this->dataVue['isCheckout']) {
                $this->redirect($this->url->link('checkout/checkout', '', 'SSL'));
            } else {
                $this->redirect($this->url->link('account/account', '', 'SSL'));
            }
        }

        if (isset($this->session->data['warning'])) {
            $this->errors['warning'] = $this->session->data['warning'];
            unset($this->session->data['warning']);
        }

        foreach ($this->errors as $key => $error) {
            $this->dataVue['error_' . $key] = $error;
        }

        $this->setDebug();
        $this->dataVue['debug'] = $this->debug;

        parent::index();

        if ($this->request->server['REQUEST_METHOD'] == 'POST') {

            if (!$this->validate()) {
                return $this->response->setOutputJson(['errors' => $this->errors]);
            }

            // Default Shipping Address
            if ($this->config->get('config_tax_customer') == 'shipping') {
                $this->session->data['shipping_country_id'] = $this->request->post['country_id'];
                $this->session->data['shipping_zone_id'] = $this->request->post['zone_id'];
                $this->session->data['shipping_postcode'] = $this->request->post['postcode'];
            }

            // Default Payment Address
            if ($this->config->get('config_tax_customer') == 'payment') {
                $this->session->data['payment_country_id'] = $this->request->post['country_id'];
                $this->session->data['payment_zone_id'] = $this->request->post['zone_id'];
            }

            // if (!$this->dataVue['isCheckout']) {
            if (isset($this->request->get['tbp'])) {
                $this->request->post['tbp'] = base64_decode($this->request->get['tbp']);
            }

            if (isset($this->session->data['customerml'])) {
                $this->request->post['customerml'] = $this->session->data['customerml'];
                $this->model_account_customer->editCustomer($this->request->post);
            } else {
                $postData = $this->request->post;
                if (isset($this->request->get['indication_customer_id'])) {
                    $postData['indicator_id'] = $this->request->get['indication_customer_id'];
                }
                $this->model_account_customer->addCustomer($postData);
            }

            unset($this->session->data['guest']);
            unset($this->session->data['customerml']);

            $this->customer->login($this->request->post['email'], $this->request->post['password']);

            $redirect = '';
            if ($this->dataVue['isCheckout']) {
                $redirect = $this->url->link('checkout/checkout');
            } else {
                $redirect = $this->url->link('account/success');
            }

            return $this->response->setOutputJson(['redirect' => $redirect]);
            // }
        }

        //======================================================================
        //======= todo o conteudo que estava aqui esta na função loadData ======
        //======================================================================

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

    protected function setDebug()
    {
        $dataCaptcha = [
            'debug' => (bool) isset($this->request->get['debug']) ? $this->request->get['debug'] : false,
            'ambiente' => (bool) defined('AMBIENTE_TESTE')
        ];

        if (count(array_filter($dataCaptcha)) == 2) {
            $this->debug = true;
        }
    }

    protected function setData($data, $post, $info)
    {

        foreach ($data as $value) {

            if (is_array($value)) {
                foreach ($value as $val) {
                    if (isset($post[$val])) {
                        $this->dataVue[$val] = $post[$val];
                    } elseif ($info[$val]) {
                        $this->dataVue[$val] = $info[$val];
                    }
                }
                if (isset($value['pessoa'])) {
                    $this->dataVue['fields_register_brazil_tipo_de_pessoa'] = (isset($this->dataVue['cnpj']) && ($this->dataVue['cnpj'] != "")) ? Type_CadastroPessoa::Tp_Juridico : Type_CadastroPessoa::Tp_Fisico;
                    $this->dataVue['pessoa'] = (isset($this->dataVue['cnpj']) && ($this->dataVue['cnpj'] != "")) ? Type_CadastroPessoa::Tp_Juridico : Type_CadastroPessoa::Tp_Fisico;
                }
            } else {
                if (isset($post[$value])) {
                    $this->dataVue[$value] = $post[$value];
                } elseif ($info[$value]) {
                    $this->dataVue[$value] = $info[$value];
                } else {
                    $this->dataVue[$value] = '';
                }
            }
        }
    }

    public function captcha()
    {
        $this->load->library('captcha');

        $captcha = new Captcha();
        $this->session->data['captcha'] = $captcha->getCode();

        $captcha->showImage();
    }

    public function country()
    {
        $json = [];

        $country_info = $this->model_localisation_country->getCountry($this->request->get['country_id']);

        if ($country_info) {
            $json = [
                'country_id' => $country_info['country_id'],
                'name' => $country_info['name'],
                'iso_code_2' => $country_info['iso_code_2'],
                'iso_code_3' => $country_info['iso_code_3'],
                'address_format' => $country_info['address_format'],
                'postcode_required' => $country_info['postcode_required'],
                'zone' => $this->model_localisation_zone->getZonesByCountryId($this->request->get['country_id']),
                'status' => $country_info['status']
            ];
        }

        $this->response->setOutputJson($json);
    }

    public function email()
    {
        $errors = [];

        $this->language->load('checkout/checkout');

        $errors = array_merge($errors, $this->validate->execute([
            'email' => [
                'value' => $this->request->post['email'],
                'validates' => [
                    'isEmpty',
                    [
                        'method' => 'isEmail',
                        'message' => $this->language->get('error_email'),
                    ],
                    [
                        'method' => 'isAlreadyRegisteredEmail',
                        'message' => $this->language->get('error_exists'),
                    ]
                ],
            ],
        ]));

        $json = $errors ? ['errors' => $errors] : ['success' => true];

        $this->response->setOutputJson($json);
    }

    protected function getDadosClienteMl($clienteMl)
    {
        $customer = $this->model_account_customer->getCustomer($clienteMl);

        if (($customer) && (!$customer['cadastro_atualizado_ml'])) {

            $dataCustomer = [
                'firstname',
                'lastname',
                'telephone',
                'celular',
                'pessoa' => [
                    'cpf',
                    'cnpj'
                ]
            ];

            $this->setData($dataCustomer, $this->request->post, $customer);

            $address = $this->model_account_address->getAddressCustomer($clienteMl);

            if ($address) {
                $dataAdress = [
                    'address_1',
                    'numero',
                    'address_2',
                    'city',
                    'postcode',
                    'zone_id',
                    'country_id',
                    'tipo_logradouro',
                    'logradouro',
                    'codigo_municipio'
                ];
                $this->setData($dataAdress, $this->request->post, $address);
            }

            $this->session->data['customerml'] = $clienteMl;
        } else {
            $this->dataVue['customerml'] = 'Seu cadastro está atualizado, entre com sua conta.';
        }
    }

    public function validate()
    {
        $this->setDebug();
        $data = $this->request->post;

        $this->language->load('checkout/checkout');

        extract($this->request->post);

        $numero = preg_replace('/([^0-9])/i', '', $numero);
        if ((utf8_strlen($numero) < 1) || (utf8_strlen($numero) > 6)) {
            $this->errors['numero'] = ['Atenção: O número deve ter entre 1 e 6 caracteres!'];
        }

        if (trim($codigo_municipio) == '') {
            $this->errors['city'] = [$this->language->get('error_city')];
        }

        $country_info = $this->model_localisation_country->getCountry($country_id);

        if ($country_info) {
            if ($country_info['postcode_required'] && (utf8_strlen($postcode) < 2) || (utf8_strlen($postcode) > 10)) {
                $this->errors['postcode'] = [$this->language->get('error_postcode')];
            }
        }

        if ($country_id == '') {
            $this->errors['country'] = [$this->language->get('error_country')];
        }

        if (!isset($zone_id) || $zone_id == '') {
            $this->errors['zone'] = [$this->language->get('error_zone')];
        }

        $zone_info = $this->model_localisation_zone->getZone($zone_id);

        if (isset($zone_id) && isset($codigo_municipio)) {

            if (!$this->dmodel_localisation_ibge->getEstadoCidade($zone_id, $codigo_municipio)) {
                $this->errors['city'] = ['A cidade não pertence ao estado selecionado'];
            }
        }
        if ($country_id <> $this->model_account_address->getCountryByZone($zone_id)) {
            $zone_id = '';
            $this->errors['zone'] = [$this->language->get('error_zone')];
        }

        $errors = [];
        $errors = array_merge($errors, $this->validate->execute([
            "firstname" => [
                'value' => $firstname,
                'validates' => [
                    'isEmpty',
                    [
                        'method' => 'isMinMax',
                        'min' => 1,
                        'max' => 32
                    ]
                ],
            ],
            "lastname" => [
                'value' => $lastname,
                'validates' => [
                    'isEmpty',
                    [
                        'method' => 'isMinMax',
                        'min' => 1,
                        'max' => 32
                    ]
                ],
            ],
            "data_nascimento" => [
                'value' => $data_nascimento ?? null,
                'validates' => [
                    [
                        'method' => 'isDate',
                        'condition' => $pessoa == "F" && isset($data_nascimento)
                    ],
                    [
                        'method' => 'isDateSmallerThanToday',
                        'condition' => $pessoa == "F" && isset($data_nascimento)
                    ],
                    [
                        'method' => 'isEmpty',
                        'condition' => $this->config->get('fields_register_brazil_status_data_nascimento_required') && !$this->ftrgeralregistry->isApp() && $pessoa == "F" && isset($data_nascimento)
                    ]
                ],
                'condition' => $pessoa == "F" && isset($data_nascimento)
            ],
            "cpf" => [
                'value' => $cpf ?? null,
                'validates' => ['isCpf'],
                'condition' => $pessoa == "F" && isset($cpf)
            ],
            "cnpj" => [
                'value' => $cnpj ?? null,
                'validates' => ['isCnpj'],
                'condition' => $pessoa == "J" && isset($cnpj)
            ],
            "razao_social" => [
                'value' => $razao_social ?? null,
                'validates' => ['isEmpty'],
                'condition' => $pessoa == "J"
            ],
            "inscricao_estadual" => [
                'value' =>  $inscricao_estadual ?? '',
                'validates' => [
                    'isEmpty',
                    [
                        'method' => 'isValidIE',
                        'uf' => $zone_info['code'],
                    ],
                ],
                'condition' => isset($inscricao_estadual) && isset($zone_id) && $contribuinte == 'S'
            ],
            'email' => [
                'value' => $email,
                'validates' => [
                    'isEmpty',
                    [
                        'method' => 'isEmail',
                        'message' => $this->language->get('error_email'),
                    ],
                    [
                        'method' => 'isAlreadyRegisteredEmail',
                        'message' => $this->language->get('error_exists'),
                    ]
                ],
            ],
            'telephone' => [
                'value' => $telephone,
                'validates' => [
                    [
                        'method' => 'isPhone',
                        'condition' => !ftr_geral::isIsset($this->config->get('fields_register_brazil_status_telefone')) || $this->config->get('fields_register_brazil_status_telefone') && !$this->ftrgeralregistry->isApp()
                    ],
                ]
            ],
            'celular' => [
                'value' => $celular,
                'validates' => [
                    [
                        'method' => 'isEmpty',
                        'message' => $this->language->get('error_celular'),
                        'condition' => $this->config->get('fields_register_brazil_status_celular')
                    ],
                    [
                        'method' => 'isCellPhone',
                        'message' => $this->language->get('error_celular'),
                        'condition' => !ftr_geral::isIsset($this->config->get('fields_register_brazil_status_celular')) || $this->config->get('fields_register_brazil_status_celular') && !$this->ftrgeralregistry->isApp()
                    ]
                ],
            ],
            'feedback_whatsapp_number' => [
                'value' => $feedback_whatsapp_number ?? null,
                'validates' => [
                    [
                        'method' => 'isEmpty',
                        'message' => $this->language->get('error_whatsapp'),
                        'condition' => $feedback_whatsapp_status ?? null
                    ],
                    [
                        'method' => 'isCellPhone',
                        'message' => $this->language->get('error_whatsapp'),
                        'condition' => $feedback_whatsapp_status ?? null
                    ],
                ],
                'condition' => isset($feedback_whatsapp_number)
            ],
            'address_1' => [
                'value' => $address_1,
                'validates' => [
                    [
                        'method' => 'isMinMax',
                        'min' => 3,
                        'max' => 70,
                        'message' => $this->language->get('error_address_1'),
                    ]
                ],
            ],
            'address_2' => [
                'value' => $address_2,
                'validates' => [
                    [
                        'method' => 'isMinMax',
                        'min' => 1,
                        'max' => 50,
                        'message' => $this->language->get('error_address_2'),
                    ]
                ],
            ],
            'complemento' => [
                'value' => $complemento,
                'validates' => [
                    [
                        'method' => 'isMinMax',
                        'min' => 3,
                        'max' => 60,
                        'message' => $this->language->get('error_complemento'),
                    ]
                ],
            ],
            'apelido' => [
                'value' => $apelido,
                'validates' => [
                    'isEmpty',
                    [
                        'method' => 'isMinMax',
                        'min' => 3,
                        'max' => 128,
                        'message' => $this->language->get('error_apelido'),
                    ]
                ],
            ],

        ]));

        $this->errors = array_merge($this->errors, $errors);

        if ($this->config->get('fields_register_brazil_status_cnpgcpf')) {
            if (!isset($this->session->data['customerml'])) {

                $doc = isset($cpf) && $cpf ? 'cpf' : 'cnpj';
                $dados = preg_replace('/([^0-9])/i', '', $this->request->post[$doc]);

                if ($dados) {

                    if ($this->dmodel_account_customer->getTotalCustomersByCnpjCpf($dados)) {

                        if ($this->request->post[$doc]) {
                            $this->errors[$doc] = [$this->language->get('error_' . $doc . '_exists')];
                        }
                    }
                }
            }
        }

        if ((utf8_strlen($password) < 4) || (utf8_strlen($password) > 20)) {
            $this->errors['password'] = [$this->language->get('error_password')];
        }

        if ($confirm != $password) {
            $this->errors['confirm'] = [$this->language->get('error_confirm')];
        }

        if ($this->config->get('config_account_id')) {
            $information_info = $this->model_catalog_information->getInformation($this->config->get('config_account_id'));

            if ($information_info && !isset($agree)) {
                $this->errors['agree'] = [$this->language->get('error_agree')];
            }
        }

        if (isset($tipo_logradouro) && $tipo_logradouro == '') {
            $this->dataVue['postcode_readonly'] = false;
        }

        //validação do recaptcha sempre tem que ser a ultima a ser feita
        if (!$this->debug) {

            if (isset($data['g-recaptcha-response']) && (count($this->errors) == 0)) {
                if (!$this->config->get('google_recaptcha_site_key') || !$this->config->get('google_recaptcha_secret_key') || !$this->config->get('wg24_google_recaptcha_status')) {
                    if (empty($this->session->data['captcha']) || ($this->session->data['captcha'] != $captcha)) {
                        $this->errors['captcha'] = [$this->language->get('error_captcha')];
                    }
                }

                if ($this->config->get('google_recaptcha_site_key') && $this->config->get('google_recaptcha_secret_key') && $this->config->get('wg24_google_recaptcha_status')) {
                    $recaptcha = $this->ftrgeralregistry->validateGoogleCaptha($this->config->get('google_recaptcha_secret_key'), isset($data['g-recaptcha-response']) ? $data['g-recaptcha-response'] : '', $this->request->server['REMOTE_ADDR']);
                    if (!$recaptcha["success"]) {
                        $this->errors['google_recaptcha'] = ['Erro de validação no reCaptcha! Efetue a validação para continuar'];
                    }
                }
            } else if ((empty($this->session->data['captcha']) || ($this->session->data['captcha'] != $captcha)) && (count($this->errors) == 0)) {
                $this->errors['captcha'] = ['O código de verificação não coincide com a imagem!' . $this->debug];
            }
        }

        if ($this->errors) {
            $this->errors['warning'] = $this->language->get('error_warning_register');
            $this->errors['postcode_visible'] = true;
        }

        return !$this->errors;
    }
}
