<?php
/**
 * 2018 Paysera
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@prestashop.com so we can send you a copy immediately.
 *
 * @author Paysera <plugins@paysera.com>
 * @copyright 2018 Paysera
 * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
 * International Registered Trademark & Property of Paysera
 */
declare(strict_types=1);

namespace Paysera\Delivery\HookHandler\OrderHandler;

use Paysera\Delivery\Entity\ShipmentRequestGateway;
use Paysera\Delivery\HookHandler\HookHandlerParameters;
use Paysera\Delivery\HookHandler\OrderHandlerInterface;
use Paysera\Delivery\Model\ShipmentRequestModel;
use Paysera\Delivery\PayseraDeliveryConfiguration;
use Paysera\Delivery\PayseraDeliveryCarriers;
use Paysera\Delivery\Service\DeliveryApiClient;
use Paysera\Delivery\Service\Logger;
use Order;
use Validate;

class OrderConfirmationHandler extends AbstractOrderCreateHandler implements OrderHandlerInterface
{
    /**
     * @var ShipmentRequestModel $shipmentRequestModel
     */
    private $shipmentRequestModel;

    public function __construct(
        Logger $logger,
        PayseraDeliveryConfiguration $configuration,
        DeliveryApiClient $deliveryApiClient,
        ShipmentRequestModel $shipmentRequestModel,
        PayseraDeliveryCarriers $payseraDeliveryCarriers
    ) {
        parent::__construct($logger, $configuration, $deliveryApiClient, $payseraDeliveryCarriers);
        $this->shipmentRequestModel = $shipmentRequestModel;
    }

    /**
     * Handles the order confirmation hook.
     *
     * @param HookHandlerParameters $hookHandlerParameters
     * @return void
     */
    public function handle(HookHandlerParameters $hookHandlerParameters): void
    {
        $params = $hookHandlerParameters->getParams();
        $module = $hookHandlerParameters->getModule();
        $context = $module->getContext();
        
        if ($this->configuration->isTestModeEnabled()) {
            return;
        }

        /** @var Order */
        $order = $params['order'];

        if (!Validate::isLoadedObject($order) || $order->id === null) {
            $this->logger->error('Order not found. Order ID: ' . ($order->id ?? 'null'));

            return;
        }

        $shipmentRequest = $this->shipmentRequestModel->find($order->id);

        if ($shipmentRequest !== null) {
            return;
        }

        $carrierInfo = $this->payseraDeliveryCarriers->getCarrierById((int) $order->id_carrier);

        if (!isset($carrierInfo['type']) || !isset($carrierInfo['code'])) {
            $this->logger->error('Invalid shipping carrier for Order ID: ' . $order->id);

            return;
        }

        $gateway = null;
        $country = $context->cookie->__get('paysera_delivery_country');
        $city = $context->cookie->__get('paysera_delivery_city');
        $terminal = $context->cookie->__get('paysera_delivery_terminal');

        if ($carrierInfo['type'] === PayseraDeliveryConfiguration::TYPE_PARCEL_MACHINE
            && $country !== null && $city !== null && $terminal !== null
        ) {
            $gateway = new ShipmentRequestGateway(
                $country,
                $city,
                $terminal
            );
        }

        $shipmentRequest = $this->shipmentRequestModel->findOrCreate($order->id);
        $shipmentRequest->setCarrierCode($carrierInfo['code']);
        $shipmentRequest->setCarrierType($carrierInfo['type']);
        $shipmentRequest->setShippingRequestGateway($gateway);
        $shipmentRequest = $this->shipmentRequestModel->save($shipmentRequest);

        $deliveryOrder = $this->handleDeliveryOrderCreation(
            $module,
            $order,
            $shipmentRequest
        );

        if ($deliveryOrder === null) {
            $this->logger->error('Failed to create delivery order for Order ID: ' . $order->id);

            return;
        }

        $shipmentRequest->setDeliveryOrderApiId($deliveryOrder->getId());
        $this->shipmentRequestModel->save($shipmentRequest);
    }
}
