<?php

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

use Opencart\Extension\Alsendo\Repositories\ConfigRepository;
use Opencart\Extension\Alsendo\Services\GeoIpService;
use Opencart\Extension\Alsendo\Services\MapWidgetService;

require_once(DIR_EXTENSION . 'alsendo/wrapper/src/Map/MapRegion.php');
require_once(DIR_EXTENSION . 'alsendo/src/Repositories/ConfigRepository.php');
require_once(DIR_EXTENSION . 'alsendo/src/Services/MapWidgetService.php');
require_once(DIR_EXTENSION . 'alsendo/src/Services/GeoIpService.php');

use Alsendo\AlsendoWrapper\Map\MapRegion;

class Alsendo extends \Opencart\System\Engine\Controller
{
    public function addCheckoutMapDetection(string $route, array &$data, &$output): void
    {
        if (strpos($this->request->get['route'] ?? '', 'checkout') !== false) {
            $this->load->language('extension/alsendo/main');
        }

        $configRepository = new ConfigRepository($this->db);
        $config = $configRepository->getConfig();
        $region = $config->getRegion();

        $mapWidgetService = new MapWidgetService($region);
        $mapAssets = $mapWidgetService->getAssetUrls();
        $mapConfig = $mapWidgetService->getClientConfig();
        $mapConfig['countryCodes'] = MapRegion::EU_COUNTRY_CODES;

        $clientIp = $this->getClientIp();
        $geoIpService = new GeoIpService();
        $mapOptions = $geoIpService->getMapOptionsFromIp($clientIp, $region);
        $mapConfig['mapOptions'] = $mapOptions;

        $shippingAddress = $this->session->data['shipping_address'] ?? null;
        $initialPoint = null;
        if ($shippingAddress) {
            $country = $shippingAddress['country'] ?? null;
            $city = $shippingAddress['city'] ?? null;

            if ($country) {
                $initialPoint = $country;
            }

            if ($city) {
                $initialPoint .= ' ' . $city;
            }
        }

        $scriptHtml = $this->load->view('extension/alsendo/checkout/checkout_map_detection', [
            'region' => $region,
            'map_config_json' => json_encode($mapConfig),
            'map_js_url' => $mapAssets['js'],
            'map_css_url' => $mapAssets['css'],
            'initial_point' => $initialPoint,
        ]);

        $output = str_replace('</body>', $scriptHtml . '</body>', $output);
    }

    private function getClientIp(): string
    {
        $server = $this->request->server ?? [];
        $ip = $server['HTTP_CF_CONNECTING_IP']
            ?? $server['HTTP_X_FORWARDED_FOR']
            ?? $server['HTTP_X_REAL_IP']
            ?? $server['REMOTE_ADDR']
            ?? '';
        return is_array($ip) ? (string) reset($ip) : (string) $ip;
    }
}
