<?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('crm_quotes', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('tenant_id');
            $table->string('quote_number', 50)->unique();
            $table->unsignedBigInteger('lead_id')->nullable();
            $table->unsignedBigInteger('corporate_account_id')->nullable();
            $table->decimal('base_rate', 12, 2)->nullable();
            $table->decimal('discount_percentage', 5, 2)->nullable();
            $table->decimal('discount_amount', 12, 2)->nullable();
            $table->decimal('total_amount', 12, 2)->nullable();
            $table->string('currency', 3)->default('USD');
            $table->integer('validity_days')->default(30);
            $table->date('quote_date')->nullable();
            $table->date('valid_until')->nullable();
            $table->json('vehicles_included')->nullable();
            $table->text('terms')->nullable();
            $table->string('payment_terms', 100)->nullable();
            $table->enum('status', ['draft', 'sent', 'under_review', 'accepted', 'rejected', 'expired'])
                ->default('draft');
            $table->unsignedBigInteger('generated_by')->nullable();
            $table->timestamp('sent_at')->nullable();
            $table->timestamp('accepted_at')->nullable();
            $table->timestamps();
            
            $table->foreign('tenant_id')->references('id')->on('tenants')->onDelete('cascade');
            $table->foreign('lead_id')->references('id')->on('crm_leads')->nullOnDelete();
            $table->foreign('corporate_account_id')->references('id')->on('corporate_accounts')->nullOnDelete();
            $table->foreign('generated_by')->references('id')->on('users')->nullOnDelete();
            $table->index('tenant_id');
            $table->index('quote_number');
            $table->index('status');
        });
    }

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