<?php

namespace routes;

use classes\authentication;
use objects\logs_o;
use objects\order_items_o;
use objects\orders_o;
use traits\route_t;

class orderItemsRoute
{
    use route_t;

    public function run(): void
    {
        $this->post('/order/items', function () {
            // Require the user to be logged in
            global $response;
            $this->requirePermission('add_order_items');
            // 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['order_id'])) {
                    $response->error('Order ID is required', 400);
                }
                if (!isset($data['product_id'])) {
                    $response->error('Product ID is required', 400);
                }
                if (!isset($data['quantity'])) {
                    $response->error('Quantity is required', 400);
                }
                $related_item_id = null;
                // Check if the related_item_id is set
                if (self::isParametersSet(['related_item_id'])) {
                    // Check if the related_item_id is null, if so continue
                    if ($data['related_item_id'] !== null) {
                        // Check if the related_item_id is a number
                        if (!is_numeric($data['related_item_id'])) {
                            $response->error('Related item ID must be a number', 400);
                        }
                        $related_item_id = (int)$data['related_item_id'];
                    }
                }
                $notes = null;
                // Check if the notes is set
                if (self::isParametersSet(['notes'])) {
                    // Check if the notes is null, if so continue
                    if (self::getParameter('notes') !== null) {
                        // Check if the notes is a string
                        if (!is_string(self::getParameter('notes'))) {
                            $response->error('Notes must be a string', 400);
                        }
                        $notes = (string)self::getParameter('notes');
                    }
                }
                $price = null;
                // Check if the price is set
                if (self::isParametersSet(['price'])) {
                    // Check if the price is null, if so continue
                    if (self::getParameter('price') !== null) {
                        // Check if the price is a number
                        if (!is_numeric(self::getParameter('price'))) {
                            $response->error('Price must be a number', 400);
                        }
                        $price = (int)self::getParameter('price');
                    }
                }

                // Add the order item to the order This is done individually, to make the notes to the individual order items possible
                $order_items = (new order_items_o());
                // Add the order item to the order
                $order_items->addItemToOrder((int)$data['order_id'], (int)$data['product_id'], (int)$user->id, (int)$data['quantity'], $related_item_id, $notes, $price);
                // Return the list of departments
                $response->success(
                    $order_items->getItemAsArray()
                );
            } else {
                // Log the incident
                (new logs_o())->add('departments', 'global', 1, 0, 'ADD_ORDER_ITEMS', 'No user found, or invalid session');
                // Return an error
                $response->error('Invalid session', 400);
            }
        },
            [
                'add_order_items' => 'Add order items'
            ]
        );

        $this->get('/order/items', function () {
            // Require the user to be logged in
            global $response;
            // Check if the user is requesting their own order items
            $isCustomerAccess = ($this->hasPermission('user') && !($this->hasPermission('list_order_items')));
            $user = (new authentication())->get_user();
            if ($isCustomerAccess) {
                $hasPermission = $this->hasPermission('list_own_order_items');
                $hasAttribute = $user->showPricesOnBookingPage(); // Check if the user has the attribute to show prices on the booking page
                if (!$hasPermission && !$hasAttribute) {
                    $response->error('You do not have permission to list order items, neither your own nor all orders', 403);
                }
            } else {
                $this->requirePermission('list_order_items');
            }
            // Check if the request was successful
            if ($user) {
                // Get the post data
                $data = $_GET;
                // Check if the required fields are set
                if (!(int)$data['order_id']) {
                    $response->error('Order ID is required', 400);
                }
                // Check if the order_id is a valid number
                if (!is_numeric($data['order_id'])) {
                    $response->error('Order ID must be a number', 400);
                }
                // Check if the order exists
                if (!(new orders_o())->getOrderById((int)$data['order_id'])->exists()) {
                    $response->error('Order not found', 404);
                }
                $order = (new orders_o())->getOrderById((int)$data['order_id']);
                // If the user is requesting their own order items, check if the order belongs to them
                if ($isCustomerAccess && !$order->isOwnOrder((int)$user->customer_number->value())) {
                    $response->error('Order does not belong to the user', 400);
                };
                // Apply the departments unique pricing
                $orderItems = $order->getOrderItems($order->id);
                $orderItems = $order->applyDepartmentPrices($orderItems, $order->department_id->value());
                // Return the list of departments
                $response->success(
                    $orderItems
                );
            } else {
                // Log the incident
                (new logs_o())->add('departments', 'global', 1, 0, 'LIST_ORDER_ITEMS', 'No user found, or invalid session');
                // Return an error
                $response->error('Invalid session', 400);
            }
        },
            [
                'list_order_items' => 'List all order items'
            ]
        );

        $this->delete('/order/items', function () {
            // Require the user to be logged in
            global $response;
            $this->requirePermission('delete_order_items');
            // Get the user object
            $user = (new authentication())->get_user();
            // Check if the request was successful
            if ($user) {
                // Get the query data
                $data = $_GET;
                // Check if the required fields are set
                if (!isset($data['id'])) {
                    $response->error('Order Item ID is required', 400);
                }
                // Delete the order item
                (new order_items_o())->removeOrderItem((int)$data['id']);
                // Return the list of departments
                $response->success(
                    ['message' => 'Order item deleted']
                );
            } else {
                // Log the incident
                (new logs_o())->add('departments', 'global', 1, 0, 'DELETE_ORDER_ITEMS', 'No user found, or invalid session');
                // Return an error
                $response->error('Invalid session', 400);
            }
        },
            [
                'delete_order_items' => 'Delete order items'
            ]
        );

        $this->put('/order/items', function () {
            // Require the user to be logged in
            global $response;
            $this->requirePermission('edit_order_items');
            // Get the user object
            $user = (new authentication())->get_user();
            // Check if the request was successful
            if ($user) {
                // Get the post data
                $data = json_decode(file_get_contents('php://input'), true);
                // Check if the required fields are set
                if (!isset($data['id'])) {
                    $response->error('Order Item ID is required', 400);
                }
                if (!isset($data['price'])) {
                    $response->error('Price is required', 400);
                }
                if (!isset($data['notes'])) {
                    $response->error('Notes is required', 400);
                }
                if (!isset($data['reference'])) {
                    $response->error('Reference is required', 400);
                }
                if (!isset($data['quantity'])) {
                    $response->error('Quantity is required', 400);
                }
                // Update the order item
                (new order_items_o())->updateOrderItem((int)$data['id'], (int)$data['price'], (string)$data['notes'], (string)$data['reference'], (int)$data['quantity']);
                // Log the incident
                (new logs_o())->add('departments', 'global', 1, $user->id, 'EDIT_ORDER_ITEMS', 'Changed order item: ' . $data['id']);
                // Return the list of departments
                $response->success(
                    ['message' => 'Order item updated']
                );
            } else {
                // Log the incident
                (new logs_o())->add('departments', 'global', 1, 0, 'EDIT_ORDER_ITEMS', 'No user found, or invalid session');
                // Return an error
                $response->error('Invalid session', 400);
            }
        },
            [
                'edit_order_items' => 'Edit order items'
            ]
        );
    }
}