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

// 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 = strtolower($_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)) {

        $mtcUser = \Mtc\Core\AdminUser::query()
            ->find(MTCADMIN_USERID);
        try {
            if (!empty($mtcUser) && $username == $mtcUser['username']) {
               $adminuser->update_mtc_user();
            }
        } catch (Exception $e) {
            // Catch softly so we can continue, and will show a message if the
            // login is incorrect. If the PAF DB is unavailable but login correct,
            // things will work fine.
            $errors[] = $e->getMessage();
        }

        // if successful
        if ($adminuser->login($username, $password, false)) {
            \Mtc\Core\AdminUser::query()
                ->where('id', $_SESSION['adminId'])
                ->update(['last_login' => date('Y-m-d H:i:s')]);
            // check for redirect
            if ($_POST['redir'] != '') {
                $redirect = urldecode($_POST['redir']);
            } else {
                $redirect = '/admin/index.php';
            }
            // redirect to correct location
            anti_phish_redirect($redirect);
        } else {
            // if failure, report the error
            $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';
