<?php
/**
 * Update class for version 1.0.6
 *
 * @package SAAI
 */

namespace SAAI\Updates;

use SAAI\Abstracts\Abstract_Class;
use SAAI\Helpers\Helper;

defined( 'ABSPATH' ) || exit;

/**
 * Version 1.0.6 update class.
 */
class Version_1_0_6 extends Abstract_Class {

    /**
     * Run the update.
     */
    public function run() {
        global $wpdb;

        if ( version_compare( get_option( SAAI_INSTALLED_VERSION ), '1.0.6', '<' ) ) {
            // Migrate options with new naming convention.
            $agents = Helper::get_ai_agents();

            foreach ( $agents as $agent ) {
                $old_settings_key = '_' . str_replace( '-', '_', $agent['id'] );
                $new_settings_key = 'saai_' . str_replace( '-', '_', $agent['id'] );

                $old_settings = get_option( $old_settings_key );
                if ( ! empty( $old_settings ) ) {
                    update_option( $new_settings_key, $old_settings, 'no' );

                    delete_option( $old_settings_key );
                }
            }

            // Add hide_archive column to storeagent_notifications table if it doesn't exist.
            $table_name = $wpdb->prefix . 'storeagent_notifications';

            // Check if the column exists.
            $column_exists = $wpdb->get_results(
                $wpdb->prepare(
                    "SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s AND COLUMN_NAME = 'hide_archive'",
                    DB_NAME,
                    $table_name
                )
            );

            // If the column doesn't exist, add it.
            if ( empty( $column_exists ) ) {
                // For ALTER TABLE queries, we can't use placeholders for table names or column definitions.
                // But since we're using $wpdb->prefix which is safe, this is an acceptable use case.
                // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
                $wpdb->query( "ALTER TABLE $table_name ADD COLUMN hide_archive TINYINT(1) DEFAULT 0 AFTER archived" );
            }
        }
    }
}
