<?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('serenatas', function (Blueprint $table) {
            $table->id();
            $table->foreignId('organization_id')->constrained()->cascadeOnDelete();
            $table->foreignId('created_by_user_id')->nullable()->constrained('users')->nullOnDelete();
            $table->unsignedInteger('sequence')->default(1);
            $table->string('code', 40);

            $table->string('payer_name');
            $table->string('service_address');
            $table->string('address_additional')->nullable();
            $table->string('neighborhood', 120);
            $table->string('locality', 120);
            $table->string('contact_phone_1', 30);
            $table->string('contact_phone_2', 30)->nullable();
            $table->string('reason');
            $table->string('from_name');
            $table->string('to_name');
            $table->date('event_date');
            $table->string('event_time', 5);
            $table->text('internal_notes')->nullable();
            $table->text('client_notes')->nullable();

            $table->decimal('base_price', 12, 2)->default(0);
            $table->decimal('gift_amount', 12, 2)->default(0);
            $table->json('gift_items')->nullable();
            $table->decimal('artist_amount', 12, 2)->default(0);
            $table->json('artist_items')->nullable();
            $table->decimal('other_cost_amount', 12, 2)->default(0);
            $table->json('other_cost_items')->nullable();
            $table->decimal('discount_amount', 12, 2)->default(0);
            $table->decimal('base_cost', 12, 2)->default(0);
            $table->decimal('total_charged', 12, 2)->default(0);
            $table->decimal('profit_amount', 12, 2)->default(0);
            $table->decimal('commission_rate', 5, 2)->default(0);
            $table->decimal('commission_amount', 12, 2)->default(0);

            $table->string('payment_status', 20)->default('Pendiente');
            $table->string('service_status', 40)->default('Pendiente');
            $table->string('payment_method', 40)->default('Efectivo al finalizar');
            $table->string('cancellation_reason', 600)->nullable();
            $table->decimal('ceded_amount', 12, 2)->default(0);

            $table->timestamps();

            $table->unique(['organization_id', 'code']);
            $table->unique(['organization_id', 'sequence']);
            $table->index(['organization_id', 'event_date']);
            $table->index(['organization_id', 'payment_status']);
            $table->index(['organization_id', 'service_status']);
        });
    }

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