<?php
namespace src\controllers;

use \src\Config;
use \core\Controller;
use \src\handlers\LoginHandler;

use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\PHPMailer;

class LoginController extends Controller {

    public function signin() {
        $flash = '';
        $flash_type = '';
        if(!empty($_SESSION['flash'])) {
            $flash = $_SESSION['flash'];
            $flash_type = $_SESSION['flash_type'];
            $_SESSION['flash'] = '';
            $_SESSION['flash_type'] = '';
        }

        $this->render('login', [
            'flash' => $flash,
            'flash_type' => $flash_type
        ]);
    }

    public function signinAction() {
        $email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
        $password = filter_input(INPUT_POST, 'password');

        if($email && $password) {
            $token = LoginHandler::verifyLogin($email, $password);

            if($token) {
                $_SESSION['token'] = $token;
                $this->redirect('/');
            } else {
                $_SESSION['flash'] = 'E-mail e/ou senha incorretos!';
                $_SESSION['flash_type'] = 'alert-danger';
                $this->redirect('/login');
            }

        } else {
            $_SESSION['flash'] = 'Preencha os dados de login!';
            $_SESSION['flash_type'] = 'alert-warning';
            $this->redirect('/login');
        }
    }

    public function forgot() {
        $this->render('forgot');
    }

    public function forgotAction() {
        $email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);

        if($email) {
            $idUser = LoginHandler::verifyForgetPassword($email);

            if($idUser) {
                $link = md5($idUser['id']);
                LoginHandler::saveLinkForget($idUser['id'], $link);                
                $this->sendConfirmation($email, $link);

            } else {
                $_SESSION['flash'] = 'E-mail não pode ser enviado!';
                $_SESSION['flash_type'] = 'alert-warning!';
                $this->redirect('/forgot');
            }

        } else {
            $this->redirect('/forgot');
        }
    }

    private function sendConfirmation($email, $link) {
        $mail = new PHPMailer();

        try {
            $mail->SMTPOptions = [
                'ssl' => [
                    'verify_peer' => false,
                    'verify_peer_name' => false,
                    'allow_self_signed' => true
                ]
            ];
            $mail->isSMTP();
            //$mail->SMTPDebug = 3;

            $mail->Host = 'mail.supporteagronegocios.com.br';
            $mail->SMTPAuth = true;
            $mail->Username = 'app@supporteagronegocios.com.br';
            $mail->Password = 'n}8gXccy0L;?';
            $mail->Port = 587;
            $mail->SMTPSecure = 'tls';
            $de = 'app@supporteagronegocios.com.br';

            $mail->setFrom($de, utf8_decode('Supporte Agronegócios')); // De

            $mail->addAddress($email); //Para

            $mail->addReplyTo($de, utf8_decode('Não responder este!'));

            $mail->isHTML(true);

            $mail->Subject = utf8_decode('Solicitação de alteração de senha');

            $redirect = Config::SITE_URL.'forgotlink?h='.$link;

            $logo = Config::SITE_URL.'assets/images/logo_login.jpg';

            $bodyEmail = utf8_decode(
                '
                <head>
                    <meta charset="UTF-8">
                    <meta name="viewport" content="width=device-width, initial-scale=1.0">
                    <meta http-equiv="X-UA-Compatible" content="ie=edge">
                </head>
                <body style="margin: 0;font-size: 18px;line-height: 22px;background-color: #CCC;">
                    <div class="container" style="margin: 10px auto 0;width: 400px;">
                        <div class="content-area" style="width: 400px;float:left;box-sizing: border-box;padding: 20px;background-color: #FFF;border-radius: 3px;border: 2px solid #4682B4;">
                            <div class="header" style="width: 100%;float: left;text-align: center;">
                                <h6 style="font-size: 24px;margin: 15px 0 0;">Alteração de senha</h6>
                            </div>
                            <div class="message" style="margin-top: 20px;width: 100%;float: left;">
                                <p style="width: 100%;float: left;margin: 5px 0">Olá '.$email.'</p>
                                <p style="width: 100%;float: left;margin: 5px 0">Clique no link para alterar sua senha.</p>
                                <a href="'.$redirect.'" style="width: 100%;float: left;margin: 5px 0">Clique aqui.</a>
                            </div>
                            <div class="copyright" style="width: 100%;text-align: center;margin-top: 50px;float: left;">
                                <img src='.$logo.' style="width: 50%">
                            </div>
                        </div>
                    </div>
                </body>                 
                '
            );

            $mail->Body = $bodyEmail;

            if ($mail->send()) {
                $_SESSION['flash'] = 'Verifique seu e-mail para proseguir!';
                $_SESSION['flash_type'] = 'alert-info';
                $this->redirect('/login');

            } else {
                $_SESSION['flash'] = 'Ocorreu um erro inesperado. Tente novamente mais tarde!';
                $_SESSION['flash_type'] = 'alert-info';
                $this->redirect('/login');
            }

        } catch(Exception $e) {
            echo '<p>Não foi possivel enviar o email.</p>';
            echo 'Error: ' . $mail->ErrorInfo;
        }
    }

    public function forgotLink() {
        if(!empty($_GET['h'])) {
            $linkHash = addslashes($_GET['h']);

            if(LoginHandler::verifyLink($linkHash)) {
                $_SESSION['update_pass'] = $linkHash;
                $this->render('update_password');
            } else {
                $_SESSION['flash'] = 'Link já utilizado!';
                $_SESSION['flash_type'] = 'alert-info';
                $this->redirect('/login');
            }            
        }
    }

    public function update() {
        $pass = filter_input(INPUT_POST, 'password');

        if(strlen($pass) >= 6) {
            $newPassword = md5($pass);
            LoginHandler::update($newPassword, $_SESSION['update_pass'], null);
            $_SESSION['flash'] = 'Senha alterada com sucesso!';
            $_SESSION['flash_type'] = 'alert-success';
        } else {
            $_SESSION['flash'] = 'Senha muito curta!';
            $_SESSION['flash_type'] = 'alert-info';            
        }

        $this->redirect('/login');
    }

    public function logout() {
        unset($_SESSION['token']);
        $this->redirect('/');
    }

}