<?php
/**
 * Alsendo - PrestaShop shipping module
 *
 * @author    Innovation Software
 * @copyright 2026 Innovation Software
 * @license   https://opensource.org/licenses/AFL-3.0  Academic Free License (AFL 3.0)
 */
if (!defined('_PS_VERSION_')) {
    exit;
}

/**
 * Upgrade hook for the 1.7.29 release.
 *
 * Pickup point persistence hardening. The alsendo_order_pickup table gains an id_order column
 * (with an index) so a selected pickup point can be linked to the created order and recovered
 * even when the cart id changed after selection (e.g. an OPC module regenerated the cart).
 *
 * Older installs may have created the table from the legacy definition without id_order; add the
 * column idempotently here.
 *
 * @param Module $module the module instance being upgraded
 *
 * @return bool true on success
 */
function upgrade_module_1_7_29($module)
{
    $db = Db::getInstance();
    $table = _DB_PREFIX_ . 'alsendo_order_pickup';

    $hasColumn = (bool) $db->getValue(
        'SELECT COUNT(*) FROM information_schema.COLUMNS
         WHERE TABLE_SCHEMA = DATABASE()
           AND TABLE_NAME = "' . pSQL($table) . '"
           AND COLUMN_NAME = "id_order"'
    );

    if (!$hasColumn) {
        $db->execute(
            'ALTER TABLE `' . bqSQL($table) . '` ADD COLUMN `id_order` INT(11) DEFAULT NULL AFTER `id_cart`'
        );
    }

    $hasIndex = (bool) $db->getValue(
        'SELECT COUNT(*) FROM information_schema.STATISTICS
         WHERE TABLE_SCHEMA = DATABASE()
           AND TABLE_NAME = "' . pSQL($table) . '"
           AND INDEX_NAME = "id_order"'
    );

    if (!$hasIndex) {
        $db->execute(
            'ALTER TABLE `' . bqSQL($table) . '` ADD INDEX `id_order` (`id_order`)'
        );
    }

    return true;
}
