<?php

namespace routes;

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

class potentialOrderMatchesRoute
{
    use route_t;

    public function run(): void
    {
        $this->get('/orders/sync/potential-matches', function () {
            // Require the user to be logged in
            global $response;
            self::requirePermission('list_potential_order_matches');
            // Check if the user has permission to list all potential order matches
            if (self::hasPermission('list_all_potential_order_matches')) {
                $this->requirePermission('list_all_potential_order_matches');
            } else {
                $this->requirePermission('list_own_potential_order_matches');
            }
            // Get the user object
            $user = (new authentication())->get_user();
            // Check if the request was successful
            if ($user) {
                // Log the incident
                (new logs_o())->add('potential_order_matches', 'global', 1, $user->id, 'LIST_OWN_POTENTIAL_ORDER_MATCHES', 'User accessed the list of potential order matches');
                $potentialOrderMatches = new \objects\xlvask_potential_order_matches_o();
                // Return the list of potential order matches
                $response->success(
                    $potentialOrderMatches
                        ->setSearchableFields([
                            'id',
                            'wash_id',
                            'order_id',
                            'customer_id',
                            'customer_number',
                            'ignore_duplicate',
                            'department',
                            'created_at',
                            'updated_at',
                            'deleted_at',
                        ])
                        ->listObjectsWithPaginationIfSet(
                            function ($match) use ($potentialOrderMatches, $user) {
                                return [
                                    'id' => (int)$match['id'],
                                    'wash_id' => (string)$match['wash_id'],
                                    'order_id' => (int)$match['order_id'],
                                    'customer_id' => (string)$match['customer_id'],
                                    'customer_number' => (int)$match['customer_number'],
                                    'ignore_duplicate' => (int)$match['ignore_duplicate'],
                                    'department' => (int)$match['department'],
                                    'created_at' => (string)$match['created_at'],
                                    'updated_at' => (string)$match['updated_at'],
                                    'deleted_at' => $match['deleted_at'] ? (string)$match['deleted_at'] : null,
                                ];
                            },
                            $potentialOrderMatches->forceRestrictFilters(
                                [
                                    // This makes sure that the user can only see department matches that belong to their departments
                                    'department' => $user->getGroup()->getDepartments()
                                ]
                            )
                        )
                );
            } else {
                // Log the incident
                (new logs_o())->add('potential_order_matches', 'global', 1, 0, 'LIST_OWN_POTENTIAL_ORDER_MATCHES', 'No user found, or invalid session');
                // Return an error
                $response->error('Invalid session', 400);
            }
        },
            [
                'list_potential_order_matches' => 'List potential order matches, provided the user has either list_all_potential_order_matches, or list_own_potential_order_matches permission',
                'list_own_potential_order_matches' => 'List all potential order matches for the logged in user',
                'list_all_potential_order_matches' => 'List all potential order matches for all users (superuser only)',
            ]
        );

        $this->post('/orders/sync/potential-matches/ignore-duplicate', function () {
            // Require the user to be logged in
            global $response;
            self::requirePermission('ignore_duplicate_potential_order_matches');
            // Get the user object
            $user = (new authentication())->get_user();
            // Check if the request was successful
            if ($user) {
                // Log the incident
                (new logs_o())->add('potential_order_matches', 'global', 1, $user->id, 'IGNORE_DUPLICATE_POTENTIAL_ORDER_MATCHES', 'User ignored duplicate potential order matches');
                // Get the potential order match data from the request
                self::requireParameters(['id']);
                self::requireType((int)self::getParameter('id'), self::type_int());
                self::requireMinValue((int)self::getParameter('id'), 1); // Ensure the ID is a positive integer
                $potentialOrderMatch = new xlvask_potential_order_matches_o();
                $potentialOrderMatch->select((int)self::getParameter('id'));
                if (!$potentialOrderMatch->exists()) {
                    // Log the incident
                    (new logs_o())->add('potential_order_matches', 'global', 1, $user->id, 'IGNORE_DUPLICATE_POTENTIAL_ORDER_MATCHES', 'Potential order match not found');
                    // Return an error response
                    $response->error('Potential order match not found', 404);
                }
                // Check if the user has permission to ignore duplicate potential order matches in the department of the potential order match
                self::requireDepartmentAccess((int)$potentialOrderMatch->department->value());
                // Set the ignore_duplicate field to 1
                $potentialOrderMatch->ignore_duplicate->set(1);
                // Save the potential order match
                $potentialOrderMatch->objectChanged();
                // Return a success response
                $response->success(
                    $potentialOrderMatch->asArray(),
                    200,
                );
            } else {
                // Log the incident
                (new logs_o())->add('potential_order_matches', 'global', 1, 0, 'IGNORE_DUPLICATE_POTENTIAL_ORDER_MATCHES', 'No user found, or invalid session');
                // Return an error response
                $response->error('Invalid session', 400);
            }
        },
            [
                'ignore_duplicate_potential_order_matches' => 'Ignore duplicate potential order matches for a specific wash and order',
            ]
        );
    }
}