<?php
/**
 * LangForge schema versioning.
 *
 * Plugin updates from Freemius / wp.org do NOT re-fire the activation hook,
 * so any new column / index / table added across versions has to be applied
 * in a separate code path that runs on every page load (cheaply gated by an
 * option flag). Pattern mirrors `SEOFORGE_Redirects::maybe_create_table`.
 *
 * Bump LF_DB_VERSION in `langforge.php` when:
 * - any of the 5 lf_* tables gains/loses a column or index
 * - the migration logic itself changes shape
 *
 * `maybe_upgrade` is a no-op when the stored version matches LF_DB_VERSION.
 *
 * @package LangForge
 * @since 1.0.1
 */

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

class LF_Schema {

    const OPTION_KEY = 'lf_db_version';

    /**
 * Hook for `plugins_loaded`. Cheap on the hot path: one option read,
 * one strcmp, return.
 */
    public static function maybe_upgrade() {
        $current = defined('LF_DB_VERSION') ? LF_DB_VERSION : '1.0.1';
        $stored  = (string) get_option(self::OPTION_KEY, '');

        if ($stored === $current) {
            return;
        }

        self::run_migrations();

        update_option(self::OPTION_KEY, $current, false);
    }

    /**
 * Idempotent migration runner. Each step is `CREATE TABLE IF NOT EXISTS`
 * + `dbDelta`, so repeated runs are safe — a cold install on activation
 * and a warm bump-from-update both end up with the same schema.
 *
 * Keep the calls in the order they are introduced; new versions append.
 */
    public static function run_migrations() {
        // v1.0.0 baseline Free schema — lf_translations + lf_strings via
        // LF_Core::activate. The Pro-only tables (lf_translation_memory,
        // lf_glossary, lf_analytics) are created by langforge-pro on its own
        // activation hook + its own plugins_loaded schema check, so this
        // method stays no-op on Free-only sites for those tables.
        if (!class_exists('LF_Core')) { require_once LF_PLUGIN_DIR . 'includes/class-core.php'; }
        LF_Core::activate();

        // Best-effort Pro table creation — only fires when Pro is also active
        // in the current process. On Free-only sites these class_exists checks
        // return false and the call is skipped.
        if (class_exists('LF_Translation_Memory')) { LF_Translation_Memory::create_table(); }
        if (class_exists('LF_Glossary'))           { LF_Glossary::create_table(); }
        if (class_exists('LF_Analytics'))          { LF_Analytics::create_table(); }

        // Future migrations: append here, gated by version comparison if the
        // migration is destructive or expensive.
    }
}
