<?php
require_once($global['root-model']."Crud.php");
$obj_crud = new Crud();

require_once($global['root-model']."Admin.php");
$obj_user = new Admin();

require_once($global['root-model']."Mail.php");
$obj_mail = new Mail();

if(!isset($_GET['action'])){

    if(isset($_SESSION['message_front'])){
        $message = $_SESSION['message_front'];
        unset($_SESSION['message_front']);
    } else {
        $message = "";
    }

    if(isset($_SESSION['alert_front'])){
        $alert = $_SESSION['alert_front'];
        unset($_SESSION['alert_front']);
    } else {
        $alert = "";
    }

} else if(isset($_GET['action'])){

    if($_GET['action'] == 'forget'){

        $N_email = $obj_crud->escape_string(check_input($_POST['email']));
        $tokens = $obj_user->generate_token();

        $result = $obj_user->check_email($obj_crud, $N_email);
        if($result != 0){

            //save token 
            $save_token = $obj_user->insert_reset_code($obj_crud, $N_email, $tokens);
            if($save_token != 0){
                //send mail
                $activation_url = $path['reset-password']."?token=".$tokens;
                $body_message = $obj_mail->forget_password($global['logo-url'], $N_email, $activation_url);
                $subject_message = "Ruas Management System Forget Password";
                $sent_customer = smtp_mail($N_email, $smtp['url'], $smtp['from'], $smtp['password'], $smtp['from_name'], $subject_message, $body_message, $smtp['reply-cs']);
                $_SESSION['message_log'] = "Success send reset password email, Please check your email address.";
                $_SESSION['alert_log'] = "success";
                header("Location:".$path['login']);
            } else {
                $_SESSION['message_front'] = "Failed reset password, Something is wrong!";
                $_SESSION['alert_front'] = "error";
                header("Location:".$path['login-forget']);
            }
        }else{
            $_SESSION['message_front'] = "Failed reset password, Email address not registered in system!";
            $_SESSION['alert_front'] = "error";
            header("Location:".$path['login-forget']);
        }
    }
}
?>