<?php

use api\classes\API_apitoken;
use api\classes\API_users;


session_start();
require_once "{$_SERVER['DOCUMENT_ROOT']}/api/classes/API_apitoken.php";

$API_apitoken = new API_apitoken();

if ($API_apitoken->request_method === 'GET') {

    # Retrieve all the API tokens from a user and return them.

    $requiredFields = [
        'user_uuid' => ['type' => 'uuid'],
    ];

    $API_apitoken->validateData($requiredFields);

    $API_apitoken->checkTokenPermissions();

    $apitokens = $API_apitoken->getTokens();

    $API_apitoken->apiOutput($code = 200, ['success' => $apitokens], 'api_token_created');

} elseif ($API_apitoken->request_method === 'POST') {

    # Creates a new API Token. First check if the uuid is correct and then check the permission
    # After that create a new token, retrieve the newly created api_token and give a response.
    $requiredFields = [
        'user_uuid' => ['type' => 'uuid']
    ];

    $optionalFields = [
        'api_token_name' => ['type' => 'string']
    ];

    $API_apitoken->validateData($requiredFields, $optionalFields);

    $API_apitoken->checkTokenPermissions();

    $API_apitoken->createNewToken();

} elseif ($API_apitoken->request_method === 'PUT') {

    # Change the revoked status of an API token

    # This api call, when called from the frontend will not be forwarding to a url.
    $API_apitoken->return_url = false;

    $requiredFields = [
        'api_token_uuid' => ['type' => 'uuid'],
        'api_token_revoked' => ['type' => 'boolean'],
    ];

    $API_apitoken->validateData($requiredFields);

    $api_token_data = $API_apitoken->getToken();

    $API_apitoken->checkTokenPermissions();

    $API_apitoken->revokeToken();

} elseif ($API_apitoken->request_method === 'DELETE') {

    # Deletes an API token, requires DELETE with 'api_token_uuid' first retrieve the uuid of the user with getToken then check
    # if the user is another user or itself

    # This api call, when called from the frontend will not be forwarding to a url.
    $API_apitoken->return_url = false;

    $requiredFields = [
        'api_token_uuid' => ['type' => 'uuid'],
    ];

    $API_apitoken->validateData($requiredFields);
    $api_token_data = $API_apitoken->getToken();

    $API_apitoken->checkTokenPermissions();

    $API_apitoken->deleteToken();

}