<?php

defined( 'ABSPATH' ) || exit;
/**
 * Handles plugin activation (free-clean):
 *  - Creates the audit log DB table
 *  - Stores the installed version
 *
 * PRO schema (certificates table, upload directory) is created and
 * migrated from Rankd_Tx_Pro::init() via the __premium_only methods below,
 * which Freemius strips from the free build.
 */
class Rankd_Tx_Install {
    public static function activate() {
        self::create_tables();
        self::store_version();
        Rankd_Tx_Capabilities::sync_editor_caps();
        // Certificate schema, the protected upload directory, and cron
        // scheduling are Pro-only and owned by Rankd_Tx_Pro::init(), which
        // runs on every licensed load — activation stays free-clean.
        // Set flag so the init hook registers the endpoint and flushes
        // rewrite rules on the next request. Calling add_rewrite_endpoint()
        // directly here is unsafe as $wp_rewrite may not be ready.
        update_option( 'rankd_tx_needs_rewrite_flush', '1' );
    }

    /**
     * Runs upgrade routines for schema changes added after initial release.
     * Safe to call on every activation and on plugins_loaded version check.
     */
    public static function maybe_upgrade() {
        global $wpdb;
        $installed_version = get_option( 'rankd_tx_version', '0' );
        // Fast exit on every normal page load — only run migration checks
        // when the stored version is behind the code version.
        if ( version_compare( $installed_version, RANKD_TX_VERSION, '>=' ) ) {
            return;
        }
        // Re-sync the management capability against the setting on every
        // upgrade — corrects any drift (e.g. the pre-1.8.1 bug where an
        // empty saved value left the default roles holding the cap).
        Rankd_Tx_Capabilities::sync_editor_caps();
        // PRO: certificate-table schema migrations.
        if ( function_exists( 'rankd_tx_fs' ) && rankd_tx_fs()->can_use_premium_code__premium_only() ) {
            self::upgrade_certificates_schema__premium_only();
        }
        // Version changed (guaranteed by the guard above) — flag a rewrite
        // flush so the init hook can safely flush once $wp_rewrite is available.
        update_option( 'rankd_tx_needs_rewrite_flush', '1' );
        self::store_version();
    }

    /**
     * Called on the init hook (priority 20 — after Rankd_Tx_My_Account has
     * registered the tax-exemption endpoint in the Pro build, so the flushed
     * rules include it). Flushes once after a version change, then clears the flag.
     */
    public static function maybe_flush_rewrite_rules() {
        // Only flush if flagged — avoids the performance hit on every request.
        if ( get_option( 'rankd_tx_needs_rewrite_flush' ) ) {
            flush_rewrite_rules();
            delete_option( 'rankd_tx_needs_rewrite_flush' );
        }
    }

    // -------------------------------------------------------------------------
    // Database tables
    // -------------------------------------------------------------------------
    public static function create_tables() {
        global $wpdb;
        $charset = $wpdb->get_charset_collate();
        // Audit log table — one row per status change event.
        $audit = "CREATE TABLE {$wpdb->prefix}rankd_tx_audit_log (\n\t\t\tid              BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,\n\t\t\tcountry         VARCHAR(2)          NOT NULL DEFAULT '',\n\t\t\tuser_id         BIGINT(20) UNSIGNED NOT NULL,\n\t\t\tcert_id         BIGINT(20) UNSIGNED          DEFAULT NULL,\n\t\t\taction          VARCHAR(50)         NOT NULL DEFAULT '',\n\t\t\tactor_id        BIGINT(20) UNSIGNED          DEFAULT NULL,\n\t\t\tnote            TEXT                NOT NULL,\n\t\t\tcreated_at      DATETIME            NOT NULL DEFAULT CURRENT_TIMESTAMP,\n\t\t\tPRIMARY KEY     (id),\n\t\t\tKEY user_id     (user_id),\n\t\t\tKEY cert_id     (cert_id)\n\t\t) {$charset};";
        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta( $audit );
    }

    // -------------------------------------------------------------------------
    // Version tracking
    // -------------------------------------------------------------------------
    public static function store_version() {
        update_option( 'rankd_tx_version', RANKD_TX_VERSION, false );
    }

}
