<?php

use Mtc\Core\Admin\TotpService;
use Mtc\Core\RateLimit;

$path = '../../../';
require $path . 'core/includes/header.inc.php';

// initialize variables
if (!isset($_REQUEST['action'])) {
    $_REQUEST['action'] = null;
}
$errors = [];
$show_sudo_prompt = false;

$pagename = 'Admin User';
$table = 'admin_users';
$page_meta['title'] = 'Manage ' . $pagename . 's';

// Sudo check helper
$sudo_timeout = 300;
$has_sudo = !empty($_SESSION['admin_2fa_sudo_at']) && (time() - $_SESSION['admin_2fa_sudo_at']) < $sudo_timeout;
$is_2fa_exempt = TotpService::isExempt($adminuser->user['username'] ?? '');
$currentAdminModel = \Mtc\Core\AdminUser::query()->find($adminuser->user['id']);
$needs_sudo = !$is_2fa_exempt && $currentAdminModel && !empty($currentAdminModel->totp_secret) && !$has_sudo;

// Handle sudo verification POST
$sudoRateLimitKey = '2fa_sudo_' . $adminuser->user['id'];
$sudoMaxAttempts = 5;
$sudoLockoutSeconds = 120;

if ($_REQUEST['action'] === 'sudo_verify' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    if (RateLimit::isLocked($sudoRateLimitKey, $sudoLockoutSeconds, $sudoMaxAttempts)) {
        $errors[] = 'Too many failed attempts. Please wait 2 minutes before trying again.';
        $show_sudo_prompt = true;
        $_REQUEST['action'] = 'sudo_verify';
    } elseif (!CSRF::checkToken('admin_sudo_2fa_manage')) {
        $errors[] = 'Verification failed, please try again.';
    } else {
        $code = preg_replace('/\s+/', '', $_POST['totp_code'] ?? '');
        $service = new TotpService();
        $timestamp = (!empty($code) && $currentAdminModel)
            ? $service->verifyCode($currentAdminModel->totp_secret, $code, $currentAdminModel->totp_last_used_at)
            : false;
        if ($timestamp !== false) {
            // Save the timestamp to reject replay of this code
            $currentAdminModel->forceFill(['totp_last_used_at' => $timestamp])->save();
            $_SESSION['admin_2fa_sudo_at'] = time();
            // Redirect to the original action
            $redirectAction = $_POST['pending_action'] ?? '';
            $redirectUserId = (int) ($_POST['pending_userid'] ?? 0);
            if ($redirectAction === 'loginas' && $redirectUserId > 0) {
                header('Location: manage.php?action=loginas&userid=' . $redirectUserId);
                exit();
            }
            header('Location: manage.php');
            exit();
        } else {
            RateLimit::logAttempt($sudoRateLimitKey);
            $errors[] = 'Invalid 2FA code. Please try again.';
            $show_sudo_prompt = true;
            $_REQUEST['action'] = 'sudo_verify';
        }
    }
}

/*
    Delete
*/
if ($_REQUEST['action'] == 'delete' && is_numeric($_REQUEST['delete_id'])) {
    \Mtc\Core\AdminUser::query()
        ->where('id', $_REQUEST['delete_id'])
        ->delete();
}

if ($_REQUEST['action'] == 'loginas' && isset($_REQUEST['userid']) && is_numeric($_REQUEST['userid'])) {
    // Require sudo for login-as
    if ($needs_sudo) {
        $show_sudo_prompt = true;
    } else {
        $_SESSION['admin_impersonating_from'] = $adminuser->user['id'];
        $_SESSION['adminId'] = $_REQUEST['userid'];
        \Mtc\Core\AdminUser::query()
            ->where('id', $_REQUEST['userid'])
            ->update([
                    'session_id' => session_id()
            ]);
        header("Location: /admin/index.php");
        exit();
    }
}

$roles = \Mtc\Core\Admin\Role::all();

include $path . 'core/admin/templates/adminheader.html.php';

?>

<ul class="breadcrumbs el">
    <li><a href="/admin/">Home</a> /</li>
    <li class="end">Manage <?=$pagename?>s</li>
</ul>

<h1>Manage <?=$pagename?>s</h1>

<?php

include 'tabnav.php';

if (sizeof($errors) > 0) {
    showerrors($errors);
}

