<?php
/**
 * Route for department self-serve conditions
 */

namespace routes;

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

class departmentSelfserveConditionsRoute
{
    use route_t;

    public function run(): void
    {
        /**
         * List department self-serve conditions
         */
        $this->get('/department/selfserve/conditions', function () {
            global $response;
            $this->requirePermission('list_department_selfserve_conditions');
            $user = (new authentication())->get_user();
            if ($user) {
                (new logs_o())->add('department_selfserve_conditions', 'global', 1, $user->id, 'LIST_CONDITIONS', 'User listed department self-serve conditions');
                
                $conditions_o = new department_selfserve_conditions_o();
                $authorized_department_ids = $user->getGroup()->getDepartments();
                $has_view_all_permission = $this->hasPermission('view_all_department_selfserve_conditions');
                
                // If an ID is provided, return that specific condition
                if (self::isParametersSet(['id'])) {
                    $conditions_o->select((int)self::getParameter('id'));
                    if ($conditions_o->exists()) {
                        if (!in_array((int)$conditions_o->department->value(), $authorized_department_ids)) {
                            if (!$has_view_all_permission) {
                                $response->error('You do not have access to this department', 403);
                            }
                        }
                        $response->success($conditions_o->asArray());
                    } else {
                        $response->error('Condition not found', 404);
                    }
                }

                $filters = [];
                if (self::isParametersSet(['department'])) {
                    $requested_department = (int)self::getParameter('department');
                    if (!in_array($requested_department, $authorized_department_ids) && !$has_view_all_permission) {
                        $response->error('You do not have access to this department', 403);
                    }
                    $filters['department'] = $requested_department;
                } else {
                    if (!$has_view_all_permission) {
                        if (empty($authorized_department_ids)) {
                            $response->success([]);
                            return;
                        }
                        $filters['department'] = $authorized_department_ids;
                    }
                }

                if (self::isParametersSet(['lane'])) {
                    $filters['lane'] = (int)self::getParameter('lane');
                }

                if (self::isParametersSet(['product'])) {
                    $filters['product'] = (int)self::getParameter('product');
                }

                $response->success(
                    $conditions_o->setSearchableFields(['id', 'department', 'lane', 'product', 'condition_id', 'name', 'description', 'deleted_at'])
                        ->listObjectsWithPaginationIfSet(function ($condition) {
                            $c = new department_selfserve_conditions_o();
                            $c->select((int)$condition['id']);
                            return $c->asArray();
                        }, $conditions_o->forceRestrictFilters($filters))
                );
            } else {
                $response->error('Invalid session', 400);
            }
        }, [
            'list_department_selfserve_conditions' => 'List all department self-serve conditions',
            'view_all_department_selfserve_conditions' => 'View all department self-serve conditions'
        ]);

        /**
         * Add a department self-serve condition
         */
        $this->post('/department/selfserve/conditions', function () {
            global $response;
            $this->requirePermission('add_department_selfserve_conditions');
            $user = (new authentication())->get_user();
            if ($user) {
                $department = (int)$response->getRequestParameter('department');
                $lane = (int)$response->getRequestParameter('lane');
                $product = (int)$response->getRequestParameter('product');
                $condition_id = $response->getRequestParameter('condition_id');
                $condition_id = is_null($condition_id) || $condition_id === 'null' ? null : (int)$condition_id;
                $name = (string)$response->getRequestParameter('name');
                $description = (string)$response->getRequestParameter('description');

                if (!$department || !$lane || !$product || !$name || !$description) {
                    $response->error('Missing required fields', 400);
                }

                $authorized_department_ids = $user->getGroup()->getDepartments();
                if (!in_array($department, $authorized_department_ids)) {
                    $response->error('You do not have access to this department', 403);
                }

                try {
                    $condition_o = (new department_selfserve_conditions_o())->add(
                        $department,
                        $lane,
                        $product,
                        $name,
                        $description,
                        $condition_id
                    );
                    (new logs_o())->add('department_selfserve_conditions', 'global', 1, $user->id, 'ADD_CONDITION', 'User added department self-serve condition ' . $condition_o->id);
                    $response->success($condition_o->asArray());
                } catch (\Exception $e) {
                    $response->error($e->getMessage(), 500);
                }
            } else {
                $response->error('Invalid session', 400);
            }
        }, [
            'add_department_selfserve_conditions' => 'Add a department self-serve condition'
        ]);

        /**
         * Update a department self-serve condition
         */
        $this->put('/department/selfserve/conditions', function () {
            global $response;
            $this->requirePermission('update_department_selfserve_conditions');
            $user = (new authentication())->get_user();
            if ($user) {
                $id = (int)$response->getRequestParameter('id');
                if (!$id) {
                    $response->error('Missing required fields', 400);
                }

                $condition_o = new department_selfserve_conditions_o();
                $condition_o->select($id);
                if (!$condition_o->exists()) {
                    $response->error('Condition not found', 404);
                }

                $authorized_department_ids = $user->getGroup()->getDepartments();
                if (!in_array((int)$condition_o->department->value(), $authorized_department_ids)) {
                    $response->error('You do not have access to this department', 403);
                }

                if ($response->isRequestParameterSet('department')) {
                    $new_department = (int)$response->getRequestParameter('department');
                    if (!in_array($new_department, $authorized_department_ids)) {
                        $response->error('You do not have access to the target department', 403);
                    }
                    $condition_o->department->update($new_department);
                }
                if ($response->isRequestParameterSet('lane')) {
                    $condition_o->lane->update((int)$response->getRequestParameter('lane'));
                }
                if ($response->isRequestParameterSet('product')) {
                    $condition_o->product->update((int)$response->getRequestParameter('product'));
                }
                if ($response->isRequestParameterSet('condition_id')) {
                    $condition_id = $response->getRequestParameter('condition_id');
                    $condition_o->condition_id->update(is_null($condition_id) || $condition_id === 'null' ? null : (int)$condition_id);
                }
                if ($response->isRequestParameterSet('name')) {
                    $condition_o->name->update((string)$response->getRequestParameter('name'));
                }
                if ($response->isRequestParameterSet('description')) {
                    $condition_o->description->update((string)$response->getRequestParameter('description'));
                }

                (new logs_o())->add('department_selfserve_conditions', 'global', 1, $user->id, 'UPDATE_CONDITION', 'User updated department self-serve condition ' . $id);
                $response->success($condition_o->asArray());
            } else {
                $response->error('Invalid session', 400);
            }
        }, [
            'update_department_selfserve_conditions' => 'Update a department self-serve condition'
        ]);

        /**
         * Delete a department self-serve condition
         */
        $this->delete('/department/selfserve/conditions', function () {
            global $response;
            $this->requirePermission('delete_department_selfserve_conditions');
            $user = (new authentication())->get_user();
            if ($user) {
                $id = (int)$response->getRequestParameter('id');
                if (!$id) {
                    $response->error('Missing required fields', 400);
                }

                $condition_o = new department_selfserve_conditions_o();
                $condition_o->select($id);
                if (!$condition_o->exists()) {
                    $response->error('Condition not found', 404);
                }

                $authorized_department_ids = $user->getGroup()->getDepartments();
                if (!in_array((int)$condition_o->department->value(), $authorized_department_ids)) {
                    $response->error('You do not have access to this department', 403);
                }

                $condition_o->delete();
                (new logs_o())->add('department_selfserve_conditions', 'global', 1, $user->id, 'DELETE_CONDITION', 'User deleted department self-serve condition ' . $id);
                $response->success('Condition deleted');
            } else {
                $response->error('Invalid session', 400);
            }
        }, [
            'delete_department_selfserve_conditions' => 'Delete a department self-serve condition'
        ]);
    }
}
