<?php

use api\classes\API_permissions;
use api\classes\API_usergroups;

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

$API_permissions = new API_permissions();
$API_usergroups = new API_usergroups();

if ($API_permissions->request_method === 'GET') {
    $API_usergroups->checkPermissions('admin-access-control-permissions', 'RO');

    $permissions = $API_permissions->getUserGroupPermissions();

    $API_permissions->apiOutput($code = 200, ['success' => $permissions]);

} elseif ($API_permissions->request_method === 'PUT') {
    # when called from the frontend will not be forwarding to a url since when it's called from the frontend it doesn't need a redirection
    $API_permissions->return_url = false;

    $API_permissions->checkPermissions('admin-access-control-permissions', 'RW');

    $requiredFields = [
        'permission_uuid' => ['type' => 'uuid'],
        'user_group_uuid' => ['type' => 'uuid'],
        'permission_value' => ['type' => 'enum', 'values' => ['NA', 'RO', 'RW']],
    ];

    $API_permissions->validateData($requiredFields);

    # check if the permission exists
    $_GET['builder'] = [1 => ['where' => [0 => 'permission_uuid', 1 => $API_permissions->data['permission_uuid']]]];
    $API_permissions->getPermission();

    # check if the user_group_uuid exists
    $_GET['builder'] = [1 => ['where' => [0 => 'user_group_uuid', 1 => $API_permissions->data['user_group_uuid']]]];
    $user_group = $API_usergroups->getUsergroup();

    # if the user updating the permissions is in a lower group (higher group weight number) prevent them for doing so to prevent
    # Privilege escalation.
    if ($user_group[0]['user_group_weight'] < $_SESSION['user']['user_group_weight']) {
        $API_permissions->apiOutput(405, ['error' => 'You are not allowed to update this user since you are in a lower group']);
    }

    # Update the permission
    $API_permissions->updateAccessRights();
}