<?php
class ControllerAccountForgottenNew extends Controller
{
    private $error = array();

    public function index()
    {
        if ($this->customer->isLogged()) {
            $this->redirect($this->url->link('account/account', '', 'SSL'));
        }

        $language = $this->language->load('account/forgotten_new');
        $this->data = array_merge($this->data, $language);

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

        $this->data['action'] = $this->url->link('account/forgotten_new/email', '', 'SSL');
    }

    protected function validate()
    {
        $this->load->model('account/customer');

        $language = $this->language->load('account/forgotten_new');
        $this->data = array_merge($this->data, $language);

        if (!$this->request->post['email_forgotten']) {
            $this->error['email_forgotten'] = [$this->language->get('error_email')];
            $this->error['warning'] = $this->language->get('error_email');
        } elseif (
            (utf8_strlen($this->request->post['email_forgotten']) > 96) || !preg_match('/^[^\@]+@.*\.[a-z]{2,6}$/i', $this->request->post['email_forgotten']) || !filter_var($this->request->post['email_forgotten'], FILTER_VALIDATE_EMAIL) || !preg_match('/^[a-zA-Z0-9\._-]+@/', $this->request->post['email_forgotten'])
        ) {
            $this->error['email_forgotten'] = [$this->language->get('error_email_invalid')];
            $this->error['warning'] = $this->language->get('error_email_invalid');
        } elseif (!$this->model_account_customer->getTotalCustomersByEmail($this->request->post['email_forgotten'])) {
            $this->error['email_forgotten'] = [$this->language->get('error_email_not_found')];
            $this->error['warning'] = $this->language->get('error_email_not_found');
        }

        if (!$this->error) {
            return true;
        } else {
            return false;
        }
    }

    public function email()
    {
        if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
            $this->language->load('mail/forgotten');

            $password = substr(sha1(uniqid(mt_rand(), true)), 0, 10);

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

            $this->model_account_customer->editPassword($this->request->post['email_forgotten'], $password);

            $subject = sprintf($this->language->get('text_subject'), $this->config->get('config_name'));

            $message  = sprintf($this->language->get('text_greeting'), $this->config->get('config_name')) . "\n\n";
            $message .= $this->language->get('text_password') . "\n\n";
            $message .= $password;

            try {
                $mail = new Mail();
                $mail->protocol  = $this->config->get('config_mail_protocol');
                $mail->parameter = $this->config->get('config_mail_parameter');
                $mail->hostname  = $this->config->get('config_smtp_host');
                $mail->username  = $this->config->get('config_smtp_username');
                $mail->password  = $this->config->get('config_smtp_password');
                $mail->port      = $this->config->get('config_smtp_port');
                $mail->timeout   = $this->config->get('config_smtp_timeout');
                $mail->setTo($this->request->post['email_forgotten']);
                $mail->setFrom($this->config->get('config_email'));
                $mail->setSender($this->config->get('config_name'));
                $mail->setSubject(html_entity_decode($subject, ENT_QUOTES, 'UTF-8'));
                $mail->setText(html_entity_decode($message, ENT_QUOTES, 'UTF-8'));
                $mail->send(true);

                $this->data['success'] = $this->language->get('text_success');
            } catch (Exception $e) {
                $this->error['warning'] = 'Erro ao reenviar senha tente novamente mais tarde!';
                $this->error['message'] = 'As configurações de envio de email não estão corretas. Verifique com o administrador do site.';
                if ($this->config->get('config_error_log')) {
                    $this->log->write('Error ao reenviar senha: ' . $e);
                }
            }
        }



        if ($this->error) {
            $this->data['errors'] = $this->error;
        } else {
            $this->data['warning'] = '';
        }

        $this->response->setOutput(json_encode($this->data));
    }
}
