<?php

use Openguru\OpenCartFramework\Migrations\Migration;
use Openguru\OpenCartFramework\OpenCart\Decorators\OcRegistryDecorator;
use Openguru\OpenCartFramework\Support\Arr;

return new class extends Migration {
    public function up(): void
    {
        $opencart = $this->app->get(OcRegistryDecorator::class);
        $opencart->load->model('setting/setting');

        $currentSettings = $opencart->model_setting_setting->getSetting('module_telecart');
        
        if (! $currentSettings || ! isset($currentSettings['module_telecart_settings'])) {
            $this->logger->info("Settings not found in database, migration skipped");
            return;
        }

        $allSettings = $currentSettings['module_telecart_settings'];
        
        // Проверяем наличие store.enable_store
        $enableStore = Arr::get($allSettings, 'store.enable_store');
        
        if ($enableStore !== null) {
            // Определяем значение product_interaction_mode на основе store.enable_store
            $productInteractionMode = filter_var($enableStore, FILTER_VALIDATE_BOOLEAN) 
                ? 'order' 
                : 'browser';
            
            // Устанавливаем product_interaction_mode, если его еще нет
            if (!isset($allSettings['store']['product_interaction_mode'])) {
                Arr::set($allSettings, 'store.product_interaction_mode', $productInteractionMode);
                $this->logger->info("Migrated store.enable_store to product_interaction_mode: {$enableStore} -> {$productInteractionMode}");
            } else {
                $this->logger->info("product_interaction_mode already exists, skipping migration but removing store.enable_store");
            }
            
            // Удаляем store.enable_store из настроек
            Arr::unset($allSettings, 'store.enable_store');
            $this->logger->info("Removed store.enable_store from settings");
            
            // Сохраняем обновленные настройки через OpenCart модель
            $opencart->model_setting_setting->editSetting('module_telecart', [
                'module_telecart_settings' => $allSettings,
            ]);
            
            $this->logger->info("Successfully migrated store.enable_store to product_interaction_mode and removed store.enable_store from settings");
        } else {
            $this->logger->info("store.enable_store not found in settings, migration skipped");
        }
    }
};

