<?php
/**
 * @author Aitoc Team
 * @copyright Copyright (c) 2020 Aitoc (https://www.aitoc.com)
 * @package Aitoc_PreOrders
 */

/**
 * Copyright © 2018 Aitoc. All rights reserved.
 * Developed by Alex Yakimovich
 */

namespace Aitoc\PreOrders\Plugin\Sales\Model\Order\Shipment;

use Aitoc\PreOrders\Helper\PreOrder as PreOrderHelper;
use Magento\Sales\Model\Order\Shipment\ShipmentValidator as MagentoShipmentValidator;
use Magento\Sales\Api\Data\ShipmentInterface;

/**
 * Class ShipmentValidator
 */
class ShipmentValidator
{
    /**
     * @var PreOrderHelper
     */
    private $preOrderHelper;

    /**
     * @param PreOrderHelper $preOrderHelper
     */
    public function __construct(PreOrderHelper $preOrderHelper)
    {
        $this->preOrderHelper = $preOrderHelper;
    }

    /**
     * Validate pre-order state for shipment items before shipment creation
     *
     * @param MagentoShipmentValidator $subject
     * @param ShipmentInterface $entity
     * @param array $validators
     */
    public function beforeValidate(
        MagentoShipmentValidator $subject,
        ShipmentInterface $entity,
        array $validators
    ) {
        $items = $entity->getItems();
        foreach ($items as $item) {
            $orderItem = $item->getOrderItem();
            if (!$this->preOrderHelper->isOrderItemCanBeShipped($orderItem, $orderItem->getId())) {
                $item->setQty(0);
            }
        }
    }
}
