<?php
class ControllerAccountEdit extends Controller
{
    protected $dataJs = [];

    protected function loadLanguage()
    {
        $language = $this->language->load('account/edit');
        $this->data = array_merge($this->data, $language);
        $this->dataJs = array_merge($this->dataJs, $language);
    }

    protected function loadScripts()
    {
        $this->document->addScript([
            'catalog/view/theme/vista/public/js/account/edit.js',
        ]);
    }

    protected function breadcrumbs()
    {
        $this->breadcrumbs->setbreadcumbs([
            [
                'text' => $this->language->get('text_home'),
                'href' => $this->url->link('common/home', '', 'NONSSL', 'false'),
                'separator' => false
            ],
            [
                'text' => $this->language->get('text_account'),
                'href' => $this->url->link('account/account', '', 'SSL'),
                'separator' => true
            ],
            [
                'text' => $this->language->get('text_edit'),
                'href' => $this->url->link('account/edit', '', 'SSL'),
                'separator' => true
            ]
        ]);
    }

    public function save()
    {
        $this->loadLanguage();
        $this->load->model('account/customer');

        $errors = $this->validate();
        $responseJson = [];

        if ($errors) {
            $responseJson['errors'] = $errors;
        } else {
            $this->model_account_customer->editCustomer($this->request->post);
            $responseJson['success'] = $this->language->get('text_success');
            $responseJson['redirect'] = $this->url->link('account/account', '', 'SSL');
        }

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

    public function index()
    {
        if (!$this->customer->isLogged()) {
            $this->session->data['redirect'] = $this->url->link('account/edit', '', 'SSL');
            $this->redirect($this->url->link('account/register', '', 'SSL'));
        }

        $this->loadLanguage();
        $this->loadScripts();
        $this->breadcrumbs();

        $this->load->model('account/customer');
        $this->load->helper('ftr_geral');
        $this->load->type('tipocomum');

        $this->document->setTitle($this->language->get('heading_title'));

        $customerInfo = $this->model_account_customer->getCustomer($this->customer->getId());
        $this->dataJs['configurations']['firstname'] = $customerInfo['firstname'] ?? '';
        $this->dataJs['configurations']['lastname'] = $customerInfo['lastname'] ?? '';
        $this->dataJs['configurations']['email'] = $customerInfo['email'] ?? '';
        $this->dataJs['configurations']['telephone'] = $customerInfo['telephone'] ?? '';
        $this->dataJs['configurations']['celular'] = $customerInfo['celular'] ?? '';
        $this->dataJs['configurations']['feedback_whatsapp_number'] = $customerInfo['feedback_whatsapp_number'] ?? '';
        $this->dataJs['configurations']['fax'] = $customerInfo['fax'] ?? '';
        $this->dataJs['configurations']['sexo'] = $customerInfo['sexo'] ?? '';
        $this->dataJs['configurations']['data_nascimento'] = implode('/', array_reverse(explode('-', $customerInfo['data_nascimento']))) ?? '';
        $this->dataJs['configurations']['rg'] = $customerInfo['rg'] ?? '';
        $this->dataJs['configurations']['cpf'] = $customerInfo['cpf'] ?? '';
        $this->dataJs['configurations']['razao_social'] = $customerInfo['razao_social'] ?? '';
        $this->dataJs['configurations']['cnpj'] = $customerInfo['cnpj'] ?? '';
        $this->dataJs['configurations']['inscricao_estadual'] = $customerInfo['inscricao_estadual'] ?? '';
        $this->dataJs['configurations']['perfil'] = $customerInfo['perfil'] ?? '';
        $this->dataJs['configurations']['pessoa'] = ($this->customer->getCpf() && $this->customer->getCpf() != '') ? Type_CadastroPessoa::Tp_Fisico : Type_CadastroPessoa::Tp_Juridico;
        $this->dataJs['configurations']['contribuinte'] = $customerInfo['contribuinte'] ?? 'S';

        $this->dataJs['configurations']['update'] = isset($this->request->get['update'])? 1 : 0;

        $this->dataJs['action'] = $this->url->link('account/edit/save', '', 'SSL');
        $this->dataJs['Type_PerfilCustomerJuridico'] = Type_PerfilCustomerJuridico::getEnumlist();
        $this->dataJs['Type_PjContribuoIcms'] = Type_PjContribuoIcms::getEnumlist();
        $this->dataJs['tp_fisico'] = Type_CadastroPessoa::Tp_Fisico;
        $this->dataJs['tp_juridico'] = Type_CadastroPessoa::Tp_Juridico;
        $this->dataJs['feedback_whatsapp'] = $this->feedback->isEnabled();

        /* Configurado no módulo: Campos para cadastro do Brasil */
        $fieldKeys = [
            'fields_register_brazil_status_celular', // Celular Obrigatório
            'fields_register_brazil_status_telefone', // Telefone Obrigatório
            'fields_register_brazil_status_data_nascimento_required', // Celular Obrigatório
            'fields_register_brazil_status_perfil_pj', // Editar Perfil (Pessoa Jurídica)
            'fields_register_brazil_status_contribuinte_pj', // Editar Contribuinte (Pessoa Jurídica)
            'fields_register_brazil_status_ie_pj', // Editar Inscrição Estadual (Pessoa Jurídica)
            'fields_register_brazil_status_telefone2', // Exibir campo segundo Telefone
            'fields_register_brazil_status_sexo', // Exibir campo sexo
            'fields_register_brazil_status_data_nascimento', // Exibir campo data de nascimento
            'fields_register_brazil_status_rg', // Exibir campo RG
        ];
        foreach ($fieldKeys as $key) {
            $this->dataJs[$key] = boolval($this->config->get($key));
        }

        $this->data['back'] = $this->url->link('account/account', '', 'SSL');
        $this->data['NickFromValue'] = Type_CadastroPessoa::getNickFromValue($this->dataJs['configurations']['pessoa']);

        $this->children = [
            'common/breadcrumbs',
            'common/column_left',
            'common/column_right',
            'common/content_top',
            'common/content_bottom',
            'common/footer',
            'common/header'
        ];

        if (!$this->ftrgeralregistry->isApp()) {
            array_push($this->children, 'module/account');
        }

        $this->data['dataJs'] = $this->dataJs;

        $this->app();

        $this->response->setOutput($this->render('account/edit'));
    }

    protected function validate()
    {
        extract($this->request->post);
        $this->loadLanguage();
        $this->load->model('account/customer');
        $this->load->model('account/address');

        $isALegalEntity = $pessoa == Type_CadastroPessoa::Tp_Juridico;
        $isAnIndividual = $pessoa == Type_CadastroPessoa::Tp_Fisico;
        $isNotApp = !$this->ftrgeralregistry->isApp();

        $uf = '';
        $addressId = $this->customer->getAddressId();
        if($addressId){
            $addressInfo = $this->model_account_address->getAddress($addressId);
            $uf = $addressInfo['zone_code'];
        }

        $errors = $this->validate->execute([
            'firstname' => [
                'value' => $firstname,
                'validates' => [
                    'isEmpty',
                    [
                        'method' => 'isMinMax',
                        'min' => '2',
                        'max' => '32',
                    ]
                ],
            ],
            'lastname' => [
                'value' => $lastname,
                'validates' => [
                    'isEmpty',
                    [
                        'method' => 'isMinMax',
                        'min' => '1',
                        'max' => '32',
                    ]
                ],
            ],
            'email' => [
                'value' => $email,
                'validates' => [
                    'isEmpty',
                    'isEmail',
                    [
                        'method' => 'isMinMax',
                        'min' => '1',
                        'max' => '96',
                    ]
                ],
            ],
            'telephone' => [
                'value' => $telephone,
                'validates' => [
                    [
                        'method' => 'isEmpty',
                        'condition' => $isNotApp && $this->config->get('fields_register_brazil_status_telefone')
                    ],
                    'isPhone'
                ],
            ],
            'data_nascimento' => [
                'value' => $data_nascimento ?? '',
                'validates' => [
                    [
                        'method' => 'isDate',
                        'condition' => $isAnIndividual
                    ],
                    [
                        'method' => 'isDateSmallerThanToday',
                        'condition' => $isAnIndividual
                    ],
                    [
                        'method' => 'isEmpty',
                        'condition' => $isNotApp && $isAnIndividual && $this->config->get('fields_register_brazil_status_data_nascimento_required')
                    ]
                ],
                'condition' => $isAnIndividual && $this->config->get('fields_register_brazil_status_data_nascimento_required') && isset($data_nascimento)
            ],
            'celular' => [
                'value' => $celular ?? '',
                'validates' => [
                    [
                        'method' => 'isEmpty',
                        'condition' => $isNotApp && $this->config->get('fields_register_brazil_status_celular')
                    ],
                    'isCellPhone'
                ],
            ],
            'fax' => [
                'value' => $fax ?? '',
                'validates' => ['isPhone'],
            ],
            'sexo' => [
                'value' => $sexo ?? '',
                'validates' => ['isEmpty'],
                'condition' => $isNotApp && $isAnIndividual && $this->config->get('fields_register_brazil_status_sexo')
            ],
            'cpf' => [
                'value' => $cpf ?? '',
                'validates' => ['isCpf'],
                'condition' => $isAnIndividual
            ],
            'cnpj' => [
                'value' => $cnpj ?? '',
                'validates' => ['isCnpj'],
                'condition' => $isALegalEntity
            ],
            'razao_social' => [
                'value' => $razao_social ?? '',
                'validates' => ['isEmpty'],
                'condition' => $isALegalEntity
            ],
            'inscricao_estadual' => [
                'value' => $inscricao_estadual ?? '',
                'validates' => [
                    [
                        'method' => 'isEmpty',
                        'condition' => $isALegalEntity && $contribuinte == 'S'
                    ],
                    [
                        'method' => 'isValidIE',
                        'uf' => $uf,
                        'condition' => $isALegalEntity
                    ],
                ],
            ],
        ]);


        if ($this->customer->getEmail() != $email && $this->model_account_customer->getTotalCustomersByEmail($email)) {
            $errors['email'] = $this->language->get('error_exists');
        }

        if ($this->config->get('fields_register_brazil_status_cnpgcpf')) {
            if ($isAnIndividual) {
                $cpf = preg_replace('/([^0-9])/i', '', $cpf);
                if ($this->customer->getCpf() != $cpf && $this->dmodel_account_customer->getTotalCustomersByCnpjCpf($cpf)) {
                    $errors['cpf'] = $this->language->get('error_cpf_exists');
                }
            }

            if ($isALegalEntity) {
                $cnpj = preg_replace('/([^0-9])/i', '', $cnpj);
                if ($this->customer->getCnpj() != $cnpj && $this->dmodel_account_customer->getTotalCustomersByCnpjCpf($cnpj)) {
                    $errors['cnpj'] = $this->language->get('error_cnpj_exists');
                }
            }
        }


        return $errors;
    }

    public function app()
    {
        if (!$this->ftrgeralregistry->isApp()) {
            return;
        }

        $this->document->addScriptApp([
            'catalog/view/theme/appmobile/public/js/mainheaderform.js',
            'catalog/view/theme/appmobile/public/js/page.edit.js'
        ]);

        $this->document->addStyleApp([
            'catalog/view/theme/appmobile/public/css/mdDateTimePicker.css'
        ]);

        $this->data = array_merge($this->data, $this->dataJs);
        $this->data = array_merge($this->data, $this->dataJs['configurations']);
        $this->data['action'] = $this->url->link('account/edit', '', 'SSL');

        foreach ($this->dataJs['configurations'] as $key => $value) {
            $this->data['error_' . $key] = '';
        }

        if ($this->request->server['REQUEST_METHOD'] == 'POST') {
            $errors = $this->validate();
            if (empty($errors)) {
                $this->model_account_customer->editCustomer($this->request->post);
                $this->session->data['success'] = $this->language->get('text_success');
                $this->redirect($this->url->link('account/account', '', 'SSL'));
            } else {
                foreach ($this->dataJs['configurations'] as $key => $value) {
                    if (in_array($key, array_keys($errors))) {
                        $this->data['error_' . $key] = $errors[$key][0];
                    } else {
                        $this->data['error_' . $key] = '';
                    }
                }
            }
        }

        $this->data['fields_register_brazil_status_telefone'] = false; // Telefone Obrigatório
        $this->data['fields_register_brazil_status_celular'] = false; // Celular Obrigatório
        $this->data['fields_register_brazil_status_data_nascimento_required'] = false; // Data de nascimento obrigatório
    }
}
