<?php

namespace Opencart\Admin\Controller\Extension\Alsendo\Event;

require_once(DIR_EXTENSION . 'alsendo/src/OrderDetails/OrderDetailsPayloadBuilder.php');

use Opencart\Extension\Alsendo\DTO\Entity\AbstractOrderDetailsShippingAddressEntity;
use Opencart\Extension\Alsendo\DTO\Entity\AlsendoRegionEntity;
use Opencart\Extension\Alsendo\OrderDetails\OrderDetailsPayloadBuilder;
use Opencart\System\Engine\Registry;

class Order extends \Opencart\System\Engine\Controller
{
    private OrderDetailsPayloadBuilder $payloadBuilder;

    public function __construct(Registry $registry)
    {
        parent::__construct($registry);

        $this->payloadBuilder = new OrderDetailsPayloadBuilder($registry);
    }

    public function syncOrder(string $route, array &$data, &$output): void
    {
        $queryParams = $this->request->get ?? [];
        $payload = $this->request->post ?? [];

        if (($queryParams['action'] ?? null) !== 'sale/order.confirm') {
            return;
        }

        $responseOutput = $this->response->getOutput();
        if (empty($responseOutput)) {
            return;
        }

        if (!is_string($responseOutput)) {
            return;
        }

        $responseOutput = json_decode($responseOutput);
        if (empty($responseOutput->order_id)) {
            return;
        }

        $orderId = $responseOutput->order_id;

        if (empty($orderId) || $orderId === 0) {
            return;
        }

        $this->load->model('sale/order');
        $orderInfo = $this->model_sale_order->getOrder($orderId);

        $this->load->model('extension/alsendo/module/alsendo_region');
        /** @var AlsendoRegionEntity $currentRegion */
        $currentRegion = $this->model_extension_alsendo_module_alsendo_region->getCurrentRegion();

        $street = $orderInfo['shipping_address_1'];
        $houseNumber = '';

        if (str_contains($street, ' ')) {
            [$street, $houseNumber] = explode(' ', $street, 2);
        }

        $dataToSave = [
            'full_name' => sprintf('%s %s', $orderInfo['shipping_firstname'], $orderInfo['shipping_lastname']),
            'company_name' => $orderInfo['shipping_company'],
            'address_type' => empty($orderInfo['shipping_company']) ? 'home' : 'company',
            'phone_number' => $orderInfo['telephone'],
            'email' => $orderInfo['email'],
            'country' => $orderInfo['shipping_country'],
            'city' => $orderInfo['shipping_city'],
            'postal_code' => $orderInfo['shipping_postcode'],
            'street' => $street,
            'house_number' => $houseNumber,
            'apartment_number' => $orderInfo['shipping_address_2'],
        ];

        if ($currentRegion->code === 'romania') {
            $romanianAddress = $this->payloadBuilder->parseRomanianAddress($orderInfo['shipping_address_1'], $orderInfo['shipping_address_2']);
            $dataToSave['street'] = $romanianAddress['street'];
            $dataToSave['house_number'] = $romanianAddress['house_number'];
            $dataToSave['apartment_number'] = $romanianAddress['apartment_number'];
            $dataToSave['block'] = $romanianAddress['block'];
            $dataToSave['entrance'] = $romanianAddress['entrance'];
            $dataToSave['floor'] = $romanianAddress['floor'];
        }

        $this->registry->load->model('extension/alsendo/module/alsendo_order_details_shipping_address');


        /** @var null|AbstractOrderDetailsShippingAddressEntity $orderDetailsShippingAddress */
        $orderDetailsShippingAddress = $this->registry->model_extension_alsendo_module_alsendo_order_details_shipping_address->getShippingAddressByOrderId($orderId);
        if (empty($orderDetailsShippingAddress)) {
            return;
        }

        $this->registry->model_extension_alsendo_module_alsendo_order_details_shipping_address->updateShippingAddress(
            $orderDetailsShippingAddress->id,
            $dataToSave
        );
    }
}