<?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('subcontractors', function (Blueprint $t) {
            $t->id();
            $t->foreignId('company_id')->constrained()->cascadeOnDelete();
            $t->string('name');
            $t->string('specialty', 48)->nullable();   // Turbo / Cutie viteze / ...
            $t->string('phone', 40)->nullable();
            $t->string('email')->nullable();
            $t->unsignedTinyInteger('rating')->default(3);
            $t->boolean('is_active')->default(true);
            $t->text('notes')->nullable();
            $t->timestamps();
            $t->softDeletes();

            $t->index(['company_id', 'is_active']);
        });

        Schema::create('subcontract_jobs', function (Blueprint $t) {
            $t->id();
            $t->foreignId('company_id')->constrained()->cascadeOnDelete();
            $t->foreignId('work_order_id')->nullable()->constrained()->nullOnDelete();
            $t->foreignId('subcontractor_id')->nullable()->constrained()->nullOnDelete();

            $t->string('number', 32);
            $t->string('category', 48)->nullable();
            $t->text('description')->nullable();

            $t->decimal('cost', 12, 2)->default(0);          // what the sub charges us
            $t->decimal('markup_pct', 5, 2)->default(0);
            $t->decimal('client_price', 12, 2)->default(0);  // what we bill the client

            $t->string('status', 16)->default('sent');       // sent / in_progress / done / returned / cancelled
            $t->date('sent_at')->nullable();
            $t->date('eta')->nullable();
            $t->date('returned_at')->nullable();
            $t->boolean('paid_to_sub')->default(false);
            $t->text('notes')->nullable();

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

            $t->unique(['company_id', 'number']);
            $t->index(['company_id', 'status']);
            $t->index(['company_id', 'work_order_id']);
        });
    }

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