<?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
    {
        // First, create the table without foreign key constraints
        Schema::create('customer_prop_service', function (Blueprint $table) {
            $table->unsignedBigInteger('CustomerID');
            $table->unsignedBigInteger('IDService');
            $table->decimal('Price', 10, 2)->nullable();
            $table->date('StartDate')->useCurrent();
            $table->date('EndDate')->nullable();
            $table->boolean('IsActive')->default(true);
            $table->text('Notes')->nullable();
            $table->integer('Quantity')->default(1);
            $table->timestamps();
            
            // Composite primary key
            $table->primary(['CustomerID', 'IDService']);
        });

        // Add foreign key constraints after ensuring both tables exist
        if (Schema::hasTable('customer') && Schema::hasTable('propservice')) {
            Schema::table('customer_prop_service', function (Blueprint $table) {
                $table->foreign('CustomerID')
                      ->references('CustomerID')
                      ->on('customer')
                      ->onDelete('cascade');
                      
                $table->foreign('IDService')
                      ->references('IDService')
                      ->on('propservice')
                      ->onDelete('cascade');
            });
        }
    }

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