<?php
/**
 * Update class for version 1.1.2
 *
 * Migrates post meta keys from saai_product_* to saai_post_* naming convention
 * to support AI memory functionality for multiple post types beyond just products.
 *
 * @package SAAI\Updates
 * @since   1.1.2
 */

namespace SAAI\Updates;

use SAAI\Abstracts\Abstract_Class;
use SAAI\Classes\Memory\Data_Upload;

defined( 'ABSPATH' ) || exit;

/**
 * Version 1.1.2 update class.
 */
class Version_1_1_2 extends Abstract_Class {

    /**
     * Run the update to migrate meta keys from saai_product_* to saai_post_*.
     *
     * This update renames all product-specific meta keys to use the generic post_
     * prefix, allowing the AI memory feature to work with any post type.
     *
     * @since 1.1.2
     * @return void
     */
    public function run() {
        /**
         * Global WordPress database abstraction object.
         *
         * @var \wpdb $wpdb
         */
        global $wpdb;

        if ( version_compare( get_option( SAAI_INSTALLED_VERSION ), '1.1.2', '<' ) ) {
            $find_replace = array(
                'saai_product_ai_memory_enabled'     => Data_Upload::POST_AI_MEMORY_ENABLED_META,
                'saai_product_data_upload_hash'      => Data_Upload::POST_DATA_UPLOAD_HASH_META,
                'saai_product_data_upload_timestamp' => Data_Upload::POST_DATA_UPLOAD_TIMESTAMP_META,
                'saai_product_data_upload_pending'   => Data_Upload::PENDING_POST_DATA_UPLOAD_META,
                'saai_product_data_current_hash'     => Data_Upload::POST_DATA_CURRENT_HASH_META,
            );

            // Build query with placeholders and values array.
            $case_whens      = array();
            $case_values     = array();
            $in_placeholders = array();
            $in_values       = array();

            foreach ( $find_replace as $find => $replace ) {
                // Build CASE WHEN clauses with placeholders directly in the array.
                $case_whens[]  = 'WHEN %s THEN %s';
                $case_values[] = $find;
                $case_values[] = $replace;
                // Build IN clause placeholders and values.
                $in_placeholders[] = '%s';
                $in_values[]       = $find;
            }

            // Combine values: CASE values first, then IN values.
            $prepare_values = array_merge( $case_values, $in_values );

            // Build complete query string by concatenation (not interpolation) to preserve placeholders.
            $case_sql = 'CASE meta_key ' . implode( ' ', $case_whens ) . ' END';
            $in_sql   = implode( ',', $in_placeholders );

            // Build the full query using concatenation to ensure placeholders remain as %s.
            // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            $query = 'UPDATE ' . $wpdb->postmeta . ' SET meta_key = ' . $case_sql . ' WHERE meta_key IN (' . $in_sql . ')';

            // Use a single prepare call with all values using spread operator.
            // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
            $prepared_query = $wpdb->prepare( $query, ...$prepare_values );

            // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
            $result = $wpdb->query( $prepared_query );
            if ( false === $result ) {
                wc_get_logger()->error(
                    'StoreAgent AI v1.1.2: Failed to update post meta keys.',
                    array( 'source' => 'storeagent-ai-for-woocommerce' )
                );
                return;
            } elseif ( $wpdb->rows_affected > 0 ) {
                wc_get_logger()->info(
                    'StoreAgent AI v1.1.2: Post meta keys updated successfully.',
                    array( 'source' => 'storeagent-ai-for-woocommerce' )
                );

                wp_cache_flush();
            } else {
                wc_get_logger()->info(
                    'StoreAgent AI v1.1.2: No post meta keys updated.',
                    array( 'source' => 'storeagent-ai-for-woocommerce' )
                );
            }
        }
    }
}
