<?php

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

class AddAuditColumnsAndCreateAuditLogsTable extends Migration
{
    public function up()
    {
        // Skip if audit_logs already created
        if (Schema::hasTable('audit_logs')) {
            return;
        }
        
        // Ajouter colonnes d'audit aux tables critiques
        $tables = ['users', 'orders', 'commissions', 'wallet_transactions', 'withdrawals'];

        foreach ($tables as $tableName) {
            if (Schema::hasTable($tableName)) {
                Schema::table($tableName, function (Blueprint $t) use ($tableName) {
                    // Ajouter soft deletes si nécessaire
                    if (!Schema::hasColumn($tableName, 'deleted_at')) {
                        $t->softDeletes();
                    }
                    
                    // Ajouter colonnes d'audit
                    if (!Schema::hasColumn($tableName, 'updated_by')) {
                        $t->unsignedBigInteger('updated_by')->nullable();
                    }
                    if (!Schema::hasColumn($tableName, 'deleted_by')) {
                        $t->unsignedBigInteger('deleted_by')->nullable();
                    }
                });
            }
        }

        // Table d'audit logs (trace toutes les modifications)
        Schema::create('audit_logs', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id')->nullable(); // Qui a fait la modification
            $table->string('model')->index(); // Modèle affecté
            $table->unsignedBigInteger('model_id'); // ID du record
            $table->enum('action', ['created', 'updated', 'deleted'])->index();
            $table->json('before')->nullable(); // Données avant
            $table->json('after')->nullable(); // Données après
            $table->text('description')->nullable();
            $table->string('ip_address')->nullable();
            $table->string('user_agent')->nullable();
            $table->timestamps();
            
            $table->foreign('user_id')->references('id')->on('users')->onDelete('set null');
            $table->index(['model', 'model_id']);
            $table->index('created_at');
        });

        // Table de sauvegarde des modifications sensibles
        Schema::create('sensitive_field_changes', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id'); // L'utilisateur affecté
            $table->unsignedBigInteger('changed_by'); // Qui a changé
            $table->string('field_name'); // Champ modifié
            $table->string('table_name'); // Table
            $table->text('old_value')->nullable();
            $table->text('new_value')->nullable();
            $table->text('reason')->nullable();
            $table->timestamps();
            
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->foreign('changed_by')->references('id')->on('users')->onDelete('restrict');
        });
    }

    public function down()
    {
        // Supprimer les tables
        Schema::dropIfExists('sensitive_field_changes');
        Schema::dropIfExists('audit_logs');

        // Supprimer les colonnes
        $tables = ['users', 'orders', 'commissions', 'wallet_transactions', 'withdrawals'];
        foreach ($tables as $tableName) {
            if (Schema::hasTable($tableName)) {
                Schema::table($tableName, function (Blueprint $t) {
                    $t->dropColumn(['updated_by', 'deleted_by']);
                });
            }
        }
    }
}

