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

use App\Src\Encryption;
use Mtc\Core\Admin\TotpService;

// 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)) {
            $pendingId = $_SESSION['adminId'];
            session_regenerate_id(true);

            // Successful login actions — update session_id to match the regenerated ID
            \Mtc\Core\AdminUser::query()
                ->where('id', $pendingId)
                ->update(['last_login' => date('Y-m-d H:i:s'), 'session_id' => session_id()]);

            // MTC staff and bypassed environments skip 2FA
            if (TotpService::isExempt($username)) {
                $redirect = !empty($_POST['redir']) ? urldecode($_POST['redir']) : '/admin/index.php';
                if (!preg_match('#^/(?!/)#', $redirect)) {
                    $redirect = '/admin/index.php';
                }
                anti_phish_redirect($redirect);
            }

            // Move to pending 2FA state
            unset($_SESSION['adminId']);
            unset($_SESSION['mtcadminarea']);
            $_SESSION['admin_2fa_pending_id'] = $pendingId;
            $_SESSION['admin_2fa_pending_at'] = time();

            $loggedInUser = \Mtc\Core\AdminUser::query()->find($pendingId);
            $redirectParam = !empty($_POST['redir']) ? '?redir=' . urlencode($_POST['redir']) : '';

            if (!empty($loggedInUser->totp_secret)) {
                header('Location: /admin/2fa_verify.php' . $redirectParam);
            } else {
                header('Location: /admin/2fa_setup.php');
            }
            exit();
        } 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';
