<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('requests', function (Blueprint $table) {
            // Supprimer les contraintes de clé étrangère
            $table->dropForeign(['approved_by']);
            $table->dropForeign(['rejected_by']);

            // Modifier les colonnes pour les rendre nullable
            $table->unsignedBigInteger('approved_by')->nullable()->change();
            $table->unsignedBigInteger('rejected_by')->nullable()->change();

            // Recréer les contraintes de clé étrangère avec nullable
            $table->foreign('approved_by')->references('id')->on('users')->cascadeOnDelete('set null');
            $table->foreign('rejected_by')->references('id')->on('users')->cascadeOnDelete('set null');

            // Ajouter des champs manquants
            $table->date('requested_date')->nullable()->after('status'); // Date de demande
            $table->date('delivery_date')->nullable()->after('requested_date'); // Date de livraison prévue
            $table->date('delivered_date')->nullable()->after('delivery_date'); // Date de livraison effective
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('requests', function (Blueprint $table) {
            $table->dropColumn(['requested_date', 'delivery_date', 'delivered_date']);

            // Supprimer les contraintes
            $table->dropForeign(['approved_by']);
            $table->dropForeign(['rejected_by']);

            // Remettre les colonnes en non-nullable
            $table->unsignedBigInteger('approved_by')->nullable(false)->change();
            $table->unsignedBigInteger('rejected_by')->nullable(false)->change();

            // Recréer les contraintes
            $table->foreign('approved_by')->references('id')->on('users')->cascadeOnDelete('set null');
            $table->foreign('rejected_by')->references('id')->on('users')->cascadeOnDelete('set null');
        });
    }
};