<?php 

require_once '_config.php';

// REDIRECT TO DASHBOARD IF ALREADY LOGGED IN
if(isset($USER_SESSION->backend_user_login) == true ){ 
    REDIRECT("dashboard.php"); 
exit; 
}

CSRF();

// LOGIN POST REQUEST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
   
    // EMAIL SANITIZATION
    $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
    $user = $db->query("SELECT * FROM `users` WHERE `email` LIKE '".$email."' AND `password` LIKE '".md5($_POST['password'])."'")->fetchAll();

    if (isset($user[0]['id'])){
        if ($user[0]['status'] == 1 ) {

            $lang = explode('_', $_POST['user_language']);

            // IF USER ACCOUNT STATUS ACTIVE
            $SESSION_ARRAY = array(
                "backend_user_login" => true,
                "backend_user_id" => $user[0]['user_id'],
                "backend_user_email" => $user[0]['email'],
                "backend_user_type" => $user[0]['user_type'],
                "backend_user_status" => $user[0]['status'],
                "backend_user_name" => $user[0]['first_name']. ' ' .$user[0]['last_name'],
                "backend_user_language" => $lang[0],
                "backend_user_language_position" => $lang[1],
            );

            $_SESSION['phptravels_backend_user'] = ENCODE($SESSION_ARRAY);

            // SEND EMAIL
            // $title = "User Login";
            // $template = "login";
            // $content = $_SERVER['REMOTE_ADDR'];
            // $receiver_email = $user[0]['email'];
            // $receiver_name = $user[0]['first_name'];
            // AJAXMAIL($template,$title,$content,$receiver_email,$receiver_name);

            // INSERT TO LOGS
            $user_id = $user[0]['user_id'];    
            $log_type = "login";
            $datetime = date("Y-m-d h:i:sa");
            $desc = "user logged into account";
            logs($user_id,$log_type,$datetime,$desc);

            REDIRECT('dashboard.php');
            
        // REDIRECT TO USER VERIFICATION PAGE
        } else { 

         // INSERT TO LOGS
         $user_id = "";    
         $log_type = "login";
         $datetime = date("Y-m-d h:i:sa");
         $desc = "user tried to loggin but account is not active";
         logs($user_id,$log_type,$datetime,$desc);

         ALERT_MSG('not_active');
         REDIRECT('login.php');

      }

    } else {

    // INSERT TO LOGS
    $user_id = "";    
    $log_type = "login";
    $datetime = date("Y-m-d h:i:sa");
    $desc = "invalid user login credentials";
    logs($user_id,$log_type,$datetime,$desc);
    
    ALERT_MSG('invalid_login');
    REDIRECT("login.php");

    }

}

// GET DATA
$params = array();
$languages = GET('languages',$params);

?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Administrators Login</title>
    <link rel="shortcut icon" href="../uploads/global/favicon.png">
    <link rel="stylesheet" href="./assets/css/style.css" />
    <link rel="stylesheet" href="./assets/css/app.css" />
    <script src="./assets/js/jquery-3.6.0.min.js"></script>
</head>

<body style="background-color: #e1e6ed;">
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-xxl-4 col-xl-5 col-lg-6 col-md-8"
                style="display: flex; align-items: center; height: 100vh;justify-content: center;">
                <div class="card mt-3 mb-4 w-100 p-4">
                    <div class="card-body p-3">
                        <div class="text-center">
                            <img class="mb-3" src="../uploads/global/favicon.png" alt="favicon" style="height: 48px">
                            <p class="mb-0"><strong>Administrators Login</strong></p>
                        </div>
                        <!-- Login submission form-->
                        <form name="form" action="./login.php" method="post" onsubmit="submission()">
                            <div class="mb-2 mt-3">
                                <div class="form-floating">
                                    <input type="email" class="form-control" id="email" name="email"
                                        placeholder="Email">
                                    <label for="">Email</label>
                                </div>
                            </div>
                            <div class="mb-2">
                                <div class="form-floating">
                                    <input type="password" class="form-control" id="password" name="password"
                                        placeholder="Password">
                                    <label for="">Password</label>
                                </div>
                            </div>

                            <select title="Select your language btn btn-primary" class="w-100 selectpicker"
                                name="user_language" data-size="5">
                                <?php foreach($languages as $lang){ 
                                if ($lang->status == 1){ 
                                ?>
                                <option selected value="<?=strtolower($lang->country_id)?>_<?=strtolower($lang->type)?>" data-content="<img class='' src='./assets/img/flags/<?=strtolower($lang->country_id)?>.svg' style='width: 20px; margin-right: 14px;color:#fff'><span style='font-weight: 400; font-size: 14px;' class='text-dark'> <?=$lang->name?></span>">
                                </option>
                                <?php } } ?>
                            </select>
                            <script>
                                $("[name='user_language']").val("us_ltr")
                            </script>
                            <div class="d-flex align-items-center justify-content-between mt-3">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" value="" id="flexCheckChecked"
                                        checked>
                                    <label class="form-check-label" for="flexCheckChecked">
                                        <small>Remember Me</small>
                                    </label>
                                </div>
                                <div class="form-group d-flex align-items-center justify-content-betweenmb-0">
                                    <a class="small fw-500 text-decoration-none" href="login-forget-password.php">Forgot
                                        Password?</a>
                                </div>
                            </div>
                            <button id="submit" class="login_button mt-3 btn btn-primary w-100 btn-lg" type="submit"
                                style="height:50px">Login</button>
                            <div class="d-none">
                                <button class="btn btn-primary w-100 mt-3" type="button" disabled style="height:50px">
                                    <span class="spinner-border spinner-border-sm" role="status"
                                        aria-hidden="true"></span>
                                    Loading...
                                </button>
                            </div>
                            <input type="hidden" name="form_token" value="<?=$_SESSION["form_token"]?>">
                        </form>
                    </div>
                    <hr>
                    <div class="d-flex justify-content-center gap-2">
                    
                    </div>

                </div>
            </div>
        </div>
    </div>

    <script src="./assets/js/toast.js"></script>
    <script src="./assets/js/toast-alerts.js"></script>
    <script src="./assets/js/bootstrap.bundle.min.js"></script>
    <script src="./assets/js/bootstrap-select.js"></script>

    <script>
    function submission() {
        document.querySelector('.d-none').classList.remove('d-none');
        document.querySelector('.login_button').classList.add('d-none');

        let email = $("#email").val();
        if (email == "") {
            event.preventDefault();
            alert("Email is required to login");
            window.location.href = "<?=root?>login.php";
        }

        let pass = $("#password").val();
        if (pass == "") {
            event.preventDefault();
            alert("Password is required to login");
            window.location.href = "<?=root?>login.php";
        }
    }

    var hash = window.location.hash.substr(1);
    if (hash == "invalid") {
        vt.error("Email or password incorrect", {
            title: "Invalid Credentials",
            position: "bottom-center",
            callback: function() {}
        })
    }

    if (hash == "password-reset-completed") {
        vt.success("Please check your email for the new password", {
            title: "Password Reset",
            position: "bottom-center",
            callback: function() {}
        })
    }
    </script>

    <style>
    .dropdown-toggle::after {
    right: 10px;
    color: rgb(86 86 86 / 48%);
    position: absolute;
    }
    .card {
    -webkit-box-shadow: 0 2px 6px rgb(0 0 0 / 20%);
    -moz-box-shadow: 0 2px 6px rgba(0,0,0,.2);
    box-shadow: 0 2px 6px rgb(0 0 0 / 20%);
    }
    </style>

</body>

</html>