<?php
/**
 * FormForge schema migrations — versioned, idempotent, run on plugins_loaded.
 *
 * Why a separate class instead of doing it all in register_activation_hook:
 * - Activation hook fires only on activate/deactivate cycles. A user who
 * upgrades a plugin via auto-update or via WP.org "Update Now" never
 * deactivates → activates, so dbDelta on activation is silently skipped.
 * - maybe_upgrade runs on every page load while is_admin, compares the
 * `formforge_db_version` option against FORMFORGE_DB_VERSION, and only
 * does work if there's a real upgrade gap. Idempotent — safe to call
 * every request.
 *
 * @package FormForge
 * @since 1.0.2
 */

if (!defined('ABSPATH')) exit;

class FORMFORGE_Schema {

    const OPTION = 'formforge_db_version';

    /**
 * Compare stored DB version vs FORMFORGE_DB_VERSION. If they diverge,
 * run dbDelta to apply CREATE / ALTER statements idempotently and bump
 * the option. Anything beyond column-add / index-add belongs in a
 * dedicated migrate_X_to_Y helper inside this class so we have a
 * permanent audit trail of schema evolution.
 */
    public static function maybe_upgrade() {
        $current = get_option(self::OPTION, '');
        $target  = defined('FORMFORGE_DB_VERSION') ? FORMFORGE_DB_VERSION : '1.0.0';

	        if ($current === $target && self::schema_current()) return;

        // Run the same dbDelta as activate. dbDelta is the canonical
        // idempotent schema applier — it inspects column definitions and
        // ALTERs only what diverges. Safe to call on every upgrade.
        if (class_exists('FORMFORGE_Core') && method_exists('FORMFORGE_Core', 'activate')) {
            FORMFORGE_Core::activate();
        }

        // Future migration hooks — append branches here as the schema grows:
        
        // if (version_compare($current, '1.1.0', '<')) {
        // self::migrate_1_0_x_to_1_1_0;
        // }
        
        // Each helper should be idempotent (column-exists check before
        // ALTER), short, and update-only the rows it owns.

	        update_option(self::OPTION, $target, false);
	    }

	    /**
	 * DB version can be correct while columns are still missing if an older
	 * build bumped the option before dbDelta successfully altered the table.
	 */
	    private static function schema_current() {
	        global $wpdb;
	        $table = $wpdb->prefix . 'formforge_submissions';
	        $columns = $wpdb->get_col("SHOW COLUMNS FROM {$table}", 0); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter -- own table from $wpdb->prefix; one-time/admin read
	        if (!is_array($columns)) {
	            return false;
	        }
	        return in_array('session_id', $columns, true)
	            && in_array('payment_status', $columns, true);
	    }
	}
