<?php
/**
 * Migration: Remove custom_prompt opening screen mode.
 *
 * Unlinks bots from presets that use the deprecated custom_prompt mode,
 * setting them back to the default welcome message with show_welcome_message enabled.
 * Also changes those presets' mode to questions_ai for backward compatibility.
 *
 * @package BoostBot
 * @since   1.1.4
 */

// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Migration owns custom-table DDL. Table names pass through sanitize_identifier(); DDL cannot use prepare() placeholders for identifiers; caching is irrelevant for one-shot migrations.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class BoostBot_Migration_Remove_Custom_Prompt_Mode {

	/**
	 * Run migration (idempotent).
	 *
	 * @return bool
	 */
	public static function run() {
		global $wpdb;

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

		// 1. Find all opening screen presets still in custom_prompt mode.
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		$custom_prompt_presets = $wpdb->get_col(
			// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
			$wpdb->prepare(
				// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
				"SELECT id FROM {$presets_table} WHERE mode = %s",
				'custom_prompt'
			)
		);

		if ( empty( $custom_prompt_presets ) ) {
			return true;
		}

		$success = true;

		// 2. Unlink all bots pointing to these presets:
		//    - Clear opening_screen_preset_id → NULL (= "ללא הגדרה")
		//    - Clear opening_screen_overrides → NULL
		//    - Enable show_welcome_message → 1
		$placeholders = implode( ',', array_fill( 0, count( $custom_prompt_presets ), '%d' ) );

		// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, PluginCheck.Security.DirectDB.UnescapedDBParameter
		$affected = $wpdb->query(
			$wpdb->prepare(
				"UPDATE `{$bots_table}`
				 SET opening_screen_preset_id = NULL,
				     opening_screen_overrides = NULL,
				     show_welcome_message = 1
				 WHERE opening_screen_preset_id IN ({$placeholders})",
				...$custom_prompt_presets
			)
		);
		// phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, PluginCheck.Security.DirectDB.UnescapedDBParameter

		if ( false === $affected ) {
			$success = false;
			if ( class_exists( 'BoostBot_Logger' ) ) {
				BoostBot_Logger::error(
					'Migration: failed to unlink bots from custom_prompt presets',
					array( 'error' => $wpdb->last_error )
				);
			}
		} else {
			if ( class_exists( 'BoostBot_Logger' ) ) {
				BoostBot_Logger::info(
					'Migration: unlinked bots from custom_prompt presets',
					array( 'bots_affected' => $affected, 'preset_ids' => $custom_prompt_presets )
				);
			}
		}

		// 3. Change the presets' mode from custom_prompt to questions_ai
		//    (keeps data intact, prevents re-triggering in case of re-run).
		// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$preset_result = $wpdb->update(
			$presets_table,
			array( 'mode' => 'questions_ai' ),
			array( 'mode' => 'custom_prompt' ),
			array( '%s' ),
			array( '%s' )
		);
		// phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching

		if ( false === $preset_result ) {
			$success = false;
			if ( class_exists( 'BoostBot_Logger' ) ) {
				BoostBot_Logger::error(
					'Migration: failed to change custom_prompt presets to questions_ai',
					array( 'error' => $wpdb->last_error )
				);
			}
		} else {
			if ( class_exists( 'BoostBot_Logger' ) ) {
				BoostBot_Logger::info(
					'Migration: changed custom_prompt presets to questions_ai',
					array( 'presets_affected' => $preset_result )
				);
			}
		}

		return $success;
	}

	/**
	 * Restrict a SQL identifier to [A-Za-z0-9_] characters.
	 *
	 * @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 );
	}
}
