<?php

namespace routes;

use classes\authentication;
use classes\department_customer_pricing_service;
use classes\limited_backoffice_exception;
use objects\branding_o;
use objects\department_variables_o;
use objects\departments_o;
use objects\logs_o;
use objects\products_o;
use objects\users_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
                $department = (new departments_o())->getDepartmentById((int)$this->fromRequest('department_id'));
                $department['custom_pricing_only'] = (bool)(int)($department['custom_pricing_only'] ?? 0);
                $response->success($department);
            } 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->put('/superuser/department/branding', function () {
            global $response;
            $this->requirePermission('superuser_set_department_branding');

            $user = (new authentication())->get_user();
            if (!$user) {
                (new logs_o())->add('departments', 'global', 1, 0, 'SUPERUSER_SET_DEPARTMENT_BRANDING', 'No user found, or invalid session');
                $response->error('Invalid session', 400);
            }

            self::requireParameters(['department_id', 'branding_id']);

            $departmentId = self::getParameter('department_id');
            if (!is_int($departmentId) && !(is_string($departmentId) && preg_match('/^\d+$/', $departmentId) === 1)) {
                $response->error('Department ID must be a number', 400);
            }
            $departmentId = (int)$departmentId;
            if ($departmentId <= 0) {
                $response->error('Department ID must be a positive number', 400);
            }

            $department = (new departments_o())->selectId($departmentId);
            if (!$department->exists()) {
                $response->error('Department not found', 404);
            }

            $brandingId = self::getParameter('branding_id');
            if ($brandingId === '' || $brandingId === null || $brandingId === 0 || $brandingId === '0') {
                $department->branding->set(null);
            } else {
                if (!is_int($brandingId) && !(is_string($brandingId) && preg_match('/^\d+$/', $brandingId) === 1)) {
                    $response->error('Branding ID must be a number', 400);
                }

                $brandingId = (int)$brandingId;
                if ($brandingId <= 0) {
                    $response->error('Branding ID must be a positive number', 400);
                }

                $branding = (new branding_o())->select($brandingId);
                if (!$branding->exists()) {
                    $response->error('Branding not found', 404);
                }

                $department->branding->set($brandingId);
            }

            $department->objectChanged();
            (new logs_o())->add('departments', 'global', 1, $user->id, 'SUPERUSER_SET_DEPARTMENT_BRANDING', 'Successfully set department branding');

            $response->success(
                (new departments_o())->getDepartmentById($departmentId, true)
            );
        }, [
            'superuser_set_department_branding' => 'Set department branding'
        ]);

        $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/customer-pricing', function () {
            global $response;
            $this->requirePermission('superuser_fetch_department_customer_pricing');

            $user = (new authentication())->get_user();
            if (!$user) {
                (new logs_o())->add('departments', 'global', 1, 0, 'SUPERUSER_FETCH_DEPARTMENT_CUSTOMER_PRICING', 'No user found, or invalid session');
                $response->error('Invalid session', 400);
            }

            $departmentId = $this->positiveIntFromRequest('department_id');
            $userId = $this->customerUserIdFromRequest();

            try {
                (new logs_o())->add('departments', 'global', 1, $user->id, 'SUPERUSER_FETCH_DEPARTMENT_CUSTOMER_PRICING', 'Successfully fetched department customer pricing');
                $response->success((new department_customer_pricing_service())->getPricing($departmentId, $userId));
            } catch (limited_backoffice_exception $exception) {
                $response->error($exception->payload(), $exception->statusCode());
            }
        }, [
            'superuser_fetch_department_customer_pricing' => 'Fetch department customer pricing'
        ]);

        $this->put('/superuser/department/customer-pricing', function () {
            global $response;
            $this->requirePermission('superuser_set_department_customer_pricing');

            $user = (new authentication())->get_user();
            if (!$user) {
                (new logs_o())->add('departments', 'global', 1, 0, 'SUPERUSER_SET_DEPARTMENT_CUSTOMER_PRICING', 'No user found, or invalid session');
                $response->error('Invalid session', 400);
            }

            $payload = json_decode(file_get_contents('php://input'), true);
            if (!is_array($payload)) {
                $response->error('Invalid request body', 400);
            }

            $departmentId = $this->positiveIntFromPayload($payload, 'department_id');
            $userId = $this->customerUserIdFromPayload($payload);

            try {
                (new logs_o())->add('departments', 'global', 1, $user->id, 'SUPERUSER_SET_DEPARTMENT_CUSTOMER_PRICING', 'Successfully set department customer pricing');
                $response->success((new department_customer_pricing_service())->updatePricing($departmentId, $userId, $payload));
            } catch (limited_backoffice_exception $exception) {
                $response->error($exception->payload(), $exception->statusCode());
            }
        }, [
            'superuser_set_department_customer_pricing' => 'Set department customer pricing'
        ]);

        $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'
        ]);

    }

    private function positiveIntFromRequest(string $name): int
    {
        global $response;
        $value = $this->fromRequest($name);
        if (!is_string($value) && !is_int($value)) {
            $response->error($name . ' is required', 400);
        }

        return $this->positiveIntValue($value, $name);
    }

    private function customerUserIdFromRequest(): int
    {
        if ($this->fromRequest('user_id') !== null) {
            return $this->positiveIntFromRequest('user_id');
        }

        return $this->userIdFromCustomerNumber($this->positiveIntFromRequest('customer_number'));
    }

    /**
     * @param array<string, mixed> $payload
     */
    private function positiveIntFromPayload(array $payload, string $name): int
    {
        global $response;
        if (!array_key_exists($name, $payload)) {
            $response->error($name . ' is required', 400);
        }

        return $this->positiveIntValue($payload[$name], $name);
    }

    /**
     * @param array<string, mixed> $payload
     */
    private function customerUserIdFromPayload(array $payload): int
    {
        if (array_key_exists('user_id', $payload)) {
            return $this->positiveIntFromPayload($payload, 'user_id');
        }

        return $this->userIdFromCustomerNumber($this->positiveIntFromPayload($payload, 'customer_number'));
    }

    private function positiveIntValue(mixed $value, string $name): int
    {
        global $response;
        if (is_int($value)) {
            $parsed = $value;
        } elseif (is_string($value) && preg_match('/^\d+$/', trim($value)) === 1) {
            $parsed = (int)trim($value);
        } else {
            $response->error($name . ' must be a positive integer', 400);
        }

        if ($parsed <= 0) {
            $response->error($name . ' must be a positive integer', 400);
        }

        return $parsed;
    }

    private function userIdFromCustomerNumber(int $customerNumber): int
    {
        global $response;
        $customer = (new users_o())->getUserByCustomerNumber($customerNumber);
        if (!$customer->exists()) {
            $response->error('Customer not found', 404);
        }

        return (int)$customer->id;
    }
}
