<?php

namespace Opencart\Admin\Model\Extension\Alsendo\Module;

use Opencart\System\Engine\Model;
use Opencart\System\Engine\Registry;

class PaymentShipment extends Model {
    public function __construct(Registry $registry) {
        parent::__construct($registry);
    }

    public function savePaymentsForShipment(array $data): void {
        $this->db->query("DELETE FROM `" . DB_PREFIX . "alsendo_payment_shipment`");

        foreach ($data as $shippingMethodId => $paymentIds) {
            foreach ($paymentIds as $paymentId) {
                $this->db->query("INSERT INTO `" . DB_PREFIX . "alsendo_payment_shipment` (`shipping_method_id`, `payment_extension_id`) VALUES (" . (int)$shippingMethodId . ", " . (int)$paymentId . ")");
            }
        }
    }

    public function getPaymentsForShipmentMap(): array {
        $result = [];

        $query = $this->db->query("SELECT `shipping_method_id`, `payment_extension_id` FROM `" . DB_PREFIX . "alsendo_payment_shipment`");

        foreach ($query->rows as $row) {
            $shipmentId = (int)$row['shipping_method_id'];
            $paymentId = (int)$row['payment_extension_id'];

            if (!isset($result[$shipmentId])) {
                $result[$shipmentId] = [];
            }

            $result[$shipmentId][] = $paymentId;
        }

        return $result;
    }

}