<?php

namespace routes;

use classes\authentication;
use classes\response;
use objects\logs_o;
use objects\users_o;
use traits\route_t;

class usersRoute
{
    use route_t;

    public function run(): void
    {
        $this->get('/users', function () {
            // Require the user to be logged in
            global /** @var response $response */
            $response;
            $this->requirePermission('list_users');
            // Get the user object
            $user = (new authentication())->get_user();
            // Check if the request was successful
            if ($user) {
                // Log the incident
                (new logs_o())->add('users', 'global', 1, $user->id, 'LIST_USERS', 'Successfully listed users');
                // Return the list of users
                $users_o = new users_o();
                $response->success(
                    $users_o->parseUsers(
                        $users_o
                            ->setSearchableFields([
                                // The fields that can be searched. This would otherwise make it possible to get secret information from the database, simply by searching for it and getting the result count back
                                'id',
                                'customer_number',
                                'group_id',
                                'display_name',
                            ])
                            ->listObjectsWithPaginationIfSet()
                    )
                );
            } else {
                // Log the incident
                (new logs_o())->add('users', 'global', 1, 0, 'LIST_USERS', 'No user found, or invalid session');
                // Return an error
                $response->error('Invalid session', 400);
            }
        },
            [
                'list_users' => 'List all users'
            ]
        );

        $this->get('/users/customer', function () {
            // Require the user to be logged in
            global $response;
            $this->requirePermission('get_user_from_customer_number');
            // Get the user object
            $user = (new authentication())->get_user();
            // Check if the request was successful
            if ($user) {
                // Check if the customer number is valid
                if (!(new users_o())->automaticGetTargetUserFromRequest()->exists()) {
                    // Log the incident
                    (new logs_o())->add('users', 'global', 1, $user->id, 'GET_USER_FROM_CUSTOMER_NUMBER', 'Customer not found, not imported');
                    $response->error('Customer not found', 400);
                }
                // Check
                // Log the incident
                (new logs_o())->add('users', 'global', 1, $user->id, 'GET_USER_FROM_CUSTOMER_NUMBER', 'Successfully retrieved user from customer number');
                // Return the list of users
                $response->success(
                    (new users_o())->automaticGetTargetUserFromRequest()->getCustomerEcocomicData()->asArray()
                );
            } else {
                // Log the incident
                (new logs_o())->add('users', 'global', 1, 0, 'GET_USER_FROM_CUSTOMER_NUMBER', 'No user found, or invalid session');
                // Return an error
                $response->error('Invalid session', 400);
            }
        },
            [
                'get_user_from_customer_number' => 'Get user from customer number'
            ]
        );

        $this->post('/users', function () {
            // Require the user to be logged in
            global $response;
            $this->requirePermission('add_user');
            // Get the user object
            $user = (new authentication())->get_user();
            // Check if the request was successful
            if ($user) {
                // Get the post data
                $data = json_decode(file_get_contents('php://input'), true);
                // Check if the required fields are set
                if (!isset($data['customer_number'])) {
                    $response->error('Customer number is required', 400);
                }
                if (!isset($data['password'])) {
                    $response->error('Password is required', 400);
                }
                if (!isset($data['role'])) {
                    $response->error('Role is required', 400);
                }
                // Add the user
                (new users_o())->add($data['customer_number'], $data['password'], (int)$data['role']);
                // Log the incident
                (new logs_o())->add('users', 'global', 1, $user->id, 'ADD_USER', 'Successfully added a user');
                // Return a success message
                $response->success(['message' => 'User added']);
            } else {
                // Log the incident
                (new logs_o())->add('users', 'global', 1, 0, 'ADD_USER', 'No user found, or invalid session');
                // Return an error
                $response->error('Invalid session', 400);
            }
        },
            [
                'add_user' => 'Add a user'
            ]
        );

        $this->put('/users', function () {
            // Require the user to be logged in
            global $response;
            $this->requirePermission('edit_user');
            // Get the user object
            $user = (new authentication())->get_user();
            // Check if the request was successful
            if ($user) {
                // Get the post data
                $data = json_decode(file_get_contents('php://input'), true);
                // Check if the required fields are set
                if (!isset($data['id'])) {
                    $response->error('ID is required', 400);
                }
                if (!isset($data['customer_number'])) {
                    $response->error('Customer number is required', 400);
                }
                // Check if a new role is set, if not, set it to null to prevent it from being updated
                if (!isset($data['role']) || $data['role'] === 'null' || $data['role'] === '') {
                    $data['role'] = null;
                }
                // Check if a display name is set, if not, set it to null to prevent it from being updated
                if (!isset($data['display_name']) || $data['display_name'] === 'null' || $data['display_name'] === '') {
                    $data['display_name'] = null;
                }
                // If the role is set, require the edit_user_role permission
                if ($data['role']) {
                    $this->requirePermission('edit_user_role');
                }
                // Check if a new password is set, if not, set it to null to prevent it from being updated
                if (!isset($data['password']) || $data['password'] === 'null' || $data['password'] === '') {
                    $data['password'] = null;
                }
                // If the password is set, require the edit_user_password permission
                if ($data['password']) {
                    $this->requirePermission('edit_user_password');
                }
                // Edit the user
                (new users_o())->edit((int)$data['id'], (string)$data['customer_number'], $data['role'], $data['password'], $data['display_name']);
                // Log the incident
                (new logs_o())->add('users', 'global', 1, $user->id, 'EDIT_USER', 'Successfully edited a user with ID: ' . $data['id']);
                // Return a success message
                $response->success(['message' => 'User edited']);
            } else {
                // Log the incident
                (new logs_o())->add('users', 'global', 1, 0, 'EDIT_USER', 'No user found, or invalid session');
                // Return an error
                $response->error('Invalid session', 400);
            }
        },
            [
                'edit_user' => 'Edit a user',
                'edit_user_role' => 'Edit a user\'s role',
                'edit_user_password' => 'Edit a user\'s password'
            ]
        );

        $this->get('/public/employees', function () {
            // This route is public, no authentication is required.
            global $response;
            // Get the users with the permission employee_public_data
            $users = (new users_o())->getUsersWithPermission('employee_public_data');
            $publicData = [];
            // Return the public data of the employees
            /** @var users_o $user */
            foreach ( $users as $user ) {
                $publicData[] = $user->listPublicEmployeeData();
            }
            // Return the list of users
            $response->success(
                $publicData
            );
        },
            [
                'list_public_employees' => 'List all public employees',
                'employee_public_data' => 'When this permission is set, the user is PUBLICLY visible on the employee login page'
            ]
        );
    }
}