<?php

namespace Opencart\Extension\Alsendo\Services;

require_once(DIR_EXTENSION . 'alsendo/src/Providers/AdditionalSettingsDataProvider.php');

use Opencart\Extension\Alsendo\Providers\AdditionalSettingsDataProvider;
use Opencart\System\Engine\Registry;

class PackageContentTags
{
    protected Registry $registry;

    public function __construct(Registry $registry)
    {
        $this->registry = $registry;
        $this->registry->load->language('extension/alsendo/main');
    }

    public function getAvailableTagMap(): array
    {
        return [
            'order_id' => $this->registry->language->get('text_available_tag_order_id'),
            'products_list' => $this->registry->language->get('text_available_tag_products_list'),
            'custom_text' => $this->registry->language->get('text_available_tag_custom_text'),
        ];
    }

    public function generatePackageContent(array $orderData, array $packageTemplate, bool $isCatalog = false): string
    {
        $templateTag = $packageTemplate['shipment_content'] ?? '-';
        $customText = $packageTemplate['default_content_custom_text'] ?? '';

        if (!in_array($templateTag, array_keys($this->getAvailableTagMap()))) {
            return $customText;
        }

        if ($templateTag === 'custom_text') {
            return $customText;
        }

        if ($templateTag === 'order_id') {
            return $orderData['order_id'];
        }

        if ($isCatalog) {
            $this->registry->load->model('checkout/order');
            $orderProducts = $this->registry->model_checkout_order->getProducts((int)$orderData['order_id']);
        } else {
            $this->registry->load->model('sale/order');
            $orderProducts = $this->registry->model_sale_order->getProducts((int)$orderData['order_id']);
        }

        if ($templateTag === 'products_list') {
            $productNames = [];
            foreach ($orderProducts as $orderProduct) {
                $productNames[] = $orderProduct['name'];
            }

            return implode(', ', $productNames);
        }
    }
}