<?php
/**
 * Copyright © 2018 EaDesign by Eco Active S.R.L. All rights reserved.
 * See LICENSE for license details.
 */
namespace Eadesigndev\Urgent\Model;

use Eadesigndev\Urgent\Api\Data\ShipmentDataInterface;
use Magento\Framework\Registry;
use Magento\Framework\Model\Context;
use Magento\Sales\Model\Order\Address;
use Magento\Sales\Model\OrderRepository;
use Magento\Framework\Model\AbstractModel;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Sales\Model\Order\ShipmentRepository;
use Magento\Framework\Data\Collection\AbstractDb;
use Magento\Framework\Model\ResourceModel\AbstractResource;
use Magento\Sales\Model\Convert\Order;
use Magento\Catalog\Model\ProductFactory;

#[\AllowDynamicProperties]
class ShipmentData extends AbstractModel implements ShipmentDataInterface
{
    private $searchCriteriaBuilder;

    private $orderRepository;

    private $orderInterface;

    private $shipmentRepository;

    private $shipmentId;

    private $orderId;

    private $carrierType;

    private $address;

    private $orderConvert;
    private $_order;

    private $_productLoader;
    public function __construct(
        Context $context,
        Registry $registry,
        Address $address,
        OrderRepository $orderRepository,
        OrderInterface $orderInterface,
        ShipmentRepository $shipmentRepository,
        SearchCriteriaBuilder $searchCriteriaBuilder,
        Order $orderConvert,
        ProductFactory $productLoader,
        ?AbstractResource $resource = null,
        ?AbstractDb $resourceCollection = null,
        array $data = []
    ) {
        $this->address               = $address;
        $this->orderRepository       = $orderRepository;
        $this->orderInterface        = $orderInterface;
        $this->shipmentRepository    = $shipmentRepository;
        $this->searchCriteriaBuilder = $searchCriteriaBuilder;
        $this->orderConvert         = $orderConvert;
        $this->_productLoader       = $productLoader;
        parent::__construct(
            $context,
            $registry,
            $resource,
            $resourceCollection,
            $data
        );
    }

    public function getAwbData()
    {
        return $this->orderData();
    }

    public function setAwbData($shipmentId, $orderId, $carrierType)
    {
        $this->shipmentId = $shipmentId;

        $this->orderId = $orderId;

        $this->carrierType = $carrierType;

        return $this;
    }

    private function orderData()
    {
        $orderId = $this->orderId;
        $order   = $this->orderRepository->get($orderId);

        $this->_order = $order;

        $payment = $order->getPayment();
        $paymentMethod = $payment->getData('method');

        $shipmentId = $this->shipmentId;

        if (empty($shipmentId)) {
            if (! $order->canShip()) {
                $shipment = $this->getShipment();

                if (empty($shipment)) {
                    throw new \Magento\Framework\Exception\LocalizedException(
                        __('You can\'t create an shipment.')
                    );
                }
            }

            if (empty($shipment)) {
                $shipment = $this->orderConvert->toShipment($order);

                // Loop through order items
                foreach ($order->getAllItems() AS $orderItem) {
                    // Check if order item has qty to ship or is virtual
                    if (!$orderItem->getQtyToShip() || $orderItem->getIsVirtual()) {
                        continue;
                    }

                    $qtyShipped = $orderItem->getQtyToShip();

                    // Create shipment item with qty
                    $shipmentItem = $this->orderConvert->itemToShipmentItem($orderItem)->setQty($qtyShipped);

                    // Add shipment item to shipment
                    $shipment->addItem($shipmentItem);
                }

                // Register shipment
                $shipment->register();
                $shipment->getOrder()->setIsInProcess(true);

                // Save created shipment and order
                $shipment->save();
                $shipment->getOrder()->save();

                $shipment->save();
            }
        } else {
            $shipment = $this->shipmentRepository->get($shipmentId);
        }

        $address = $order->getShippingAddress();
        $items   = $order->getItems();


        if($address->getData('company')){
            $recipeint = $address->getData('company');
            $firstName = $address->getData('firstname');
            $lastName  = $address->getData('lastname');
            $comments = $firstName . " " . $lastName;
        } else {
            $firstName = $address->getData('firstname');
            $lastName  = $address->getData('lastname');
            $recipeint = $firstName . " " . $lastName;
        }

        $nameProduct = '';

        foreach ($items as $item) {
            $currentProductObject = $this->_productLoader->create()->load($item->getProductId());
            $nameProduct  .= (int)$item->getQtyOrdered() . 'x' . $currentProductObject->getData('sku_fz') . ', ';
            $valueProduct = $order->getGrandTotal();
            $qtyPackage   = $item->getQtyOrdered();
            $comments = '';
        }

        $fields = [
            'recipient'       => $recipeint,
            'country_id'      => $address->getData('country_id'),
            'region_id'       => $address->getData('region'),
            'city'            => $address->getData('city'),
            'street'          => $address->getData('street'),
            'postcode'        => $address->getData('postcode'),
            'telephone'       => $address->getData('telephone'),
            'customer_email'  => $order->getData('customer_email'),
            'weight'          => $order->getData('weight'),
            'packages'        => $qtyPackage,
            'repayment_value' => $valueProduct,
            'content'         => $nameProduct,
            'order_id'        => $this->orderId,
            'shipment_id'     => $shipment->getIncrementId(),
            'comments'        => $comments,
            'carrier_id'      => $this->carrierType
        ];

        if($paymentMethod == 'eppay' || $paymentMethod == 'banktransfer'){
            $fields = [
                'recipient'       => $recipeint,
                'country_id'      => $address->getData('country_id'),
                'region_id'       => $address->getData('region'),
                'city'            => $address->getData('city'),
                'street'          => $address->getData('street'),
                'postcode'        => $address->getData('postcode'),
                'telephone'       => $address->getData('telephone'),
                'customer_email'  => $order->getData('customer_email'),
                'weight'          => $order->getData('weight'),
                'packages'        => $qtyPackage,
                'repayment_value' => 0,
                'content'         => $nameProduct,
                'order_id'        => $order->getIncrementId(),
                'shipment_id'     => $shipment->getIncrementId(),
                'comments'        => $comments,
                'carrier_id'      => $this->carrierType
            ];
        };

        return $fields;
    }

    public function getShipment()
    {
        $shipmentCollection = $this->getShipments();
        $shipment = $this->getFirstShipment($shipmentCollection);


        return $shipment;
    }

    public function getShipments()
    {
        return $this->_order->getShipmentsCollection();
    }

    public function getFirstShipment($shipmentCollection, $object = true)
    {
        if (!empty($shipmentCollection)) {
            foreach ($shipmentCollection as $shipment) {
                return $shipment;
            }
        }
    }

}