<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('emplettes', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->string('status', 32)->default('draft'); // draft, submitted, quoting, quoted, client_review, accepted, rejected, converted
            $table->decimal('estimated_total', 12, 2)->default(0);
            $table->decimal('final_total', 12, 2)->default(0);
            $table->string('currency', 8)->default('XOF');
            $table->text('notes')->nullable();
            $table->foreignId('order_id')->nullable()->constrained('orders')->nullOnDelete();
            $table->timestamps();
        });

        Schema::create('emplette_items', function (Blueprint $table) {
            $table->id();
            $table->foreignId('emplette_id')->constrained('emplettes')->cascadeOnDelete();
            $table->string('name');
            $table->unsignedInteger('quantity')->default(1);
            $table->decimal('client_price', 12, 2)->default(0); // prix proposé par le client (par unité ou total estimé)
            $table->decimal('admin_price', 12, 2)->default(0); // prix ajusté par l'admin
            $table->string('status', 32)->default('pending'); // pending, updated, accepted, removed
            $table->text('notes')->nullable();
            $table->timestamps();
        });

        Schema::create('emplette_logs', function (Blueprint $table) {
            $table->id();
            $table->foreignId('emplette_id')->constrained('emplettes')->cascadeOnDelete();
            $table->foreignId('user_id')->nullable()->constrained()->nullOnDelete(); // admin ou client
            $table->string('actor_type', 32)->nullable(); // client, admin, system
            $table->string('action', 64); // created, submitted, quote_sent, accepted, rejected, updated_item, etc.
            $table->json('payload')->nullable(); // détails de la modification (avant/après)
            $table->text('message')->nullable(); // message lisible pour l'historique
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('emplette_logs');
        Schema::dropIfExists('emplette_items');
        Schema::dropIfExists('emplettes');
    }
};

