<?php

namespace Opencart\Extension\Alsendo\Handlers;

require_once(DIR_EXTENSION . 'alsendo/src/Repositories/SenderAddressRepository.php');
require_once(DIR_EXTENSION . 'alsendo/src/Repositories/ShippingSettingsRepository.php');

use Opencart\Extension\Alsendo\Repositories\SenderAddressRepository;
use Opencart\Extension\Alsendo\Repositories\ShippingSettingsRepository;
use Opencart\System\Engine\Registry;

class OrderUpdateTemplates
{
    private Registry $registry;
    private SenderAddressRepository $senderAddressRepository;
    private ShippingSettingsRepository $shippingSettingsRepository;

    public function __construct(Registry $registry, object $db, string $dbPrefix = '')
    {
        $this->registry = $registry;
        $prefix = $dbPrefix ?: (defined('\DB_PREFIX') ? \DB_PREFIX : '');
        $this->senderAddressRepository = new SenderAddressRepository($db, $prefix);
        $this->shippingSettingsRepository = new ShippingSettingsRepository($db, $prefix);
    }

    public function updateSenderTemplate(int $orderId, int $templateId): void
    {
        $this->registry->get('load')->model('extension/alsendo/module/alsendo_order_details');
        $this->registry->get('load')->model('extension/alsendo/module/alsendo_order_details_sender');
        $orderDetails = $this->registry->get('model_extension_alsendo_module_alsendo_order_details')->getOrderDetailsByOrderId($orderId);
        if (!$orderDetails || !$orderDetails->sender) {
            return;
        }
        $template = $this->senderAddressRepository->getTemplateById($templateId);
        if (!$template) {
            return;
        }
        $fullName = $template->getFullName() ?: trim($template->getFirstName() . ' ' . $template->getLastName());
        $senderData = [
            'sender_template_id' => $template->getId(),
            'address_type' => $template->getAddressType(),
            'company_name' => $template->getCompanyName(),
            'full_name' => $fullName,
            'street' => $template->getStreet(),
            'house_number' => $template->getBuildingNumber(),
            'apartment_number' => $template->getApartmentNumber(),
            'country' => $template->getCountry(),
            'postal_code' => $template->getPostalCode(),
            'city' => $template->getCity(),
            'phone_number' => $template->getPhoneNumber(),
            'email' => $template->getEmail(),
            'shipping_point' => $template->toArray()['pickup_point'] ?? null,
        ];
        $this->registry->get('model_extension_alsendo_module_alsendo_order_details_sender')->updateSender($orderDetails->sender->id, $senderData);
        $this->registry->get('model_extension_alsendo_module_alsendo_order_details')->updateUpdatedAt($orderDetails->id);
    }

    public function updatePackageTemplate(int $orderId, int $templateId, int $packageIndex): void
    {
        $this->registry->get('load')->model('extension/alsendo/module/alsendo_order_details');
        $this->registry->get('load')->model('extension/alsendo/module/alsendo_order_details_package_details');
        $this->registry->get('load')->model('extension/alsendo/module/alsendo_order_details_package');
        $orderDetails = $this->registry->get('model_extension_alsendo_module_alsendo_order_details')->getOrderDetailsByOrderId($orderId);
        if (!$orderDetails || !$orderDetails->packageDetails) {
            return;
        }
        $template = $this->shippingSettingsRepository->getTemplateById($templateId);
        if (!$template) {
            return;
        }
        $packages = $orderDetails->packageDetails->packages;
        if ($packageIndex < 0 || $packageIndex >= count($packages)) {
            return;
        }
        $this->registry->get('model_extension_alsendo_module_alsendo_order_details_package_details')->updatePackageDetails($orderDetails->packageDetails->id, [
            'pickup_type' => $template->getPickupType(),
        ]);
        $this->registry->get('model_extension_alsendo_module_alsendo_order_details_package')->deleteByPackageDetailsId($orderDetails->packageDetails->id);
        foreach ($packages as $i => $pkg) {
            $pkgData = [
                'template_id' => $i === $packageIndex ? $template->getId() : $pkg->templateId,
                'template_name' => $i === $packageIndex ? $template->getName() : $pkg->templateName,
                'package_width' => $i === $packageIndex ? $template->getWidth() : $pkg->packageWidth,
                'package_length' => $i === $packageIndex ? $template->getLength() : $pkg->packageLength,
                'package_height' => $i === $packageIndex ? $template->getHeight() : $pkg->packageHeight,
                'package_weight' => $i === $packageIndex ? $template->getWeight() : $pkg->packageWeight,
                'package_shipment_packaging' => $i === $packageIndex ? $template->getPackageType() : $pkg->packageShipmentPackaging,
                'non_standard' => $i === $packageIndex ? $template->isNonStandard() : $pkg->nonStandard,
            ];
            $this->registry->get('model_extension_alsendo_module_alsendo_order_details_package')->insertPackage($orderDetails->packageDetails->id, $pkgData);
        }
        $this->registry->get('model_extension_alsendo_module_alsendo_order_details')->updateUpdatedAt($orderDetails->id);
    }
}
