<?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'])){

    $N_token = isset($_GET['token']) ? $_GET['token'] : "";
    if($N_token == ""){
        $_SESSION['message_log'] = "User Token Not Found.";
        $_SESSION['alert_log'] = "error";
        header("Location:".$path['login']);
    } else {
        $N_email = isset($_GET['email']) ? $_GET['email'] : "";
        $detail = $obj_user->get_data_create($obj_crud, $N_token);
        if(is_array($detail)){
            //nothing
        } else {
            $_SESSION['message_log'] = "User Token Not Found.";
            $_SESSION['alert_log'] = "error";
            header("Location:".$path['login']);
        }
    }

    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'] == 'activate'){

        $O_email = $obj_crud->escape_string(check_input($_POST['email']));
        $O_name = $obj_crud->escape_string(check_input($_POST['name']));
        $O_password = $obj_crud->escape_string(check_input($_POST['password']));
        $O_token = $obj_crud->escape_string(check_input($_POST['token']));

        $enc_pass = encrypt_key($O_password);

        $result = $obj_user->activate_acc($obj_crud, $O_email, $O_token, $enc_pass);
        if($result != 0){
            //send mail
            $body_message = $obj_mail->mail_success_activation($global['logo-url'], $O_name, $O_password);
            $subject_message = "RMS Account Activation";
            $sent_customer = smtp_mail($N_email, $smtp['url'], $smtp['from'], $smtp['password'], $smtp['from_name'], $subject_message, $body_message, $smtp['reply-cs']);
            //login
            $result = $obj_user->login($obj_crud, $O_email, $enc_pass);
            if($result == 1){
                $_SESSION['status'] = "Success Activate Account.<br>Welcome in Ruas Management System.";
                $_SESSION['alert'] = "success";
                header("Location:".$path['dashboard']);
            }else{
                $_SESSION['message_log'] = "Login to access our system!";
                $_SESSION['alert_log'] = "error";
                header("Location:".$path['login']);
            }
        }else{
            $_SESSION['message_front'] = "Failed activate account. Something wrong with your input!";
            $_SESSION['alert_front'] = "error";
            header("Location:".$path['login-activate']."?token=".$O_token);
        }
    }
}
?>