<?php

use api\classes\API_users;

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

$API_users = new API_users();

if ($API_users->request_method === 'GET') {
    $API_users->checkPermissions('admin-access-admins', 'RO');

    $users = $API_users->getUser();

    $removeFields = [
        'user_profile_picture_thumbnail',
        'user_password',
        'user_password_reset_token',
        'user_two_factor_secret',
        'user_profile_picture',
        'user_profile_picture_thumbnail'
    ];

    foreach ($users as &$user) {
        foreach ($removeFields as $field) {
            unset($user[$field]);
        }
    }
    unset($user);

    $API_users->apiOutput($code = 200, ['success' => $users], '');

} elseif ($API_users->request_method === 'POST') {
    # create a new user
    $API_users->checkPermissions('admin-access-admins', 'RW');

    $requiredFields = [
        'user_group_uuid' => ['type' => 'uuid'],
        'user_email' => ['type' => 'email'],
        'user_first_name' => ['type' => 'string'],
        'user_last_name' => ['type' => 'string'],
        'user_full_name' => ['type' => 'string'], # Does not need to be posted, set later
        'user_status' => ['type' => 'enum', 'values' => ['inactive', 'banned', 'pending']],
        'user_password' => ['type' => 'string'], # Does not need to be posted, set later
        'user_pref_language' => ['type' => 'enum', 'values' => ['en', 'nl']],
        'user_password_reset_token' => ['type' => 'string'], # Does not need to be posted, set later
        'user_password_reset_expires' => ['type' => 'int'], # Does not need to be posted, set later
    ];

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

    # The user will need to verify their email, the password field cannot be NULL so set a random password for now till the user resets it on when verifying there email
    $random_string = substr(str_shuffle(str_repeat('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01', 64)), 0, rand(50, 64));
    $user_password = password_hash($random_string, PASSWORD_BCRYPT, ["cost" => 12]);

    $API_users->postedData['user_password'] = $user_password;
    $API_users->postedData['user_full_name'] = trim($API_users->postedData['user_first_name'] . ' ' . $API_users->postedData['user_last_name']);
    $API_users->postedData['user_pref_language'] = $API_users->postedData['user_pref_language'] ?? 'en';

    # Password reset token that will be sent to the newly created user
    $API_users->postedData['user_password_reset_token'] = bin2hex(random_bytes(32));
    $API_users->postedData['user_password_reset_expires'] = time() + 86400;

    $API_users->validateData($requiredFields, $optionalFields);
    $API_users->createUser();

} elseif ($API_users->request_method === 'PUT') {
    # Edit a user
    if (isset($API_users->postedData['user_profile_change'])) { # If the user is changing their own profile
        $API_users->postedData['user_uuid'] = $_SESSION['user']['user_uuid']; # Make sure the user being changed is always its own user_uuid

        $requiredFields = [
            'user_uuid' => ['type' => 'uuid'],
            'user_email' => ['type' => 'email'],
            'user_first_name' => ['type' => 'string'],
            'user_last_name' => ['type' => 'string'],
            'user_full_name' => ['type' => 'string'],
            'user_pref_language' => ['type' => 'enum', 'values' => ['en', 'nl']],
        ];

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

    } else {
        $API_users->checkPermissions('admin-access-admins', 'RW');

        $requiredFields = [
            'user_uuid' => ['type' => 'uuid'],
            'user_group_uuid' => ['type' => 'uuid'],
            'user_email' => ['type' => 'email'],
            'user_first_name' => ['type' => 'string'],
            'user_last_name' => ['type' => 'string'],
            'user_full_name' => ['type' => 'string'],
            'user_status' => ['type' => 'enum', 'values' => ['active', 'inactive', 'banned', 'pending']],
            'user_pref_language' => ['type' => 'enum', 'values' => ['en', 'nl']],
        ];

        $optionalFields = [
            'user_phone_number' => ['type' => 'string'],
            'user_stompable' => ['type' => 'boolean']
        ];

        $API_users->postedData['user_stompable'] = (bool)$API_users->postedData['user_stompable'];
    }

    $API_users->postedData['user_full_name'] = trim($API_users->postedData['user_first_name'] . ' ' . $API_users->postedData['user_last_name']);
    $API_users->postedData['user_pref_language'] = $API_users->postedData['user_pref_language'] ?? 'en';

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

    $API_users->updateUser();

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

    $API_users->return_url = false;

    $API_users->checkPermissions('admin-access-admins', 'RW');
    $requiredFields = [
        'user_uuid' => ['type' => 'uuid'],
    ];

    $API_users->validateData($requiredFields);

    $API_users->deleteUser();
}