<?php
// Copyright (c) Pickware GmbH. All rights reserved.
// This file is part of software that is released under a proprietary license.
// You must not copy, modify, distribute, make publicly available, or execute
// its contents or parts thereof without express permission by the copyright
// holder, unless otherwise permitted by law.

use Shopware\CustomModels\ViisonPickwareERP\Warehouse\Warehouse;
use Shopware\CustomModels\ViisonPickwareMobile\PickProfile\PickProfile;
use Shopware\Plugins\ViisonCommon\Classes\ApiException;

/**
 * This controller provides the custom 'pickProfiles' API resource and all its available actions.
 */
class Shopware_Controllers_Api_ViisonPickwareMobilePickProfiles extends Shopware_Controllers_Api_Rest
{
    /**
     * GET /api/pickProfiles/{id}/estimatedNumberOfOrdersInWarehouse/{estimatedNumberOfOrdersInWarehouse}
     */
    public function getEstimatedNumberOfOrdersInWarehouseAction()
    {
        // Try to find the requested pick profile
        $pickProfileId = $this->Request()->getParam('id', 0);
        $pickProfile = $this->get('models')->find(PickProfile::class, $pickProfileId);
        if (!$pickProfile) {
            throw new ApiException('not_found/pick_profile', 404);
        }

        // Try to find the requested warehouse
        $warehouseId = $this->Request()->getParam('estimatedNumberOfOrdersInWarehouse', 0);
        $warehouse = $this->get('models')->find(Warehouse::class, $warehouseId);
        if (!$warehouse) {
            throw new ApiException('not_found/warehouse', 404);
        }

        // Fetch the number of orders passing the profile's configured filter in the requested warehouse
        $validOrderIds = $this->get('viison_pickware_mobile.pick_profile_order_filter_service')->getIdsOfOrdersPassingFilterOfPickProfile(
            $pickProfile,
            $warehouse
        );

        $this->View()->assign([
            'success' => true,
            'data' => [
                'estimatedNumberOfOrders' => count($validOrderIds),
            ],
        ]);
    }
}
