<?php

declare(strict_types=1);

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('offers', function (Blueprint $table): void {
            $table->id();
            $table->string('offer_number')->unique();
            $table->foreignId('customer_id')->nullable()->constrained()->nullOnDelete();
            $table->foreignId('contact_id')->nullable()->constrained()->nullOnDelete();
            $table->string('subject')->default('');
            $table->longText('intro_html')->nullable();

            $table->date('valid_until')->nullable();
            $table->string('discount_type', 24)->default('none');
            $table->decimal('discount_value', 15, 4)->default(0);

            $table->decimal('vat_total', 15, 4)->default(0);

            $table->string('status', 24)->default('draft');
            $table->uuid('public_uuid')->nullable()->unique();

            $table->timestamp('sent_at')->nullable();
            $table->timestamp('viewed_at')->nullable();
            $table->timestamp('signed_at')->nullable();
            $table->timestamp('declined_at')->nullable();
            $table->text('decline_reason')->nullable();

            $table->string('signer_name')->nullable();
            $table->string('signature_path')->nullable();

            $table->boolean('is_template')->default(false);
            $table->string('template_name')->nullable();

            $table->unsignedBigInteger('hour_project_id')->nullable();
            $table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
            $table->foreignId('updated_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamps();

            $table->index(['is_template', 'template_name']);
            $table->index(['status']);
            $table->index(['customer_id']);
            $table->index(['hour_project_id']);
        });

        if (Schema::hasTable('hour_projects')) {
            Schema::table('offers', function (Blueprint $table): void {
                $table->foreign('hour_project_id')
                    ->references('id')
                    ->on('hour_projects')
                    ->nullOnDelete();
            });
        }
    }

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