<?php
/**
 * Migration: Add Content Enabled Flag to Knowledge Index
 *
 * Adds new column for content visibility control:
 * - is_enabled: Flag to include/exclude content from RAG searches (default: 1 = enabled)
 *
 * @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_Content_Enabled_Flag
 *
 * @since 1.7.0
 */
class BoostBot_Migration_Add_Content_Enabled_Flag {

    /**
     * Run the migration.
     *
     * @return bool Success or failure.
     */
    public static function run() {
        global $wpdb;

        $table_name = self::sanitize_identifier( $wpdb->prefix . 'boostbot_knowledge_index' );

        // Check if table exists
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $table_exists = $wpdb->get_var(
            $wpdb->prepare( 'SHOW TABLES LIKE %s', $table_name )
        );

        if ( ! $table_exists ) {
            return false;
        }

        // Check which columns already exist
        // 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.
        $columns = $wpdb->get_results( "SHOW COLUMNS FROM `{$table_name}`" );

        $existing_columns = array();
        foreach ( $columns as $column ) {
            $existing_columns[] = $column->Field;
        }

        // Column definitions are hard-coded literals.
        $columns_to_add = array(
            'is_enabled' => 'tinyint(1) DEFAULT 1 AFTER updated_at',
        );

        foreach ( $columns_to_add as $column_name => $column_definition ) {
            if ( in_array( $column_name, $existing_columns, true ) ) {
                continue;
            }
            $safe_column = self::sanitize_identifier( $column_name );

            // 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.
            $wpdb->query( "ALTER TABLE `{$table_name}` ADD COLUMN `{$safe_column}` {$column_definition}" );

            if ( $wpdb->last_error ) {
                if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
                    BoostBot_Logger::error( '[Migration] Content enabled flag: ' . $wpdb->last_error );
                }
                return false;
            }
        }

        // Add index for performance on is_enabled filtering
        $indexes_to_add = array(
            'idx_is_enabled' => 'is_enabled',
        );

        foreach ( $indexes_to_add as $index_name => $column_name ) {
            $safe_index  = self::sanitize_identifier( $index_name );
            $safe_column = self::sanitize_identifier( $column_name );

            // 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().
            $index_exists = $wpdb->get_var(
                $wpdb->prepare(
                    "SHOW INDEX FROM `{$table_name}` WHERE Key_name = %s",
                    $safe_index
                )
            );

            if ( ! $index_exists ) {
                // 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.
                $wpdb->query( "ALTER TABLE `{$table_name}` ADD INDEX `{$safe_index}` (`{$safe_column}`)" );
            }
        }

        return true;
    }

    /**
     * Restrict a SQL identifier to [A-Za-z0-9_] characters.
     *
     * DDL cannot use $wpdb->prepare() for identifiers, so every interpolated
     * identifier 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 );
    }
}
