<?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::create('estimates', function (Blueprint $table) {
            $table->id();
            $table->string('estimate_number')->unique();
            $table->foreignId('job_card_id')->constrained()->onDelete('cascade');
            $table->foreignId('diagnosis_id')->constrained()->onDelete('cascade');
            $table->foreignId('prepared_by_id')->constrained('users')->onDelete('cascade');
            
            // Cost breakdown
            $table->decimal('labor_cost', 10, 2)->default(0);
            $table->decimal('parts_cost', 10, 2)->default(0);
            $table->decimal('miscellaneous_cost', 10, 2)->default(0);
            $table->decimal('subtotal', 10, 2)->default(0);
            $table->decimal('tax_rate', 5, 4)->default(8.25);
            $table->decimal('tax_amount', 10, 2)->default(0);
            $table->decimal('discount_amount', 10, 2)->default(0);
            $table->decimal('total_amount', 10, 2)->default(0);
            
            // Terms and validity
            $table->integer('validity_period_days')->default(30);
            $table->text('terms_and_conditions')->nullable();
            
            // Status tracking
            $table->enum('status', ['draft', 'sent', 'viewed', 'approved', 'rejected', 'expired', 'revised'])->default('draft');
            $table->enum('customer_approval_status', ['pending', 'approved', 'rejected', 'partially_approved'])->default('pending');
            
            // Customer interaction tracking
            $table->timestamp('customer_approved_at')->nullable();
            $table->enum('customer_approval_method', ['email', 'sms', 'phone', 'in_person', 'portal'])->nullable();
            $table->timestamp('sent_to_customer_at')->nullable();
            $table->timestamp('sms_sent_at')->nullable();
            $table->timestamp('email_sent_at')->nullable();
            
            // Notes and revisions
            $table->text('notes')->nullable();
            $table->text('internal_notes')->nullable();
            $table->integer('revision_number')->default(1);
            $table->foreignId('original_estimate_id')->nullable()->constrained('estimates')->onDelete('set null');
            
            $table->timestamps();
            
            // Indexes
            $table->index(['status', 'customer_approval_status']);
            $table->index(['job_card_id', 'diagnosis_id']);
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('estimates');
    }
};
