<?php

namespace routes;

use classes\authentication;
use customers\economicCustomers;
use objects\logs_o;
use objects\users_o;
use traits\route_t;

class customerSearchRoute
{
    use route_t;

    public function run(): void
    {
        //TODO: Remove this, this is deprecated in favor of the new search endpoint
        $this->post('/customers/search', function () {
            // Require the user to be logged in
            global $response;
            $this->requirePermission('search_customers');
            // 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 pagination, search and sort parameters are set
                if (!isset($data['search'])) {
                    $response->error('Missing required body parameter search', 400);
                }
                if (!isset($data['filter'])) {
                    $response->error('Missing required body parameter filter', 400);
                }
                // Check if the search parameter is valid
                $allowedSearchFilters = (new economicCustomers())->allowed_search_filters_customers();
                if (!in_array($data['filter'], $allowedSearchFilters)) {
                    $response->error('Invalid search parameter', 400);
                }
                (new logs_o())->add('customers', 'global', 1, $user->id, 'SEARCH_CUSTOMERS', 'Successfully retrieved customers meeting search criteria');
                // Return the list of users
                $response->success(
                    (array)(new economicCustomers())->searchCustomers((string)$data['search'], (string)$data['filter'])
                );
            } else {
                // Log the incident
                (new logs_o())->add('customers', 'global', 1, 0, 'SEARCH_CUSTOMERS', 'No user found, or invalid session');
                // Return an error
                $response->error('Invalid session', 400);
            }
        },
            [
                'search_customers' => 'Search for customers'
            ]
        );

        self::get('/customers', function () {
            // Require the user to be logged in
            global $response;
            self::requirePermission('search_customers');
            // Get the user object
            $user = (new authentication())->get_user();
            // Check if the request was successful
            if ($user) {
                // Check if the pagination parameters are set
                $page = self::fromRequest('page') ?? 1;
                $limit = self::fromRequest('limit') ?? 100;
                $search = self::fromRequest('search') ?? null;
                $filter = self::fromRequest('filter') ?? null;
                // Log the incident
                (new logs_o())->add('customers', 'global', 1, $user->id, 'LIST_CUSTOMERS', 'Successfully listed customers');
                // Create the economic customers object
                $economicCustomers = new economicCustomers();
                $result = (object)$economicCustomers->listCustomers(
                    (int)$page,
                    (int)$limit,
                    $search,
                    $filter
                );
                // Parse the pagination meta from E-conomic to the standard format used in this application
                $response->paginate(
                    $page,
                    $limit,
                    $result->pagination->results,
                    $search,
                    $filter
                );
                // Create the users object
                $users_o = new users_o();
                // Return the list of users
                $response->success(
                    self::parseFunction($result->collection, function ($customer) use ($users_o) {
                        // Add the user id to the customer object
                        $customer->id = null;
                        // Update the user id if the customer is imported from E-conomic
                        if ($users_o->isImportedFromEconomic($customer->customerNumber)) {
                            $customer->id = $users_o->getUserIdFromEconomic($customer->customerNumber);
                        }
                        return $customer;
                    })
                );
            } else {
                // Log the incident
                (new logs_o())->add('customers', 'global', 1, 0, 'LIST_CUSTOMERS', 'No user found, or invalid session');
                // Return an error
                $response->error('Invalid session', 400);
            }
        },
            [
                'search_customers' => 'Search for customers, and list all customers if no search is provided'
            ]
        );
    }

    private static function parseFunction($collection, \Closure $param): array
    {
        $result = [];
        foreach ( $collection as $item ) {
            $result[] = $param($item);
        }
        return $result;
    }
}