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

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

		$this->language->load('common/forgotten');

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

		$this->load->model('user/user');

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
			$this->language->load('mail/forgotten');
			if ($this->model_user_user->getTotalUsersByEmail($this->request->post['user']) > 0) {
                $user = ['email' => $this->request->post['user'],
                    'type' => 'email'];
            } else {
                $user = ['email' => $this->model_user_user->getUserByUsername($this->request->post['user'])['email'] ?? '',
                    'type' => 'user_name'];
            }

            if (isset($user['email']) && $user['email'] != '') {
                $code = sha1(uniqid(mt_rand(), true));

                $this->model_user_user->editCode($user['email'], $code);

                $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 .= sprintf($this->language->get('text_change'), $this->config->get('config_name')) . "\n\n";
                $message .= $this->url->link('common/reset', 'code=' . $code, 'SSL') . "\n\n";
                $message .= sprintf($this->language->get('text_ip'), $this->request->server['REMOTE_ADDR']) . "\n\n";

                try {
                    $mail = new Mail();
                    $mail->protocol = $this->config->get('futura_email_noreply_protocol');
                    $mail->parameter = $this->config->get('futura_email_noreply_parameter');
                    $mail->hostname = $this->config->get('futura_email_noreply_hostname');
                    $mail->username = $this->config->get('futura_email_noreply_username');
                    $mail->password = Crypto::descriptografarAES256($this->config->get('futura_email_noreply_password'), Crypto::CAES256);
                    $mail->port = $this->config->get('futura_email_noreply_port');
                    $mail->timeout = $this->config->get('futura_email_noreply_timeout');
                    $mail->setFrom($this->config->get('futura_email_noreply_username'));
                    $mail->setTo($user['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);

                    if($user['type'] == 'user_name') {
                        $email_atpos = strrpos($user['email'], '@');
                        $email_char = intval($email_atpos * 0.25) ;
                        $email_formatted = substr( $user['email'], 0, $email_char)
                            . str_repeat('*', $email_atpos - $email_char * 2)
                            . substr($user['email'], $email_atpos - $email_char);
                        $this->session->data['email_forgotten'] = $email_formatted;
                    } else {
                        $this->session->data['email_forgotten'] = $user['email'];
                    }
                    $this->redirect($this->url->link('common/forgotten', '&success=true', 'SSL'));

                } catch (Exception $e) {
                    $this->error['warning'] = 'Erro ao reenviar senha tente novamente mais tarde!';
                    if ($this->config->get('config_error_log')) {
                        $this->log->write('Error ao reenviar senha admin: ' . $e);
                    }

                }
            } else {
                $this->error['warning'] = $this->language->get('error_email');
            }
		}

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

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

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

		$this->data['heading_title'] = $this->language->get('heading_title');
		$this->data['text_back'] = $this->language->get('text_back');
		$this->data['text_your_email'] = $this->language->get('text_your_email');
		$this->data['text_user'] = $this->language->get('text_user');
		$this->data['entry_user'] = $this->language->get('entry_user');
		$this->data['button_reset'] = $this->language->get('button_reset');
		$this->data['button_send'] = $this->language->get('button_send');
		$this->data['button_cancel'] = $this->language->get('button_cancel');

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

		if(isset($this->request->get['success'])){
            $this->data['success'] = $this->request->get['success'];
        }else{
            $this->data['success'] = false;
        }

        if(isset($this->session->data['email_forgotten'])){
            $this->data['mensage'] = sprintf($this->language->get('text_msg'), $this->session->data['email_forgotten']);
           unset($this->session->data['email_forgotten']);
        }else{
            $this->data['email_forgotten'] = false;
        }

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

		$this->data['cancel'] = $this->url->link('common/login', '', 'SSL');

		if (isset($this->request->post['user'])) {
      		$this->data['user'] = $this->request->post['user'];
		} else {
      		$this->data['user'] = '';
    	}

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

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

	protected function validate() {
		if (!isset($this->request->post['user']) || ($this->model_user_user->getTotalUsersByUsername($this->request->post['user']) <= 0
            && $this->model_user_user->getTotalUsersByEmail($this->request->post['user']) <= 0)) {
			$this->error['warning'] = $this->language->get('error_user');
		}

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