<?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);

use SimplyIn\Webhook\WebhookIpValidator;

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

function upgrade_module_2_4_0($module)
{
    $db = Db::getInstance();

    if (!Configuration::hasKey(WebhookIpValidator::CONFIG_KEY)) {
        Configuration::updateValue(
            WebhookIpValidator::CONFIG_KEY,
            json_encode(WebhookIpValidator::DEFAULT_IPS),
        );
    }

    $tableExists = (bool) $db->getValue("SHOW TABLES LIKE '" . pSQL(_DB_PREFIX_ . 'simplyin_payments') . "'");
    if ($tableExists) {
        try {
            $db->execute(
                'UPDATE `' . _DB_PREFIX_ . 'simplyin_payments`
                 SET status = "FAILED"
                 WHERE status = "FAILD"',
            );
        } catch (Throwable $e) {
            PrestaShopLogger::addLog(
                'SimplyIn upgrade 2.4.0: failed to migrate FAILD -> FAILED (' . $e->getMessage() . ')',
                3,
                null,
                'SimplyIn',
                null,
                true,
            );
        }
    }

    $legacyLog = _PS_MODULE_DIR_ . 'simplyin/controllers/front/webhook.log';
    if (is_file($legacyLog) && is_writable($legacyLog)) {
        @unlink($legacyLog);
    }

    $debugLog = _PS_MODULE_DIR_ . 'simplyin/debug/payment.log';
    if (is_file($debugLog) && is_writable($debugLog)) {
        @file_put_contents($debugLog, '');
    }

    return true;
}
