<?php
namespace Misuzu;

use RuntimeException;

$authInfo = $msz->getAuthInfo();
if(!$authInfo->isLoggedIn())
    Template::throwError(401);

$errors = [];
$authCtx = $msz->getAuthContext();
$sessions = $authCtx->getSessions();
$currentUser = $authInfo->getUserInfo();
$activeSessionId = $authInfo->getSessionId();

while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
    $sessionId = (string)filter_input(INPUT_POST, 'session');
    $activeSessionKilled = false;

    if($sessionId === 'all') {
        $activeSessionKilled = true;
        $sessions->deleteSessions(userInfos: $currentUser);
        $msz->createAuditLog('PERSONAL_SESSION_DESTROY_ALL');
    } else {
        try {
            $sessionInfo = $sessions->getSession(sessionId: $sessionId);
        } catch(RuntimeException $ex) {}

        if(empty($sessionInfo) || $sessionInfo->getUserId() !== $currentUser->getId()) {
            $errors[] = "That session doesn't exist.";
            break;
        }

        $activeSessionKilled = $sessionInfo->getId() === $activeSessionId;
        $sessions->deleteSessions(sessionInfos: $sessionInfo);
        $msz->createAuditLog('PERSONAL_SESSION_DESTROY', [$sessionInfo->getId()]);
    }

    if($activeSessionKilled) {
        Tools::redirect($msz->getURLs()->format('index'));
        return;
    } else break;
}

$pagination = new Pagination($sessions->countSessions(userInfo: $currentUser), 10);

$sessionList = [];
$sessionInfos = $sessions->getSessions(userInfo: $currentUser, pagination: $pagination);

foreach($sessionInfos as $sessionInfo)
    $sessionList[] = [
        'info' => $sessionInfo,
        'active' => $sessionInfo->getId() === $activeSessionId,
    ];

Template::render('settings.sessions', [
    'errors' => $errors,
    'session_list' => $sessionList,
    'session_pagination' => $pagination,
]);
