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

namespace routes;

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

class departmentSelfserveQuestionsRoute
{
    use route_t;

    public function run(): void
    {
        /**
         * List department self-serve questions
         */
        $this->get('/department/selfserve/questions', function () {
            global $response;
            $this->requirePermission('list_department_selfserve_questions');
            $user = (new authentication())->get_user();
            if ($user) {
                (new logs_o())->add('department_selfserve_questions', 'global', 1, $user->id, 'LIST_QUESTIONS', 'User listed department self-serve questions');
                
                $questions_o = new department_selfserve_questions_o();
                $authorized_department_ids = $user->getGroup()->getDepartments();
                $has_view_all_permission = $this->hasPermission('view_all_department_selfserve_questions');
                
                // If an ID is provided, return that specific question
                if (self::isParametersSet(['id'])) {
                    $questions_o->select((int)self::getParameter('id'));
                    if ($questions_o->exists()) {
                        if (!in_array((int)$questions_o->department->value(), $authorized_department_ids)) {
                            if (!$has_view_all_permission) {
                                $response->error('You do not have access to this department', 403);
                            }
                        }
                        $response->success($questions_o->asArray());
                    } else {
                        $response->error('Question 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(
                    $questions_o->setSearchableFields(['id', 'department', 'lane', 'product', 'question', 'description', 'deleted_at'])
                        ->listObjectsWithPaginationIfSet(function ($question) {
                            $q = new department_selfserve_questions_o();
                            $q->select((int)$question['id']);
                            return $q->asArray();
                        }, $questions_o->forceRestrictFilters($filters))
                );
            } else {
                $response->error('Invalid session', 400);
            }
        }, [
            'list_department_selfserve_questions' => 'List all department self-serve questions',
            'view_all_department_selfserve_questions' => 'View questions from all departments'
        ]);

        /**
         * Add a department self-serve question
         */
        $this->post('/department/selfserve/questions', function () {
            global $response;
            $this->requirePermission('add_department_selfserve_questions');
            $user = (new authentication())->get_user();
            if ($user) {
                $department = (int)$response->getRequestParameter('department');
                $lane = (int)$response->getRequestParameter('lane');
                $product = (int)$response->getRequestParameter('product');
                $question = (string)$response->getRequestParameter('question');
                $description = (string)$response->getRequestParameter('description');
                $condition_id = $response->isRequestParameterSet('condition_id') ? (int)$response->getRequestParameter('condition_id') : null;
                $order_priority = (int)($response->getRequestParameter('order_priority') ?? 0);

                if (!$department || !$lane || !$product || !$question || !$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 {
                    $question_o = (new department_selfserve_questions_o())->add(
                        $department,
                        $lane,
                        $product,
                        $question,
                        $description,
                        $condition_id,
                        $order_priority
                    );
                    (new logs_o())->add('department_selfserve_questions', 'global', 1, $user->id, 'ADD_QUESTION', 'User added a department self-serve question: ' . $question);
                    $response->success($question_o->asArray());
                } catch (\Exception $e) {
                    $response->error($e->getMessage(), 500);
                }
            } else {
                $response->error('Invalid session', 400);
            }
        }, [
            'add_department_selfserve_questions' => 'Add a department self-serve question'
        ]);

        /**
         * Update a department self-serve question
         */
        $this->put('/department/selfserve/questions', function () {
            global $response;
            $this->requirePermission('edit_department_selfserve_questions');
            $user = (new authentication())->get_user();
            if ($user) {
                self::requireParameters(['id']);
                $id = (int)self::getParameter('id');
                $question_o = new department_selfserve_questions_o();
                $question_o->select($id);

                if (!$question_o->exists()) {
                    $response->error('Question not found', 404);
                }

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

                if (self::isParametersSet(['department'])) {
                    $new_department = (int)self::getParameter('department');
                    if (!in_array($new_department, $authorized_department_ids)) {
                        $response->error('You do not have access to the new department', 403);
                    }
                    $question_o->department->set($new_department);
                }
                if (self::isParametersSet(['lane'])) {
                    $question_o->lane->set((int)self::getParameter('lane'));
                }
                if (self::isParametersSet(['product'])) {
                    $question_o->product->set((int)self::getParameter('product'));
                }
                if (self::isParametersSet(['question'])) {
                    $question_o->question->set((string)self::getParameter('question'));
                }
                if (self::isParametersSet(['description'])) {
                    $question_o->description->set((string)self::getParameter('description'));
                }
                if (self::isParametersSet(['condition_id'])) {
                    $question_o->condition_id->set(self::getParameter('condition_id') === null ? null : (int)self::getParameter('condition_id'));
                }
                if (self::isParametersSet(['order_priority'])) {
                    $question_o->order_priority->set((int)self::getParameter('order_priority'));
                }

                (new logs_o())->add('department_selfserve_questions', 'global', 1, $user->id, 'EDIT_QUESTION', 'User updated department self-serve question ID: ' . $id);
                $response->success($question_o->asArray());
            } else {
                $response->error('Invalid session', 400);
            }
        }, [
            'edit_department_selfserve_questions' => 'Edit a department self-serve question'
        ]);

        /**
         * Delete a department self-serve question
         */
        $this->delete('/department/selfserve/questions', function () {
            global $response;
            $this->requirePermission('delete_department_selfserve_questions');
            $user = (new authentication())->get_user();
            if ($user) {
                self::requireParameters(['id']);
                $id = (int)self::getParameter('id');
                $question_o = new department_selfserve_questions_o();
                $question_o->select($id);

                if (!$question_o->exists()) {
                    $response->error('Question not found', 404);
                }

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

                $question_o->delete();
                (new logs_o())->add('department_selfserve_questions', 'global', 1, $user->id, 'DELETE_QUESTION', 'User deleted department self-serve question ID: ' . $id);
                $response->success('Question deleted');
            } else {
                $response->error('Invalid session', 400);
            }
        }, [
            'delete_department_selfserve_questions' => 'Delete a department self-serve question'
        ]);
    }
}
