<?php

namespace routes;

use classes\authentication;
use classes\response;
use classes\router;
use objects\department_time_bookings_entries_o;
use objects\department_time_bookings_opening_hours_o;
use objects\department_time_bookings_types_o;
use objects\logs_o;
use objects\product_options_o;
use traits\route_t;

class departmentTimeBookingsRoute
{
    use route_t;

    public function run(): void
    {
        global /** @var response $response */
        /** @var router $router */
        $router, $response;


        /** Department Time Bookings -> List */
        $this->get('/department/timebookings/opening-hours', function () {
            global $response;
            self::requirePermission('department_timebookings_opening_hours_get');
            $user = (new authentication())->get_user();
            if ($user) {
                $specific_department = null;
                if (self::isParametersSet(['department']) || self::isParametersSet(['id'])) {
                    $parameter_name = self::isParametersSet(['department']) ? 'department' : 'id';
                    self::requireType((int)self::getParameter($parameter_name), self::type_int());
                    self::requireMinValue((int)self::getParameter($parameter_name), 1);
                    self::requireSameLength(self::getParameter($parameter_name), (int)self::getParameter($parameter_name));
                    self::requireDepartmentAccess((int)self::getParameter($parameter_name));
                    $specific_department = (int)self::getParameter($parameter_name);
                    // Select the specific department
                    $department_time_bookings_opening_hours = new department_time_bookings_opening_hours_o();
                    $department_time_bookings_opening_hours->selectByDepartment(
                        (int)self::getParameter($parameter_name)
                    );
                    $response->success($department_time_bookings_opening_hours->asArray());
                }
                $department_time_bookings_opening_hours = new department_time_bookings_opening_hours_o();
                $result = $department_time_bookings_opening_hours->listObjectsWithPaginationIfSet(
                    function ($tmp_object_array) {
                        return [
                            ...$tmp_object_array,
                            'id' => (int)$tmp_object_array['id'],
                            'department' => (int)$tmp_object_array['department'],
                        ];
                    },
                    $department_time_bookings_opening_hours->forceRestrictFilters(
                        [
                            // This makes sure that the user can only see orders from the departments they explicitly have access to
                            'department' => ($specific_department ?? $user->getGroup()->getDepartments()),
                        ]
                    )
                );
                (new logs_o())->add('department_time_bookings_opening_hours', 'global', 0, $user->id, 'DEPARTMENT_TIME_BOOKINGS_OPENING_HOURS_GET', 'Get department time bookings opening hours');
                $response->success($result);
            } else {
                (new logs_o())->add('department_time_bookings_opening_hours', 'global', 0, 0, 'DEPARTMENT_TIME_BOOKINGS_OPENING_HOURS_GET', 'Get department time bookings opening hours failed');
                $response->error('Invalid session', 400);
            }
        },
            [
                'department_timebookings_opening_hours_get' => 'List department time bookings opening hours, in the departments the user has access to',
            ]
        );

        /** Department Time Bookings -> Update */
        $this->put('/department/timebookings/opening-hours', function () {
            global $response;
            self::requirePermission('department_timebookings_opening_hours_put');
            $user = (new authentication())->get_user();
            if ($user) {
                self::requireParameters(['id']);
                self::requireType((int)self::getParameter('id'), self::type_int());
                self::requireMinValue((int)self::getParameter('id'), 1);
                self::requireSameLength(self::getParameter('id'), (int)self::getParameter('id'));
                $department_time_bookings_opening_hours = new department_time_bookings_opening_hours_o();
                $department_time_bookings_opening_hours->select(
                    (int)self::getParameter('id')
                );
                // Require the department access
                self::requireDepartmentAccess((int)$department_time_bookings_opening_hours->department->value());
                function ifEmptySetNull($value): ?string
                {
                    return $value === '' ? null : $value;
                }

                // Update the department time bookings opening hours
                $department_time_bookings_opening_hours->update([
                    ...(self::isParametersSet(['monday_start']) ? ['monday_start' => ifEmptySetNull(self::getParameter('monday_start'))] : []),
                    ...(self::isParametersSet(['monday_end']) ? ['monday_end' => ifEmptySetNull(self::getParameter('monday_end'))] : []),
                    ...(self::isParametersSet(['tuesday_start']) ? ['tuesday_start' => ifEmptySetNull(self::getParameter('tuesday_start'))] : []),
                    ...(self::isParametersSet(['tuesday_end']) ? ['tuesday_end' => ifEmptySetNull(self::getParameter('tuesday_end'))] : []),
                    ...(self::isParametersSet(['wednesday_start']) ? ['wednesday_start' => ifEmptySetNull(self::getParameter('wednesday_start'))] : []),
                    ...(self::isParametersSet(['wednesday_end']) ? ['wednesday_end' => ifEmptySetNull(self::getParameter('wednesday_end'))] : []),
                    ...(self::isParametersSet(['thursday_start']) ? ['thursday_start' => ifEmptySetNull(self::getParameter('thursday_start'))] : []),
                    ...(self::isParametersSet(['thursday_end']) ? ['thursday_end' => ifEmptySetNull(self::getParameter('thursday_end'))] : []),
                    ...(self::isParametersSet(['friday_start']) ? ['friday_start' => ifEmptySetNull(self::getParameter('friday_start'))] : []),
                    ...(self::isParametersSet(['friday_end']) ? ['friday_end' => ifEmptySetNull(self::getParameter('friday_end'))] : []),
                    ...(self::isParametersSet(['saturday_start']) ? ['saturday_start' => ifEmptySetNull(self::getParameter('saturday_start'))] : []),
                    ...(self::isParametersSet(['saturday_end']) ? ['saturday_end' => ifEmptySetNull(self::getParameter('saturday_end'))] : []),
                    ...(self::isParametersSet(['sunday_start']) ? ['sunday_start' => ifEmptySetNull(self::getParameter('sunday_start'))] : []),
                    ...(self::isParametersSet(['sunday_end']) ? ['sunday_end' => ifEmptySetNull(self::getParameter('sunday_end'))] : []),
                ]);
                (new logs_o())->add('department_time_bookings_opening_hours', 'global', 0, $user->id, 'DEPARTMENT_TIME_BOOKINGS_OPENING_HOURS_PUT', 'Update department time bookings opening hours');
                $response->success($department_time_bookings_opening_hours->asArray());
            } else {
                (new logs_o())->add('department_time_bookings_opening_hours', 'global', 0, 0, 'DEPARTMENT_TIME_BOOKINGS_OPENING_HOURS_PUT', 'Update department time bookings opening hours failed');
                $response->error('Invalid session', 400);
            }
        },
            [
                'department_timebookings_opening_hours_put' => 'Update department time bookings opening hours',
            ]
        );

        /** Department Time Bookings -> Types */
        $this->get('/department/timebookings/types', function () {
            global $response;
            self::requirePermission('department_timebookings_types_get');
            $user = (new authentication())->get_user();
            if ($user) {
                $specific_department = null;
                if (self::isParametersSet(['department']) || self::isParametersSet(['id'])) {
                    $parameter_name = self::isParametersSet(['department']) ? 'department' : 'id';
                    self::requireType((int)self::getParameter($parameter_name), self::type_int());
                    self::requireMinValue((int)self::getParameter($parameter_name), 1);
                    self::requireSameLength(self::getParameter($parameter_name), (int)self::getParameter($parameter_name));
                    self::requireDepartmentAccess((int)self::getParameter($parameter_name));
                    $specific_department = (int)self::getParameter($parameter_name);
                }
                $department_time_bookings_types = new department_time_bookings_types_o();
                $result = $department_time_bookings_types->listObjectsWithPaginationIfSet(
                    function ($tmp_object_array) {
                        return [
                            ...$tmp_object_array,
                            'id' => (int)$tmp_object_array['id'],
                            'department' => (int)$tmp_object_array['department'],
                            'product' => (int)$tmp_object_array['product'],
                            'duration' => (int)$tmp_object_array['duration'],
                        ];
                    },
                    $department_time_bookings_types->forceRestrictFilters(
                        [
                            // This makes sure that the user can only see orders from the departments they explicitly have access to
                            'department' => ($specific_department ?? $user->getGroup()->getDepartments()),
                        ]
                    )
                );
                (new logs_o())->add('department_time_bookings_types', 'global', 0, $user->id, 'DEPARTMENT_TIME_BOOKINGS_TYPES_GET', 'Get department time bookings types');
                $response->success($result);
            } else {
                (new logs_o())->add('department_time_bookings_types', 'global', 0, 0, 'DEPARTMENT_TIME_BOOKINGS_TYPES_GET', 'Get department time bookings types failed');
                $response->error('Invalid session', 400);
            }
        },
            [
                'department_timebookings_types_get' => 'List department time bookings types, in the departments the user has access to',
            ]
        );

        /** Department Time Bookings -> Types -> Add */
        $this->post('/department/timebookings/types', function () {
            global $response;
            self::requirePermission('department_timebookings_types_post');
            $user = (new authentication())->get_user();
            if ($user) {
                self::requireParameters(['department', 'product']);
                self::requireType((int)self::getParameter('department'), self::type_int());
                self::requireMinValue((int)self::getParameter('department'), 1);
                self::requireSameLength(self::getParameter('department'), (int)self::getParameter('department'));
                self::requireDepartmentAccess((int)self::getParameter('department'));
                self::requireType((int)self::getParameter('product'), self::type_int());
                self::requireMinValue((int)self::getParameter('product'), 0);
                self::requireSameLength(self::getParameter('product'), (int)self::getParameter('product'));
                // Add the department time bookings type
                $department_time_bookings_types = new department_time_bookings_types_o();
                $department_time_bookings_types->add(
                    (int)self::getParameter('department'),
                    (self::isParametersSet(['name']) ? (string)self::getParameter('name') : null),
                    (int)self::getParameter('product'),
                    (string)(self::isParametersSet(['description']) ? self::getParameter('description') : null),
                    (int)(self::isParametersSet(['duration']) ? (int)self::getParameter('duration') : 0)
                );
                (new logs_o())->add('department_time_bookings_types', 'global', 0, $user->id, 'DEPARTMENT_TIME_BOOKINGS_TYPES_POST', 'Add department time bookings types');
                $response->success($department_time_bookings_types->asArray());
            } else {
                (new logs_o())->add('department_time_bookings_types', 'global', 0, 0, 'DEPARTMENT_TIME_BOOKINGS_TYPES_POST', 'Add department time bookings types failed');
                $response->error('Invalid session', 400);
            }
        },
            [
                'department_timebookings_types_post' => 'Add department time bookings types',
            ]
        );

        /** Department Time Bookings -> Types -> Update */
        $this->put('/department/timebookings/types', function () {
            global $response;
            self::requirePermission('department_timebookings_types_put');
            $user = (new authentication())->get_user();
            if ($user) {
                self::requireParameters(['id']);
                self::requireType((int)self::getParameter('id'), self::type_int());
                self::requireMinValue((int)self::getParameter('id'), 1);
                self::requireSameLength(self::getParameter('id'), (int)self::getParameter('id'));
                $department_time_bookings_types = new department_time_bookings_types_o();
                $department_time_bookings_types->select(
                    (int)self::getParameter('id')
                );
                // Require the department access
                self::requireDepartmentAccess((int)$department_time_bookings_types->department->value());
                // Update the department time bookings type
                $department_time_bookings_types->update([
                    ...(self::isParametersSet(['name']) ? ['name' => (string)self::getParameter('name')] : []),
                    ...(self::isParametersSet(['product']) ? ['product' => (int)self::getParameter('product')] : []),
                    ...(self::isParametersSet(['description']) ? ['description' => (string)self::getParameter('description')] : []),
                    ...(self::isParametersSet(['duration']) ? ['duration' => (int)self::getParameter('duration')] : []),
                ]);
                (new logs_o())->add('department_time_bookings_types', 'global', 0, $user->id, 'DEPARTMENT_TIME_BOOKINGS_TYPES_PUT', 'Update department time bookings types');
                $response->success($department_time_bookings_types->asArray());
            } else {
                (new logs_o())->add('department_time_bookings_types', 'global', 0, 0, 'DEPARTMENT_TIME_BOOKINGS_TYPES_PUT', 'Update department time bookings types failed');
                $response->error('Invalid session', 400);
            }
        },
            [
                'department_timebookings_types_put' => 'Update department time bookings types',
            ]
        );

        /** Department Time Bookings -> Types -> Delete */
        $this->delete('/department/timebookings/types', function () {
            global $response;
            self::requirePermission('department_timebookings_types_delete');
            $user = (new authentication())->get_user();
            if ($user) {
                self::requireParameters(['id']);
                self::requireType((int)self::getParameter('id'), self::type_int());
                self::requireMinValue((int)self::getParameter('id'), 1);
                self::requireSameLength(self::getParameter('id'), (int)self::getParameter('id'));
                $department_time_bookings_types = new department_time_bookings_types_o();
                $department_time_bookings_types->select(
                    (int)self::getParameter('id')
                );
                // Require the department access
                self::requireDepartmentAccess((int)$department_time_bookings_types->department->value());
                // Delete the department time bookings type
                $department_time_bookings_types->delete();
                (new logs_o())->add('department_time_bookings_types', 'global', 0, $user->id, 'DEPARTMENT_TIME_BOOKINGS_TYPES_DELETE', 'Delete department time bookings types');
                $response->success(['success' => true]);
            } else {
                (new logs_o())->add('department_time_bookings_types', 'global', 0, 0, 'DEPARTMENT_TIME_BOOKINGS_TYPES_DELETE', 'Delete department time bookings types failed');
                $response->error('Invalid session', 400);
            }
        },
            [
                'department_timebookings_types_delete' => 'Delete department time bookings types',
            ]
        );

        /** Department Time Bookings -> Entries */
        $this->get('/department/timebookings/entries', function () {
            global $response;
            self::requirePermission('department_timebookings_entries_get');
            $user = (new authentication())->get_user();
            if ($user) {
                $specific_department = null;
                if (self::isParametersSet(['id'])) {
                    self::requireType((int)self::getParameter('id'), self::type_int());
                    self::requireMinValue((int)self::getParameter('id'), 1);
                    self::requireSameLength(self::getParameter('id'), (int)self::getParameter('id'));
                    // Get the object
                    $department_time_bookings_entries = new department_time_bookings_entries_o();
                    $department_time_bookings_entries->select(
                        (int)self::getParameter('id')
                    );
                    // Require the department access
                    self::requireDepartmentAccess((int)$department_time_bookings_entries->department->value());
                    $response->success($department_time_bookings_entries->asArray());
                }
                $department_time_bookings_entries = new department_time_bookings_entries_o();
                $result = $department_time_bookings_entries->listObjectsWithPaginationIfSet(
                    function ($tmp_object_array) {
                        return [
                            ...$tmp_object_array,
                            'id' => (int)$tmp_object_array['id'],
                            'department' => (int)$tmp_object_array['department'],
                            'type' => (int)$tmp_object_array['type'],
                            'start' => (string)$tmp_object_array['start'],
                            'end' => (string)$tmp_object_array['end'],
                            'note' => $tmp_object_array['note'],
                            'reg' => $tmp_object_array['reg'],
                            'phone' => (int)$tmp_object_array['phone'],
                            'phone_country_code' => (int)$tmp_object_array['phone_country_code'],
                        ];
                    },
                    $department_time_bookings_entries->forceRestrictFilters(
                        [
                            // This makes sure that the user can only see orders from the departments they explicitly have access to
                            'department' => ($specific_department ?? $user->getGroup()->getDepartments()),
                        ]
                    )
                );
                (new logs_o())->add('department_time_bookings_entries', 'global', 0, $user->id, 'DEPARTMENT_TIME_BOOKINGS_ENTRIES_GET', 'Get department time bookings entries');
                $response->success($result);
            } else {
                (new logs_o())->add('department_time_bookings_entries', 'global', 0, 0, 'DEPARTMENT_TIME_BOOKINGS_ENTRIES_GET', 'Get department time bookings entries failed');
                $response->error('Invalid session', 400);
            }
        },
            [
                'department_timebookings_entries_get' => 'List department time bookings entries, in the departments the user has access to',
            ]
        );

        /** Department Time Bookings -> Entries -> Add */
        $this->post('/department/timebookings/entries', function () {
            global $response;
            self::requirePermission('department_timebookings_entries_post');
            $user = (new authentication())->get_user();
            if ($user) {
                self::requireParameters(['department', 'type', 'start']);
                self::requireType((int)self::getParameter('department'), self::type_int());
                self::requireMinValue((int)self::getParameter('department'), 1);
                self::requireSameLength(self::getParameter('department'), (int)self::getParameter('department'));
                self::requireDepartmentAccess((int)self::getParameter('department'));

                // Get the type
                self::requireType((int)self::getParameter('type'), self::type_int());
                self::requireMinValue((int)self::getParameter('type'), 1);
                self::requireSameLength(self::getParameter('type'), (int)self::getParameter('type'));

                // Get the start time
                self::requireType((string)self::getParameter('start'), self::type_string());
                self::requireMinLength('start', 1);
                self::requireMaxLength('start', 255);
                self::requireSameLength(self::getParameter('start'), (string)self::getParameter('start'));
                self::requireDateFormat((string)self::getParameter('start'), 'Y-m-d H:i:s');

                // Check if the department exists
                $department = new \objects\departments_o();
                $department->select((int)self::getParameter('department'));
                if (!$department->exists()) {
                    (new logs_o())->add('department_time_bookings_entries', 'global', 0, $user->id, 'DEPARTMENT_TIME_BOOKINGS_ENTRIES_POST', 'Department not found');
                    $response->error('Department not found', 404);
                }
                // Check if the department has time bookings enabled
                $variable = $department->isModuleTimeBookingsEnabled();
                if (!$variable) {
                    (new logs_o())->add('department_time_bookings_entries', 'global', 0, $user->id, 'DEPARTMENT_TIME_BOOKINGS_ENTRIES_POST', 'Department time bookings are not enabled');
                    $response->error('Department time bookings are not enabled', 404);
                }
                // Check if the type exists
                $department_time_bookings_types = new department_time_bookings_types_o();
                $department_time_bookings_types->select((int)self::getParameter('type'));
                if (!$department_time_bookings_types->exists()) {
                    (new logs_o())->add('department_time_bookings_entries', 'global', 0, $user->id, 'DEPARTMENT_TIME_BOOKINGS_ENTRIES_POST', 'Department time bookings type not found');
                    $response->error('Department time bookings type not found', 404);
                }
                // Check if the type belongs to the department
                if ((int)$department_time_bookings_types->department->value() !== (int)$department->id) {
                    (new logs_o())->add('department_time_bookings_entries', 'global', 0, $user->id, 'DEPARTMENT_TIME_BOOKINGS_ENTRIES_POST', 'Department time bookings type does not belong to the department');
                    $response->error('Department time bookings type does not belong to the department', 404);
                }
                // Calculate the end time
                $start_time = \DateTime::createFromFormat('Y-m-d H:i:s', (string)self::getParameter('start'));
                if (!$start_time) {
                    (new logs_o())->add('department_time_bookings_entries', 'global', 0, $user->id, 'DEPARTMENT_TIME_BOOKINGS_ENTRIES_POST', 'Invalid start time format');
                    $response->error('Invalid start time format', 400);
                }
                $duration = (int)$department_time_bookings_types->duration->value();
                if ($duration <= 0) {
                    (new logs_o())->add('department_time_bookings_entries', 'global', 0, $user->id, 'DEPARTMENT_TIME_BOOKINGS_ENTRIES_POST', 'Invalid duration for department time bookings type');
                    $response->error('Invalid duration for department time bookings type', 400);
                }
                $end_time = clone $start_time;
                $end_time->modify("+{$duration} minutes");

                // Check if the addons parameter is set
                $addons = [];
                if (self::isParametersSet(['addons'])) {
                    self::requireType((array)self::getParameter('addons'), self::type_array());
                    $addons = (array)self::getParameter('addons');
                    // Validate each addon
                    foreach ( $addons as $addon ) {
                        self::requireType((int)$addon, self::type_int());
                        self::requireMinValue((int)$addon, 1);
                        self::requireSameLength($addon, (int)$addon);
                        // Check if the addon is allowed on the primary type
                        $product_options = new product_options_o();
                        if (!$product_options->isOptionAllowedOnType(
                            (int)$addon,
                            (int)$department_time_bookings_types->product->value()
                        )) {
                            (new logs_o())->add('department_time_bookings_entries', 'global', 0, $user->id, 'DEPARTMENT_TIME_BOOKINGS_ENTRIES_POST', 'This product option is not allowed on the primary product type');
                            $response->error('This product option is not allowed on the primary product type', 400);
                        }
                    }
                }


                // Add the department time bookings entry
                $department_time_bookings_entries = new department_time_bookings_entries_o();
                $department_time_bookings_entries->add(
                    (int)self::getParameter('department'),
                    (int)self::getParameter('type'),
                    (string)$start_time->format('Y-m-d H:i:s'),
                    (string)$end_time->format('Y-m-d H:i:s'),
                    (int)(self::isParametersSet(['phone_country_code']) ? self::getParameter('phone_country_code') : 0),
                    (int)(self::isParametersSet(['phone']) ? self::getParameter('phone') : 0),
                    (self::isParametersSet(['note']) ? (string)self::getParameter('note') : null),
                    (self::isParametersSet(['reg']) ? (string)self::getParameter('reg') : null),
                    (array)$addons,
                );
                (new logs_o())->add('department_time_bookings_entries', 'global', 0, $user->id, 'DEPARTMENT_TIME_BOOKINGS_ENTRIES_POST', 'Add department time bookings entries');
                $response->success($department_time_bookings_entries->asArray());
            } else {
                (new logs_o())->add('department_time_bookings_entries', 'global', 0, 0, 'DEPARTMENT_TIME_BOOKINGS_ENTRIES_POST', 'Add department time bookings entries failed');
                $response->error('Invalid session', 400);
            }
        },
            [
                'department_timebookings_entries_post' => 'Add department time bookings entries',
            ]
        );
    }
}