<?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('leads', function (Blueprint $t) {
            $t->id();
            $t->foreignId('company_id')->constrained()->cascadeOnDelete();
            $t->foreignId('client_id')->nullable()->constrained()->nullOnDelete();
            $t->foreignId('vehicle_id')->nullable()->constrained()->nullOnDelete();

            $t->string('name');
            $t->string('phone');
            $t->string('email')->nullable();
            $t->string('car')->nullable();
            $t->string('model')->nullable();
            $t->text('message')->nullable();

            $t->string('source')->nullable();             // call/site/telegram/whatsapp/instagram/google/...
            $t->string('marketing_channel')->nullable();
            $t->string('utm_source')->nullable();
            $t->string('utm_medium')->nullable();
            $t->string('utm_campaign')->nullable();
            $t->string('utm_term')->nullable();
            $t->string('utm_content')->nullable();

            $t->string('status')->default('new');         // new/contacted/no_answer/scheduled/converted/lost
            $t->decimal('budget', 12, 2)->nullable();
            $t->foreignId('assigned_to')->nullable()->constrained('users')->nullOnDelete();
            $t->foreignId('deal_id')->nullable();         // set when converted
            $t->timestamp('contacted_at')->nullable();
            $t->timestamp('converted_at')->nullable();
            $t->text('notes')->nullable();

            $t->timestamps();
            $t->softDeletes();

            $t->index(['company_id', 'status']);
            $t->index(['company_id', 'created_at']);
            $t->index(['company_id', 'source']);
        });
    }

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