<?php

namespace Phox\core\upgrade;

use Phox\core\admin\DB_Proxy;
use Phox\core\upgrade\Upgrade_Abstract;

class Upgrade_Migration_254 extends Upgrade_Abstract
{

    /**
     * @inheritDoc
     */
    protected function set_version(): void
    {
        $this->version = '2.5.4';
    }

    /**
     * @inheritDoc
     */
    public function run(): void
    {
        // Initialize DB_Proxy
        $db_proxy = new DB_Proxy();
        $db_proxy->set_db_options();

        // Get the existing openai_api_key value
        $openai_api_key = $db_proxy->get_option('openai_api_key', '');

        // Get all current options
        $options = $db_proxy->get_options();

        // Check if openai_api_key has a value
        if (!empty($openai_api_key) && is_string($openai_api_key)) {
            // Set ai_provider to 'openai' and openai_model to default value
            $options['ai_provider'] = 'openai';
            $options['openai_model'] = 'gpt-5.2'; // Default OpenAI model
        } else {
            // If openai_api_key is empty, ensure new fields are set to empty/default
            $options['ai_provider'] = isset($options['ai_provider']) ? $options['ai_provider'] : '';
            $options['openai_model'] = isset($options['openai_model']) ? $options['openai_model'] : '';
            $options['gemini_api_key'] = isset($options['gemini_api_key']) ? $options['gemini_api_key'] : '';
            $options['gemini_model'] = isset($options['gemini_model']) ? $options['gemini_model'] : '';
        }

        // Update the options in the database
        $db_proxy->update_options($options);
    }
}
