<?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 Services extends \Opencart\System\Engine\Model {
    
    public function getSelectedServicesByCurrentRegion(): array
    {
        $this->load->model('extension/alsendo/module/alsendo_region');
        /** @var AlsendoRegionEntity $currentRegion */
        $currentRegion = $this->model_extension_alsendo_module_alsendo_region->getCurrentRegion();

        $query = $this->db->query("
            SELECT sm.*, s.name as service_name, s.region_id, s.supplier, s.to_point, s.comment, s.map_operator
            FROM `" . \DB_PREFIX . "alsendo_shipping_methods` sm
            LEFT JOIN `" . \DB_PREFIX . "alsendo_services` s ON sm.service_id = s.id
            WHERE sm.region_id = '".$currentRegion->id."'
        ");
        
        $methods = [];

        foreach ($query->rows as $row) {
            $name = $row['name'] ?? 'Usługa dostawy';
            $methodKey = $this->generateMethodKey($name);

            $code = sprintf('alsendo.%s:%d:%d', $methodKey, $row['id'], $row['service_id'] ?? 0);

            $methods[$code] = [
                'code' => $code,
                'name' => $name,
                'custom_name' => ($row['comment'] ?? null) ?: $name,
                'price' => $row['price'],
                'map_operator' => $row['map_operator'] ?? null,
                'supplier' => $row['supplier'],
                'delivery_time' => $row['comment'] ?? '',
                'service_id' => $row['service_id'],
                'enabled' => true,
                'to_point' => $row['to_point'] ?? null,
                'has_map' => $row['has_map'],
            ];
        }

        return $methods;
    }
    
    private function generateMethodKey(string $serviceName): string {
        $key = strtolower($serviceName);
        $key = str_replace([' ', '-', '.', '/', '\\', '(', ')', '[', ']'], '_', $key);
        $key = preg_replace('/[^a-z0-9_]/', '', $key);
        $key = preg_replace('/_+/', '_', $key);
        return trim($key, '_');
    }
} 