<?php

/**
 * Functionalities for the admin panel.
 */
//

function checkUser() {

    session_start();
    global $locator;

    $session = $locator->getSession();
    if ($session->getUser() === null) {
        http_response_code(401);
        die("You must be registered to perform this action");
    }

    $dao = $locator->getUserDAO();
    if (!$dao->isAdmin($session->getUser()->id)) {
        die("You must be an admin to perform this action");
    }
}

Flight::route('GET /admin', function() {
    checkUser();

    global $locator;
    Flight::render('admin/index.php', array('title' => 'Admin panel',
        'version' => $locator->getVersion(),
        'contextRoot' => $locator->config->contextRoot));
});

Flight::route('GET /admin-join', function() {
    checkUser();

    global $locator;
    Flight::render('admin/join.php', array('title' => 'Admin panel - Join users',
        'version' => $locator->getVersion(),
        'contextRoot' => $locator->config->contextRoot));
});

Flight::route('POST /admin-join', function() {
    checkUser();

    global $locator;

    $user1Id = filter_input(INPUT_POST, 'user1', FILTER_SANITIZE_STRING);
    $user2Id = filter_input(INPUT_POST, 'user2', FILTER_SANITIZE_STRING);

    if ($user1Id === null) {
        throw new \RAP\BadRequestException("Missing parameter user1");
    }
    if ($user2Id === null) {
        throw new \RAP\BadRequestException("Missing parameter user2");
    }

    $dao = $locator->getUserDAO();
    $user1 = $dao->findUserById($user1Id);
    $user2 = $dao->findUserById($user2Id);

    $locator->getUserHandler()->joinUsers($user1, $user2);

    Flight::redirect($locator->getBasePath() . '/admin-join');
});

Flight::route('GET /admin-search', function() {
    checkUser();

    $searchText = Flight::request()->query['query'];
    if ($searchText === null) {
        throw new \RAP\BadRequestException("Missing query parameter");
    }

    global $locator;
    $users = $locator->getUserDAO()->searchUser($searchText);

    Flight::json($users);
});

Flight::route('POST /admin/keypair', function() {

    checkUser();
    global $locator;

    $keyPair = $locator->getJWKSHandler()->generateKeyPair();
    Flight::json([
        "id" => $keyPair->keyId
    ]);
});