if ($show_sudo_prompt) {
    $pendingUserId = (int) ($_REQUEST['userid'] ?? 0);
    ?>
    <div class="tfa-container tfa-sudo-container">
        <div class="tfa-card">
            <div class="tfa-icon">
                <i class="fa fa-lock"></i>
            </div>
            <h1>Confirm Your Identity</h1>
            <p>Enter your 2FA code to continue.</p>

            <form action="manage.php" method="POST" id="tfaForm">
                <div class="tfa-digits" id="tfaDigits">
                    <input type="text" class="tfa-digit" data-index="0" inputmode="numeric" maxlength="1" autocomplete="off" autofocus />
                    <input type="text" class="tfa-digit" data-index="1" inputmode="numeric" maxlength="1" autocomplete="off" />
                    <input type="text" class="tfa-digit" data-index="2" inputmode="numeric" maxlength="1" autocomplete="off" />
                    <div class="tfa-digit-separator"></div>
                    <input type="text" class="tfa-digit" data-index="3" inputmode="numeric" maxlength="1" autocomplete="off" />
                    <input type="text" class="tfa-digit" data-index="4" inputmode="numeric" maxlength="1" autocomplete="off" />
                    <input type="text" class="tfa-digit" data-index="5" inputmode="numeric" maxlength="1" autocomplete="off" />
                </div>
                <input type="hidden" name="totp_code" id="totp_code" value="" />
                <?= CSRF::token('admin_sudo_2fa_manage') ?>
                <input type="hidden" name="action" value="sudo_verify" />
                <input type="hidden" name="pending_action" value="loginas" />
                <input type="hidden" name="pending_userid" value="<?= $pendingUserId ?>" />
            </form>

            <p class="tfa-help"><i class="fa fa-info-circle"></i> Verification is valid for 5 minutes</p>
        </div>
    </div>
    <?php

    require_once $path . 'core/admin/templates/adminfooter.html.php';
    exit();
}

$adminUsers = \Mtc\Core\AdminUser::query()
    ->orderBy('id', 'DESC')
    ->when(!$adminuser->isMtcAdmin(), function ($query) {
        $query->where('id', '!=', MTCADMIN_USERID);
    })
    ->get();

if ($adminUsers->count() > 0) {

    if (sizeof($errors) == 0 && isset($_REQUEST['action'])) {
        echo showmsg("Record updated", "success", $path);
    }

    ?>
    <form action="<?= $_SERVER['PHP_SELF'];?>" method="post">
        <table class="manage-items">
            <tr>
                <th>Name</th>
                <th>Role</th>
                <th>2FA</th>
                <th>Last Login</th>
                <th>Login as this User</th>
                <th class="center">Edit</th>
                <th class="center">Delete</th>
            </tr>
            <tbody class="tabular">
            <?php
            $flag = false;
            foreach ($adminUsers as $adminUser) {
                $data = $adminUser->toArray();
                $flag = !$flag;
                ?>
                <tr id="rorder-<?=$data['id']?>">
                    <td><a href="edit.php?id=<?=  $data['id'];?>"><?php echo $data['name'];?></a></td>
                    <td>
                        <?= clean_page($roles->where('id', $data['role'])->first()->name ?? '') ?>
                    </td>
                    <td class="center">
                        <?php if (!empty($data['totp_secret'])) { ?>
                            <span class="tfa-badge tfa-badge-active" title="2FA active"><i class="fa fa-check-circle"></i></span>
                        <?php } else { ?>
                            <span class="tfa-badge tfa-badge-pending" title="2FA not configured"><i class="fa fa-exclamation-circle"></i></span>
                        <?php } ?>
                    </td>
                    <td><?php if ($data['last_login'] !== '0000-00-00 00:00:00' && !empty($data['last_login'])) {echo date('d/m/Y H:i:s',strtotime($data['last_login']));} else {echo 'Never';} ?></td>
                    <td><a href="manage.php?action=loginas&userid=<?php echo $data['id'];?>" class="alert" title="This will log you out of your current session and log you back in as this user. Do you want to proceed?">login <i class="fa fa-share" /></a></td>
                    <td class="center"><a href="edit.php?id=<?=  $data['id'];?>" class="edit picto"><i class="fa fa-pencil"></i></a></td>
                    <td class="center"><a href="manage.php?action=delete&delete_id=<?php echo $data['id'];?>" class="alert error" title="Are you sure you want to delete this?"><i class="fa fa-times-circle"></i></a></td>
                </tr>
                <?php
            }
            ?>
            </tbody>
        </table>
    </form>
    <?php
} else {
    ?>
    <p>No <?=$pagename?>s have been created</p>
    <?php
}

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