<?php
$path = '../../';
$noauth = true;
require_once $path .'core/includes/header.inc.php';

use App\Src\Encryption;

// Redirect to /admin (dashboard) if user is logged in and trying to access /admin/login.php
if (!empty($_SESSION['adminId']) && $_SESSION['adminId'] > 0) {
    header("Location: /admin");
    exit();
}

if (!isset($_REQUEST['redir'])) {
    $_REQUEST['redir'] = '';
} else {
    // put up a 401 because the client would have landed here with the above params set only if he was doing something
    // that needed authorization based on admin area auth so that ajax scripts can handle accordingly
    header("HTTP/1.0 401 Unauthorized");
}

$adminuser = new AdminUser();

$page_meta['title'] = "Login";

if (isset($_POST['login'])) {
    // error reporting
    if ($_POST['username']=='') {
        $errors[]='Please enter a username.';
    } else {
        $username = $_POST['username'];
    }
    if ($_POST['password']=='') {
        $errors[]='Please enter a password.';
    } else {
        $password = $_POST['password'];
    }

    if (!CSRF::checkToken('admin_login')) {
        $errors['csrf'] = "Login failed, please try again";
    }

    // if no errors try to login
    if (empty($errors)) {
        // Attempt login
        if ($adminuser->login($username, $password, false)) {
            // Successful login actions
            \Mtc\Core\AdminUser::query()
                ->where('id', $_SESSION['adminId'])
                ->update(['last_login' => date('Y-m-d H:i:s')]);

            // Attempt redirect
            $redirect = !empty($_POST['redir']) ? urldecode($_POST['redir']) : '/admin/index.php';
            anti_phish_redirect($redirect);
        } else {
            $errors[] = $adminuser->error;
        }
    }
}

require_once $path . 'core/admin/templates/adminheader.html.php';
?>
<ul class="breadcrumbs el">
    <li><a href="/admin/">Home</a> /</li>
    <li class="end">Login</li>
</ul>

<h1>Admin Login</h1>

<form class="style" action="login.php" method="post">
    <?php
        if (!empty($errors) ) {
            showerrors($errors);
        }
    ?>
    <div class="row">
        <label for="username">Username</label>
        <input type="text" autofocus name="username" id="username" value="<?php
        if (!empty($_POST['username'])) {
            echo clean_page($_POST['username']);
        }
        ?>" />
    </div>
    <div class="row">
        <label for="password">Password</label>
        <input type="password" name="password" id="password" value="" />
    </div>

    <div class="row">
        <?= CSRF::token('admin_login'); ?>
        <input type="hidden" name="redir" id="redir" value="<?=clean_page($_REQUEST['redir'])?>" />
        <input type="submit" id="submitBtn" name="login" value="Login" />
    </div>
</form>

<?php
require_once $path . 'core/admin/templates/adminfooter.html.php';
