<?php

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

use Opencart\Extension\Alsendo\DTO\OrderShipmentCodeDTO;

require_once(DIR_EXTENSION . 'alsendo/src/DTO/OrderShipmentCodeDTO.php');

class PaymentMethod extends \Opencart\System\Engine\Controller
{
    public function paymentFilter(&$route, &$args, &$output) {
        $selectedShippingCode = $this->session->data['shipping_method']['code'] ?? null;

        if (empty($selectedShippingCode)) {
            return;
        }

        try {
            $orderShipmentCodeDTO = new OrderShipmentCodeDTO($selectedShippingCode);
        } catch (\Exception $exception) {
            return;
        }


        $this->load->model('setting/extension');
        $paymentExtensions = $this->model_setting_extension->getExtensionsByType('payment');

        $paymentCodeIdMap = [];
        foreach ($paymentExtensions as $paymentExtension) {
            $paymentCodeIdMap[$paymentExtension['code']] = $paymentExtension['extension_id'];
        }

        $this->load->model('extension/alsendo/module/payment_shipment');
        $paymentShipmentMap = $this->model_extension_alsendo_module_payment_shipment->getPaymentsForShipmentMap();
        $allowedPaymentIds = $paymentShipmentMap[$orderShipmentCodeDTO->shippingMethodId] ?? [];


        $filteredPaymentMethods = [];

        foreach ($output as $key => $paymentMethodData) {
            if (!array_key_exists($paymentMethodData['code'], $paymentCodeIdMap)) {
                continue;
            }

            if (!in_array($paymentCodeIdMap[$paymentMethodData['code']], $allowedPaymentIds)) {
                continue;
            }

            $filteredPaymentMethods[$key] = $paymentMethodData;
        }

        $output = $filteredPaymentMethods;
    }
}