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

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

function upgrade_module_2_9_0($module)
{
    $db = Db::getInstance();
    $table = _DB_PREFIX_ . 'simplyin_payments';

    $tableExists = (bool) $db->getValue("SHOW TABLES LIKE '" . pSQL($table) . "'");
    if ($tableExists) {
        $columns = $db->executeS('SHOW COLUMNS FROM `' . bqSQL($table) . '`');
        $existingNames = [];
        foreach ((array) $columns as $row) {
            if (isset($row['Field'])) {
                $existingNames[(string) $row['Field']] = true;
            }
        }

        $renames = [
            'payment_provaider' => ['payment_provider', 'VARCHAR(36) NULL'],
            'card_provaider' => ['card_provider',    'VARCHAR(36) NULL'],
            'provaider_logo' => ['provider_logo',    'VARCHAR(255) NULL'],
        ];

        foreach ($renames as $old => [$new, $type]) {

            if (!isset($existingNames[$old]) || isset($existingNames[$new])) {
                continue;
            }
            $sql = 'ALTER TABLE `' . bqSQL($table) . '` CHANGE COLUMN `'
                . bqSQL($old) . '` `' . bqSQL($new) . '` ' . $type;

            try {
                $db->execute($sql);
            } catch (Throwable $e) {
                PrestaShopLogger::addLog(
                    'SimplyIn upgrade 2.9.0: rename ' . $old . ' -> ' . $new . ' failed (' . $e->getMessage() . ')',
                    3,
                    null,
                    'SimplyIn',
                    null,
                    true,
                );

                return false;
            }
        }

        require_once _PS_MODULE_DIR_ . 'simplyin/models/SimplyInPayments.php';
        if (class_exists('SimplyInPayments')) {
            SimplyInPayments::ensureSchema();
        }
    }

    $debugDir = _PS_MODULE_DIR_ . 'simplyin/debug';
    if (is_dir($debugDir)) {
        foreach (['api.log', 'log.log', 'payment.log', '.htaccess', 'index.php'] as $file) {
            $path = $debugDir . '/' . $file;
            if (is_file($path)) {
                @unlink($path);
            }
        }
        @rmdir($debugDir);
    }

    return true;
}
