<?php
/**
 * Migration: Add test_mode column to bots table.
 *
 * When test_mode = 1 and is_active = 1, the bot is only visible to
 * logged-in administrators (useful for previewing before going live).
 *
 * @package BoostBot
 * @since   1.7.0
 */

// Prevent direct access
// phpcs:disable WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Class BoostBot_Migration_Add_Bot_Test_Mode
 *
 * Adds the test_mode column to the bots table.
 *
 * @since 1.7.0
 */
class BoostBot_Migration_Add_Bot_Test_Mode {

    /**
     * Run the migration.
     *
     * @return bool True on success.
     */
    public static function run() {
        return self::up();
    }

    /**
     * Run the migration.
     *
     * @return bool True on success.
     */
    public static function up() {
        global $wpdb;

        $bots_table = self::sanitize_identifier( $wpdb->prefix . 'boostbot_bots' );

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Table identifier sanitized via sanitize_identifier(); values bind via prepare().
        $column_exists = $wpdb->get_results(
            // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            "SHOW COLUMNS FROM {$bots_table} LIKE 'test_mode'"
        );

        if ( empty( $column_exists ) ) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Table identifier sanitized via sanitize_identifier(); values bind via prepare().
            $result = $wpdb->query(
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- DDL cannot use placeholders for identifiers; $table is sanitized, definitions are literals.
                "ALTER TABLE {$bots_table} ADD COLUMN test_mode tinyint(1) DEFAULT 0 AFTER is_active"
            );

            if ( false === $result ) {
                if ( class_exists( 'BoostBot_Logger' ) ) {
                    BoostBot_Logger::error( 'Migration failed: Could not add test_mode to bots', array(
                        'error' => $wpdb->last_error,
                    ) );
                }
                return false;
            } else {
                if ( class_exists( 'BoostBot_Logger' ) ) {
                    BoostBot_Logger::info( 'Migration: Added test_mode column to bots table' );
                }
            }
        }

        return true;
    }

    /**
     * Rollback the migration.
     *
     * @return bool True on success.
     */
    public static function down() {
        global $wpdb;

        $bots_table = self::sanitize_identifier( $wpdb->prefix . 'boostbot_bots' );

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Table identifier sanitized via sanitize_identifier(); values bind via prepare().
        $column_exists = $wpdb->get_results(
            // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            "SHOW COLUMNS FROM {$bots_table} LIKE 'test_mode'"
        );

        if ( ! empty( $column_exists ) ) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Table identifier sanitized via sanitize_identifier(); values bind via prepare().
            $result = $wpdb->query(
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- DDL cannot use placeholders for identifiers; $table is sanitized, definitions are literals.
                "ALTER TABLE {$bots_table} DROP COLUMN test_mode"
            );

            if ( false === $result ) {
                return false;
            }
        }

        return true;
    }

    /**
     * Restrict a SQL identifier to [A-Za-z0-9_] characters.
     *
     * DDL cannot use $wpdb->prepare() for identifiers, so any identifier
     * that ends up interpolated into a query first passes through this
     * allow-list.
     *
     * @param string $identifier Raw identifier.
     * @return string Identifier with disallowed characters removed.
     */
    private static function sanitize_identifier( $identifier ) {
        return preg_replace( '/[^A-Za-z0-9_]/', '', (string) $identifier );
    }
}
