<?php


class ControllerAccountEmailValidate extends Controller
{
    public function index()
    {
        $this->app();
        
        if ($this->config->get('email_validation_status') > 0) {
            $this->language->load('account/email_validate');

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

            $this->document->addScript(
                'catalog/view/theme/vista/public/js/account/email_validate.js',
            );

            $this->data['heading_title'] = $this->language->get('heading_title');
            $this->data['entry_email'] = $this->language->get('entry_email');
            $this->data['entry_email_placeholder'] = $this->language->get('entry_email_placeholder');
            $this->data['entry_info_validate'] = $this->language->get('entry_info_validate');
            $this->data['entry_login'] = sprintf($this->language->get('entry_login'), $this->url->link('account/register'));
            $this->data['email'] = $this->request->get['email'] ?? '';
            $this->data['button_send'] = $this->language->get('button_send');

            $this->data['action'] = !$this->ftrgeralregistry->isApp() ? $this->url->link('account/email_validate/sendEmail', '', 'SSL') : $this->url->link('account/email_validate', '', 'SSL');

            if ($this->request->server['REQUEST_METHOD'] == 'POST') {
                $error = $this->validate();
                if ($error) {
                    $this->data['error'] = $error['email'][0];
                } else {
                    $this->language->load('account/email_validate');

                    $this->load->model('account/customer');

                    $customer = $this->model_account_customer->getCustomerByEmail($this->request->post['email']);

                    $hashIdCustomer = Crypto::criptografarAES256($customer['customer_id'], Crypto::CAES256);

                    $pageToRedirect = $this->url->link('account/success', 'token=' . $hashIdCustomer, 'SSL');

                    $email = $customer["email"];

                    $name = $customer["firstname"];

                    $subject = sprintf($this->language->get('text_subject'), $name);
                    $message = sprintf($this->language->get('text_message'), $pageToRedirect, $this->language->get('text_active_account'));

                    $this->emailvalidate->sendEmail($email, $name, $subject, $message);

                    $this->data['success'] = $this->language->get('text_email_validate_success');
                }
            }

            $this->data['breadcrumbs'] = array();

            $this->data['breadcrumbs'][] = array(
                'text' => $this->language->get('text_home'),
                'href' => $this->url->link('common/home', '', 'NONSSL', 'false'),
                'separator' => false
            );

            $this->data['breadcrumbs'][] = array(
                'text' => $this->language->get('text_account'),
                'href' => $this->url->link('account/account', '', 'SSL'),
                'separator' => $this->language->get('text_separator')
            );

            $this->data['breadcrumbs'][] = array(
                'text' => $this->language->get('text_success'),
                'href' => $this->url->link('account/validate'),
                'separator' => $this->language->get('text_separator')
            );

            $this->breadcrumbs->setbreadcumbs($this->data['breadcrumbs']);

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

            $this->children = array(
                'common/breadcrumbs',
                'common/column_left',
                'common/column_right',
                'common/content_top',
                'common/content_bottom',
                'common/footer',
                'common/header'
            );

            $this->response->setOutput($this->render('account/email_validate'));
        } else {
            $this->redirect($this->url->link('account/success', '', 'SSL'));
        }
    }

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

            $response = [];

            //Para o fluxo de reenvio de email
            if (isset($this->request->post['email_login'])) {
                $this->request->post['email'] = $this->request->post['email_login'];
                $response['redirect'] = $this->url->link('account/register', '', 'SSL');
            }

            if (!$this->validate()) {

                $this->language->load('account/email_validate');

                $this->load->model('account/customer');

                $customer = $this->model_account_customer->getCustomerByEmail($this->request->post['email']);
                if($customer) {
                
                    $hashIdCustomer = Crypto::criptografarAES256($customer['customer_id'], Crypto::CAES256);

                    $pageToRedirect = $this->url->link('account/success', 'token=' . $hashIdCustomer, 'SSL');

                    $email = $customer["email"];

                    $name = $customer["firstname"];

                    $subject = sprintf($this->language->get('text_subject'), $name);
                    $message = sprintf($this->language->get('text_message'), $pageToRedirect, $this->language->get('text_active_account'));

                    $this->emailvalidate->sendEmail($email, $name, $subject, $message);

                    $response['success'] = $this->language->get('text_email_validate_success');
                }else{
                    unset($response['redirect']);
                    $response['warning'] = "Usuário não encontrado";
                }
            } else {
                $response['errors'] = $this->validate();
            }
            return $this->response->setOutputJson($response);
        }
    }

    public function app()
    {
        if ($this->ftrgeralregistry->isApp()) {
            $this->document->addScriptApp(
                array(
                    'catalog/view/theme/appmobile/public/js/page.emailvalidate.js',
                )
            );
        }
    }

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

        $errors = $this->validate->execute([
            'email' => [
                'value' => $data["email"],
                'validates' => [
                    [
                        'method' => 'isEmail',
                        'message' => 'O email deve ser valido',
                    ],
                    [
                        'method' => 'isEmpty',
                        'message' => 'Informe o email por favor'
                    ]
                ],
            ]
        ]);

        return $errors;
    }
}