<?php

use api\classes\API_usergroups;

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


$API_usergroups = new API_usergroups();

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

    $userGroups = $API_usergroups->getUserGroup();

    $API_usergroups->apiOutput($code = 200, ['success' => $userGroups], '');
} elseif ($API_usergroups->request_method === 'POST') {

    # Create a new user group

    $API_usergroups->checkPermissions('admin-access-control-user-groups', 'RW');

    $requiredFields = [
        'user_group_name' => ['type' => 'string'],
        'user_group_slugify' => ['type' => 'slugify'],
        'user_group_weight' => ['type' => 'int'],
        'user_group_type' => ['type' => 'enum', 'values' => ['admin', 'user']],
    ];

    $API_usergroups->validateData($requiredFields);

    # superuser group is a fixed group name for the superuser
    if ($API_usergroups->data['user_group_name'] === 'superuser' || $API_usergroups->data['user_group_slugify'] === 'superuser') {
        $API_usergroups->apiOutput(400, ['error' => 'superuser group cannot be created'], 'cannot_add_superuser_group');
    }

    $API_usergroups->createUsergroups();


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

    # Update a user group

    $requiredFields = [
        'user_group_uuid' => ['type' => 'uuid'],
        'user_group_name' => ['type' => 'string'],
        'user_group_weight' => ['type' => 'int'],
    ];

    $API_usergroups->validateData($requiredFields);

    $API_usergroups->updateUserGroup();

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

    # Delete a user group

    $API_usergroups->checkPermissions('admin-access-control-user-groups', 'RW');

    # 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_usergroups->return_url = false;

    $requiredFields = ['user_group_uuid' => ['type' => 'uuid']];

    $API_usergroups->validateData($requiredFields);

    # Delete the device from the database.
    $API_usergroups->deleteUsergroup();
}