<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\DB;

return new class extends Migration
{
    public function up(): void
    {
        // Vérifier si la table existe déjà avant de la créer
        if (!Schema::hasTable('feature_toggles')) {
            Schema::create('feature_toggles', function (Blueprint $table) {
                $table->id();
                $table->string('feature_key')->unique();
                $table->string('name');
                $table->text('description')->nullable();
                $table->boolean('is_enabled')->default(true);
                $table->text('config')->nullable();
                $table->string('category')->default('general');
                $table->timestamps();
                
                $table->index('feature_key');
                $table->index('is_enabled');
            });
        } else {
            // Si la table existe, ajouter la colonne category si elle n'existe pas
            if (!Schema::hasColumn('feature_toggles', 'category')) {
                Schema::table('feature_toggles', function (Blueprint $table) {
                    $table->string('category')->default('general');
                });
            }
        }
        
        // Vérifier que la colonne category existe avant d'insérer
        if (!Schema::hasColumn('feature_toggles', 'category')) {
            return; // Skip insertion si la colonne n'existe toujours pas
        }
        
        // Insertion des features critiques (seulement si elles n'existent pas)
        $features = [
            [
                'feature_key' => 'mlm_commissions',
                'name' => 'Commissions MLM',
                'description' => 'Active/désactive le calcul et crédit des commissions MLM',
                'is_enabled' => true,
                'config' => null,
                'category' => 'mlm',
                'created_at' => now(),
                'updated_at' => now()
            ],
            [
                'feature_key' => 'quick_start_bonus',
                'name' => 'Bonus démarrage rapide',
                'description' => 'Bonus de 5,000 XOF au parrain quand filleul paie abonnement',
                'is_enabled' => true,
                'config' => null,
                'category' => 'mlm',
                'created_at' => now(),
                'updated_at' => now()
            ],
            [
                'feature_key' => 'withdrawals',
                'name' => 'Retraits wallet',
                'description' => 'Permet aux membres de demander des retraits',
                'is_enabled' => true,
                'config' => null,
                'category' => 'wallet',
                'created_at' => now(),
                'updated_at' => now()
            ],
            [
                'feature_key' => 'new_registrations',
                'name' => 'Nouvelles inscriptions',
                'description' => 'Autorise les nouvelles inscriptions membres',
                'is_enabled' => true,
                'config' => null,
                'category' => 'general',
                'created_at' => now(),
                'updated_at' => now()
            ],
            [
                'feature_key' => 'shop_orders',
                'name' => 'Commandes boutique',
                'description' => 'Autorise les commandes produits boutique',
                'is_enabled' => true,
                'config' => null,
                'category' => 'shop',
                'created_at' => now(),
                'updated_at' => now()
            ],
            [
                'feature_key' => 'investment_products',
                'name' => 'Produits d\'investissement',
                'description' => 'Active les produits d\'investissement AMM',
                'is_enabled' => true,
                'config' => null,
                'category' => 'investment',
                'created_at' => now(),
                'updated_at' => now()
            ],
            [
                'feature_key' => 'mobile_money_payments',
                'name' => 'Paiements Mobile Money',
                'description' => 'Active les paiements via MTN/Orange/Moov/Wave',
                'is_enabled' => true,
                'config' => null,
                'category' => 'payment',
                'created_at' => now(),
                'updated_at' => now()
            ],
            [
                'feature_key' => 'maintenance_mode',
                'name' => 'Mode maintenance',
                'description' => 'Bloque l\'accès au site pour les non-admins',
                'is_enabled' => false,
                'config' => null,
                'category' => 'general',
                'created_at' => now(),
                'updated_at' => now()
            ]
        ];
        
        // Insérer seulement les features qui n'existent pas
        foreach ($features as $feature) {
            try {
                if (!DB::table('feature_toggles')->where('feature_key', $feature['feature_key'])->exists()) {
                    DB::table('feature_toggles')->insert($feature);
                }
            } catch (\Exception $e) {
                // Ignorer les erreurs d'insertion
            }
        }
    }

    public function down(): void
    {
        Schema::dropIfExists('feature_toggles');
    }
};
