<?php

/**
 * Copyright 2024-2025 Simply.IN Sp. z o.o.
 *
 * NOTICE OF LICENSE
 *
 * Licensed under the EUPL-1.2 or later.
 * You may not use this work except in compliance with the Licence.
 *
 * Copy of the Licence is available at:
 * https://joinup.ec.europa.eu/software/page/eupl
 * It is bundled with this package in the file LICENSE.txt
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the Licence is distributed on an as is basis,
 * without warranties or conditions of any kind, either express or implied.
 * Check the Licence for the specific language governing permissions
 * and limitations under the License.
 *
 * @author   Simply.IN Sp. z o.o.
 * @copyright 2024-2025 Simply.IN Sp. z o.o.
 * @license   https://joinup.ec.europa.eu/software/page/eupl
 */

declare(strict_types=1);

namespace SimplyIn\Service;

use Closure;
use Configuration;
use SimplyIn\Api\ApiException;
use SimplyIn\Api\SimplyInApiClient;
use SimplyIn\Webhook\WebhookSecretStore;
use Tools;

if (!defined('_PS_VERSION_')) {
    exit;
}

final class MerchantSettingsSync
{
    private static bool $called = false;

    /** @var Closure(?string): SimplyInApiClient */
    private Closure $clientFactory;

    /**
     * @param Closure(?string): SimplyInApiClient $clientFactory called with an optional merchantApiKey override
     */
    public function __construct(
        private readonly string $pluginVersion,
        Closure $clientFactory,
        private readonly WebhookSecretStore $webhookSecretStore,
    ) {
        $this->clientFactory = $clientFactory;
    }

    public function sync(string $newApiKey = '', bool $admin = false): bool
    {

        if (self::$called && !$admin) {
            return true;
        }

        if ($newApiKey === '') {
            $newApiKey = (string) Configuration::get('SIMPLYIN_SECRET_KEY');
        }

        if ($newApiKey === '') {
            return false;
        }

        $lastUpdateDate = Configuration::get('SIMPLYIN_LAST_UPDATE_INFO');
        if (!$admin && $lastUpdateDate) {
            $lastUpdateTimestamp = strtotime((string) $lastUpdateDate);
            if ($lastUpdateTimestamp !== false && $lastUpdateTimestamp > (time() - 3600)) {
                return true;
            }
        }

        self::$called = true;

        $params = [
            'platform' => 'PrestaShop',
            'pluginVersion' => $this->pluginVersion,
            'shopName' => (string) Configuration::get('PS_SHOP_NAME'),
        ];

        $client = ($this->clientFactory)($newApiKey);

        try {
            $apiResponse = $client->request('GET', 'plugin-sync/info', params: $params);
        } catch (ApiException) {
            return false;
        }

        if ($apiResponse->rawBody === null || $apiResponse->rawBody === '') {
            return false;
        }
        $response = json_decode($apiResponse->rawBody);
        if (!$response || isset($response->code)) {
            return false;
        }

        Configuration::updateValue('SIMPLYIN_LAST_UPDATE_INFO', date('Y-m-d H:i:s'));

        // Inbound-webhook HMAC secret (SIN-1477): present+non-empty = store; present+empty ('') =
        // rotate off; null or absent = leave untouched. Treating null as "no change" (not "clear")
        // avoids accidentally disabling HMAC when the backend sends null for an unchanged optional
        // field. Persisted encrypted at rest by the store.
        if (property_exists($response, 'paymentWebhookSigningSecret')) {
            $secret = $response->paymentWebhookSigningSecret;
            $this->webhookSecretStore->persist($secret === null ? null : (string) $secret);
        }

        if (!Tools::isSubmit('submitSimplyinModule') && isset($response->switchInfo->isChecked)) {
            Configuration::updateValue('SIMPLYIN_SAVE_CHECKBOX', !$response->switchInfo->isChecked);
        }

        if (isset($response->transactionHistoryLengthDays)) {
            Configuration::updateValue('SIMPLYIN_TRANS_HISTORY_LENGTH_DAY', $response->transactionHistoryLengthDays);
        }

        if (isset($response->switchInfo->lastChange)) {
            Configuration::updateValue('SIMPLYIN_SWITCH_LASTCHANGE', $response->switchInfo->lastChange);
        }

        if (isset($response->logisticsPartnersOrder->order)) {
            Configuration::updateValue(
                'SIMPLYIN_LOGISTICSPARTNERSORDER',
                (string) json_encode($response->logisticsPartnersOrder->order),
            );
        }

        if (!empty($response->docsInfo) && is_array($response->docsInfo)) {
            $docs = [];
            foreach ($response->docsInfo as $doc) {
                if (isset($doc->key, $doc->url)) {
                    $docs[$doc->key] = $doc->url;
                }
            }
            if ($docs !== []) {
                Configuration::updateValue('SIMPLYIN_DOCS_INFO', (string) json_encode($docs));
            }
        }

        return true;
    }
}
