<?php
namespace Opencart\Catalog\Model\Extension\Alsendo\Shipping;

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

use Opencart\Extension\Alsendo\DTO\Entity\AlsendoRegionEntity;

class Alsendo extends \Opencart\System\Engine\Model
{
    public function getQuote(array $address): array
    {
        $this->load->language('extension/alsendo/main');

        if (!$this->config->get('shipping_alsendo_status')) {
            return [];
        }

        $quotes = [];

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

        $configuredShippingMethods = $this->getConfiguredAvailableShippingMethods($address);

        foreach ($configuredShippingMethods as $methodCode => $methodData) {
            $preparedMethodCodeKey = str_starts_with($methodCode, 'alsendo.') ? substr($methodCode, 8) : $methodCode;
            $quotes[$preparedMethodCodeKey] = [
                'code' => $methodCode,
                'name' => $methodData['name'],
                'cost' => $methodData['cost'],
                'tax_class_id' => $this->config->get('shipping_alsendo_tax_class_id'),
                'text' => $this->currency->format($methodData['cost'], $this->session->data['currency'])
            ];
        }

        if (empty($quotes)) {
            return [];
        }

        return [
            'code' => 'alsendo',
            'name' => $this->language->get('alsendo_shipping_methods_select_header'),
            'quote' => $quotes,
            'sort_order' => $this->config->get('shipping_alsendo_sort_order'),
            'error' => false
        ];
    }

    private function getConfiguredAvailableShippingMethods(array $address): array
    {
        $methods = [];
        
        $configuredMethods = $this->getConfiguredMethods();
        
        foreach ($configuredMethods as $methodKey => $method) {
            if (!$method['enabled']) {
                continue;
            }
            
            $cost = $this->calculateShippingCost($method, $address);
            
            if ($cost !== false) {
                $methods[$methodKey] = [
                    'name' => $method['custom_name'],
                    'cost' => $cost,
                    'delivery_time' => $method['delivery_time'] ?? ''
                ];
            }
        }
        
        return $methods;
    }

    private function getConfiguredMethods(): array {
        $this->load->model('extension/alsendo/shipping/services');

        return $this->model_extension_alsendo_shipping_services->getSelectedServicesByCurrentRegion();
    }

    private function calculateShippingCost(array $method, array $address): ?float
    {
        try {
            return (float) $method['price'];
        } catch (\Exception $e) {
            $this->log->write('Alsendo Shipping Error: ' . $e->getMessage());

            return null;
        }
    }
}