<?php

namespace routes;

use classes\authentication;
use objects\categories_o;
use objects\logs_o;
use traits\route_t;

class categoriesRoute
{
    use route_t;

    public function run(): void
    {
        $this->get('/categories', function () {

            // Require the user to be logged in
            global $response;
            $this->requirePermission('list_categories');
            // Get the user object
            $user = (new authentication())->get_user();
            // Check if the request was successful
            if ($user) {
                // Log the incident
                (new logs_o())->add('categories', 'global', 1, $user->id, 'LIST_CATEGORIES', 'User listed categories');
                // Return the list of departments
                $response->success(
                    (new categories_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',
                            'name',
                            'description',
                        ])
                        ->listObjectsWithPaginationIfSet(
                            function ($category) use ($user) {
                                // Return the object as an array
                                return [
                                    'id' => (int)$category['id'],
                                    'name' => (string)$category['name'],
                                    'description' => (string)$category['description'],
                                    'created_at' => (string)$category['created_at'],
                                    'updated_at' => (string)$category['updated_at'],
                                ];
                            }
                        )
                );
            } else {
                // Log the incident
                (new logs_o())->add('categories', 'global', 1, 0, 'LIST_CATEGORIES', 'User tried to list categories without being logged in');
                // Return an error
                $response->error('Invalid session', 400);
            }
        },
            [
                'list_categories' => 'List all categories'
            ]
        );

        $this->post('/categories', function () {

            // Require the user to be logged in
            global $response;
            $this->requirePermission('add_category');
            // Get the user object
            $user = (new authentication())->get_user();
            // Check if the request was successful
            if ($user) {
                // Log the incident
                (new logs_o())->add('categories', 'global', 1, $user->id, 'ADD_CATEGORY', 'User added a category');
                // Get the request data
                $name = $response->getRequestParameter('name') ?? null;
                $description = $response->getRequestParameter('description') ?? '';
                // Check if the required fields are set
                if ($name) {
                    // Add the category
                    (new categories_o())->add($name, $description ?? '');
                    // Return a success message
                    $response->success('Category added');
                } else {
                    // Return an error
                    $response->error('Missing required fields', 400);
                }

            } else {
                // Log the incident
                (new logs_o())->add('categories', 'global', 1, 0, 'ADD_CATEGORY', 'User tried to add a category without being logged in');
                // Return an error
                $response->error('Invalid session', 400);
            }
        },
            [
                'add_category' => 'Add a category'
            ]
        );

        $this->put('/categories', function () {

            // Require the user to be logged in
            global $response;
            $this->requirePermission('edit_category');
            // Get the user object
            $user = (new authentication())->get_user();
            // Check if the request was successful
            if ($user) {
                // Log the incident
                (new logs_o())->add('categories', 'global', 1, $user->id, 'EDIT_CATEGORY', 'User edited a category');
                // Get the request data
                $id = $response->getRequestParameter('id') ?? null;
                $name = $response->getRequestParameter('name') ?? null;
                $description = $response->getRequestParameter('description') ?? '';

                // Check what fields are set
                self::requireParameters(['id']);
                // Get the category object
                $category = (new categories_o())->select((int)$id);
                // Check if the category exists
                if (!$category->exists()) {
                    // Return an error
                    $response->error('Category not found', 404);
                }
                // Update the category fields that are set
                if (self::isParametersSet(['name'])) {
                    $category->name->set($name);
                }
                if (self::isParametersSet(['description'])) {
                    $category->description->set($description);
                }
                // Return a success message
                $response->success('Category updated');
            } else {
                // Log the incident
                (new logs_o())->add('categories', 'global', 1, 0, 'EDIT_CATEGORY', 'User tried to edit a category without being logged in');
                // Return an error
                $response->error('Invalid session', 400);
            }
        },
            [
                'edit_category' => 'Edit a category'
            ]
        );
    }
}