<?php // phpcs:disable PSR1.Files.SideEffects.FoundWithSymbols

/** @noinspection PhpCSValidationInspection */

/*
 * Copyright © Resurs Bank AB. All rights reserved.
 * See LICENSE for license details.
 */

declare(strict_types=1);

use Resursbank\Ecom\Module\Customer\Http\GetAddressController;
use Resursbank\MerchantApi\Util\Log;
use Resursbank\MerchantApi\Util\Translator;

// phpcs:disable
class ResursbankFetchaddressModuleFrontController extends ModuleFrontController
// phpcs:enable
{
    /**
     * Fetch address data.
     */
    public function postProcess(): void
    {
        try {
            // Prestashop does not use the regular session_start and since this is a controller
            // that we own entirely, we need to start the session manually to make sure Ecom gets it.
            if (session_status() !== PHP_SESSION_ACTIVE) {
                session_name(name: 'ecom_session');
                session_start();
            }

            $controller = new GetAddressController();
            $getAddressRequestData = $controller->getRequestData();
            $data = json_decode(
                json: $controller->exec(data: $getAddressRequestData),
                associative: true
            );

            // Store the data in PrestaShop-owned cookies.
            if (isset($getAddressRequestData->govId)) {
                $this->context->cookie->__set(key: 'govId', value: $getAddressRequestData->govId);
            }
            if (isset($getAddressRequestData->customerType)) {
                $this->context->cookie->__set(key: 'customerType',
                    value: json_encode($getAddressRequestData->customerType->value));
            }

            // Translate countryCode on $data on corresponding id_country from PrestaShop.
            $this->translateCountryCode(data: $data);

            // Re-format postal code.
            $this->reformatPostalCode(data: $data);

            $code = 200;
        } catch (Throwable $error) {
            $code = 400;
            Log::error(message: $error);
            $data = ['error' => Translator::translate(phraseId: 'get-address-error')];
        }

        // Set response code.
        http_response_code($code);

        // Set the response header to JSON.
        header('Content-Type: application/json');

        // Output the JSON encoded data
        exit(json_encode($data));
    }

    /**
     * Translate countryCode on $data on corresponding id_country from PrestaShop.
     *
     * @param array $data
     */
    private function translateCountryCode(array &$data): void
    {
        $rs = Db::getInstance()->getRow(
            'SELECT `id_country` FROM `' . _DB_PREFIX_ . 'country` where `iso_code` = "' . $data['countryCode'] . '"'
        );

        if ($rs) {
            $data['countryCode'] = $rs['id_country'];
        }
    }

    /**
     * Convert the postalCode value from "55555" to "555 55" to match expected format by PrestaShop.
     *
     * @param array $data
     * @return void
     */
    private function reformatPostalCode(array &$data): void
    {
        if (isset($data['postalCode'])) {
            $data['postalCode'] = preg_replace(
                pattern: '/^(\d{3})(\d{2})$/',
                replacement: '$1 $2',
                subject: $data['postalCode']
            );
        }
    }
}
