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

	public function index() {

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

		$this->loadscripts();

		$this->children = array(
			'common/footer',
			'common/header'
		);

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

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

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

		if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/account/forgotten.tpl')) {
			$this->template = $this->config->get('config_template') . '/template/account/forgotten.tpl';
		} else {
			$this->template = 'default/template/account/forgotten.tpl';
		}

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

	protected function validate() {
	

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

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

		if (!$this->request->post['email_forgotten']) {
			$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['warning'] = $this->language->get('error_email_invalid');
		} elseif (!$this->model_account_customer->getTotalCustomersByEmail($this->request->post['email_forgotten'])) {
			$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($this->registry ?? null);
				$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!';
				if($this->config->get('config_error_log')){
					$logData = [
						'event'    => 'AccountForgotten::email',
						'message'  => 'Erro ao reenviar senha',
						'exception'=> [
							'type'    => get_class($e),
							'message' => $e->getMessage(),
							'code'    => $e->getCode(),
							'file'    => $e->getFile(),
							'line'    => $e->getLine(),
							'trace'   => $e->getTraceAsString()
						],
						'datetime' => date('c'), // data/hora no padrão ISO
					];
					$this->log->write(json_encode($logData, JSON_UNESCAPED_UNICODE));
				}
			}


		}

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

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

	public function loadscripts(){

		// Adiciona o Plugin que mostra o qualidade da senha - por Henrique R. Pohl
		$this->document->addScript('catalog/view/theme/vista/public/js/medidor-de-senha.js');

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

	}

}
