<?php

namespace routes;

use classes\authentication;
use objects\department_variables_o;
use objects\departments_o;
use objects\logs_o;
use objects\products_o;
use traits\route_t;

class superuserDepartmentRoute
{
    use route_t;

    public function run(): void
    {
        $this->get('/superuser/department', function () {
            // Require the user to be logged in
            global $response;
            $this->requirePermission('superuser_fetch_department');
            // Get the user object
            $user = (new authentication())->get_user();
            // Check if the request was successful
            if ($user) {
                // Check if the required fields are set
                if ($this->fromRequest('department_id') === null) {
                    $response->error('Department ID is required', 400);
                }
                // Check if the department id is a valid number
                if (!is_numeric($this->fromRequest('department_id'))) {
                    $response->error('Department ID must be a number', 400);
                }
                if (!(new departments_o())->getDepartmentById((int)$this->fromRequest('department_id'))) {
                    $response->error('Department not found', 404);
                }
                // Log the incident
                (new logs_o())->add('departments', 'global', 1, $user->id, 'SUPERUSER_FETCH_DEPARTMENT', 'Successfully fetched department');
                // Return the department
                $response->success(
                    (new departments_o())->getDepartmentById((int)$this->fromRequest('department_id'))
                );
            } else {
                // Log the incident
                (new logs_o())->add('departments', 'global', 1, 0, 'SUPERUSER_FETCH_DEPARTMENT', 'No user found, or invalid session');
                // Return an error
                $response->error('Invalid session', 400);
            }
        }, [
            'superuser_fetch_department' => 'Fetch department'
        ]);

        $this->post('/superuser/department/prices', function () {
            // Require the user to be logged in
            global $response;
            $this->requirePermission('superuser_set_department_prices');
            // Get the user object
            $user = (new authentication())->get_user();
            // Check if the request was successful
            if ($user) {
                // Check if the required fields are set
                $data = json_decode(file_get_contents('php://input'), true);
                if (!isset($data['department_id'])) {
                    $response->error('Department ID is required', 400);
                }
                if (!isset($data['price'])) {
                    $response->error('Price is required', 400);
                }
                if (!isset($data['product_id'])) {
                    $response->error('Product ID is required', 400);
                }
                // Check if the department id is a valid number
                if (!is_numeric($data['department_id'])) {
                    $response->error('Department ID must be a number', 400);
                }
                // Check if the price is a valid number
                if (!is_numeric($data['price'])) {
                    // Check if the value is an empty string
                    if ($data['price'] === '') {
                        $data['price'] = 0;
                    } else {
                        $response->error('Price must be a number', 400);
                    }
                }
                // Check if the product id is a valid number
                if (!is_numeric($data['product_id'])) {
                    $response->error('Product ID must be a number', 400);
                }
                // Check if the product exists
                if (!(new products_o())->getProductById((int)$data['product_id'])->exists()) {
                    $response->error('Product not found', 404);
                }
                // Check if the department exists
                if (!(new departments_o())->getDepartmentById((int)$data['department_id'])) {
                    $response->error('Department not found', 404);
                }
                // Log the incident
                (new logs_o())->add('departments', 'global', 1, $user->id, 'SUPERUSER_SET_DEPARTMENT_PRICES', 'Successfully set department prices');
                // Set the department prices
                (new departments_o())->setDepartmentProductPrice((int)$data['department_id'], (int)$data['product_id'], (int)$data['price']);
                // Return the department
                $response->success(
                    (new departments_o())->getDepartmentById((int)$data['department_id'])
                );
            } else {
                // Log the incident
                (new logs_o())->add('departments', 'global', 1, 0, 'SUPERUSER_SET_DEPARTMENT_PRICES', 'No user found, or invalid session');
                // Return an error
                $response->error('Invalid session', 400);
            }
        }, [
            'superuser_set_department_prices' => 'Set department prices'
        ]);

        $this->get('/superuser/department/prices', function () {
            // Require the user to be logged in
            global $response;
            $this->requirePermission('superuser_fetch_department_prices');
            // Get the user object
            $user = (new authentication())->get_user();
            // Check if the request was successful
            if ($user) {
                // Check if the required fields are set
                if ($this->fromRequest('department_id') === null) {
                    $response->error('Department ID is required', 400);
                }
                // Check if the department id is a valid number
                if (!is_numeric($this->fromRequest('department_id'))) {
                    $response->error('Department ID must be a number', 400);
                }
                if (!(new departments_o())->getDepartmentById((int)$this->fromRequest('department_id'))) {
                    $response->error('Department not found', 404);
                }
                // Log the incident
                (new logs_o())->add('departments', 'global', 1, $user->id, 'SUPERUSER_FETCH_DEPARTMENT_PRICES', 'Successfully fetched department prices');
                // Return the department
                $response->success(
                    array_map(
                        function ($price_row) {
                            $price_row['id'] = (int)$price_row['id'];
                            $price_row['department_id'] = (int)$price_row['department_id'];
                            $price_row['product_id'] = (int)$price_row['product_id'];
                            $price_row['price'] = (int)$price_row['price'];
                            return $price_row;
                        },
                    (new departments_o())->getDepartmentProductPrices((int)$this->fromRequest('department_id'))
                ));
            } else {
                // Log the incident
                (new logs_o())->add('departments', 'global', 1, 0, 'SUPERUSER_FETCH_DEPARTMENT_PRICES', 'No user found, or invalid session');
                // Return an error
                $response->error('Invalid session', 400);
            }
        }, [
            'superuser_fetch_department_prices' => 'Fetch department prices'
        ]);

        $this->get('/superuser/department/variables', function () {
            // Require the user to be logged in
            global $response;
            $this->requirePermission('superuser_fetch_department_variables');
            // Get the user object
            $user = (new authentication())->get_user();
            // Check if the request was successful
            if ($user) {
                // Log the incident
                (new logs_o())->add('departments', 'global', 1, $user->id, 'SUPERUSER_FETCH_DEPARTMENT_VARIABLES', 'Successfully fetched department variables');
                // Return the department
                $response->success(
                    (new department_variables_o())->listObjectsWithPaginationIfSet(
                        function ($variable_row) {
                            return $variable_row;
                        },
                    )
                );
            } else {
                // Log the incident
                (new logs_o())->add('departments', 'global', 1, 0, 'SUPERUSER_FETCH_DEPARTMENT_VARIABLES', 'No user found, or invalid session');
                // Return an error
                $response->error('Invalid session', 400);
            }
        }, [
            'superuser_fetch_department_variables' => 'Fetch department variables'
        ]);

        $this->post('/superuser/department/variables', function () {
            // Require the user to be logged in
            global $response;
            $this->requirePermission('superuser_set_department_variables');
            // Get the user object
            $user = (new authentication())->get_user();
            // Check if the request was successful
            if ($user) {
                // Check if the required fields are set
                self::requireParameters(['department_id', 'variable', 'value']);
                // Check if the department id is a valid number
                self::requireType((int)self::getParameter('department_id'), self::type_int());
                self::requireMinValue((int)self::getParameter('department_id'), 1);
                self::requireSameLength((int)self::getParameter('department_id'), self::getParameter('department_id'));
                // Check if the variable is a valid string
                self::requireType(self::getParameter('variable'), self::type_string());
                self::requireMinLength('variable', 1);
                self::requireMaxLength('variable', 255);
                // Check if the value is a valid string
                self::requireType(self::getParameter('value'), self::type_string());
                self::requireMinLength('value', 0);
                self::requireMaxLength('value', 4000);
                // Check if the department exists
                if (!(new departments_o())->selectId((int)self::getParameter('department_id'))) {
                    $response->error('Department not found', 404);
                }
                // Log the incident
                (new logs_o())->add('departments', 'global', 1, $user->id, 'SUPERUSER_SET_DEPARTMENT_VARIABLES', 'Successfully set department variables');
                // Set the department variables
                $department_variables = new department_variables_o();
                $department_variables->selectDepartment((int)self::getParameter('department_id'));
                $department_variables->set(
                    self::getParameter('variable'),
                    self::getParameter('value')
                );
                // Return the department
                $response->success(
                    (new department_variables_o())->listObjectsWithPaginationIfSet(
                        function ($variable_row) {
                            return $variable_row;
                        },
                    )
                );
            } else {
                // Log the incident
                (new logs_o())->add('departments', 'global', 1, 0, 'SUPERUSER_SET_DEPARTMENT_VARIABLES', 'No user found, or invalid session');
                // Return an error
                $response->error('Invalid session', 400);
            }
        }, [
            'superuser_set_department_variables' => 'Set department variables'
        ]);

    }
}