<?php

namespace routes;

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

class vehiclePlateLastOrdersRoute
{
    use route_t;

    public function run(): void
    {
        $this->get('/department/vehicle/order/history', function () {
            // Require the user to be logged in
            global $response;
            $this->requirePermission('department_vehicle_order_last_five');
            // Get the user object
            $user = (new authentication())->get_user();
            // Check if the request was successful
            if ($user) {
                // Make sure the vehicle plate is set
                if (!(string)$this->fromRequest('plate')) {
                    $response->error('Plate parameter is required', 400);
                }
                // Log the incident
                (new logs_o())->add('orders', 'global', 1, $user->id, 'FETCH_VEHICLE_ORDER_HISTORY', 'Successfully fetched vehicle order history');
                // Return the list of departments
                $response->success(
                    (new orders_o())->getOrderHistoryByVehiclePlate($this->fromRequest('plate'), 5)
                );
            } else {
                // Log the incident
                (new logs_o())->add('orders', 'global', 1, 0, 'FETCH_VEHICLE_ORDER_HISTORY', 'No user found, or invalid session');
                // Return an error
                $response->error('Invalid session', 400);
            }
        },
            [
                'department_vehicle_order_last_five' => 'Fetch the last five orders for a vehicle plate'
            ]
        );
    }
}