<?php
/**
 * ارتقای فاز ۳ — AI chat log + تنظیمات یکپارچه‌سازی
 * php run-arag-upgrade-v3.php
 */
declare(strict_types=1);

define( 'ACC_BASE_PATH', __DIR__ );
require_once __DIR__ . '/standalone/bootstrap.php';

header( 'Content-Type: application/json; charset=utf-8' );
global $wpdb;
$pre     = $wpdb->prefix;
$charset = 'DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci';
$done    = [];

$wpdb->query( "CREATE TABLE IF NOT EXISTS {$pre}arag_ai_chat_log (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    session_id VARCHAR(64) NOT NULL DEFAULT '',
    user_msg TEXT NOT NULL,
    bot_msg TEXT NOT NULL,
    engine VARCHAR(20) NOT NULL DEFAULT 'rules',
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    KEY session_id (session_id),
    KEY created_at (created_at)
) {$charset}" );
$done[] = 'arag_ai_chat_log';

$defaults = [
    'acc_shop_otp_demo'       => '1',
    'acc_sms_provider'        => 'log',
    'acc_sms_sender'          => '',
    'acc_zarinpal_sandbox'    => '1',
    'acc_shop_ai_enabled'     => '1',
    'acc_shop_ai_base_url'    => 'https://api.openai.com/v1',
    'acc_shop_ai_model'       => 'gpt-4o-mini',
];
foreach ( $defaults as $k => $v ) {
    $exists = (int) $wpdb->get_var(
        $wpdb->prepare( "SELECT option_id FROM {$wpdb->options} WHERE option_name = %s LIMIT 1", $k )
    );
    if ( ! $exists ) {
        update_option( $k, $v );
        $done[] = "option {$k}";
    }
}

echo json_encode( [ 'success' => true, 'changes' => $done ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT );
