<?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('contracts', function (Blueprint $table) {
            $table->id();
            $table->string('contract_no', 50)->unique();
            $table->string('title', 255);
            $table->foreignId('party_id')->constrained('parties')->onDelete('restrict');
            $table->enum('type', ['purchase', 'sale'])->default('purchase');
            $table->date('start_date');
            $table->date('end_date')->nullable();
            $table->foreignId('item_id')->nullable()->constrained('items')->onDelete('set null');
            $table->decimal('agreed_rate', 15, 2)->default(0);
            $table->decimal('agreed_quantity', 15, 3)->default(0);
            $table->string('quantity_unit', 20)->default('kg');
            $table->decimal('delivered_quantity', 15, 3)->default(0);
            $table->decimal('pending_quantity', 15, 3)->default(0);
            $table->decimal('agent_commission_rate', 10, 2)->default(0); // per unit commission
            $table->decimal('transport_rate', 10, 2)->default(0); // per unit transport
            $table->text('terms')->nullable();
            $table->text('remarks')->nullable();
            $table->enum('status', ['draft', 'active', 'completed', 'cancelled'])->default('active');
            $table->foreignId('created_by')->nullable()->constrained('users')->onDelete('set null');
            $table->timestamps();
            $table->softDeletes();
            
            $table->index('party_id');
            $table->index('item_id');
            $table->index('status');
            $table->index(['start_date', 'end_date']);
        });

        // Add contract_id to purchases and sales tables
        Schema::table('purchases', function (Blueprint $table) {
            $table->foreignId('contract_id')->nullable()->after('party_id')->constrained('contracts')->onDelete('set null');
        });

        Schema::table('sales', function (Blueprint $table) {
            $table->foreignId('contract_id')->nullable()->after('party_id')->constrained('contracts')->onDelete('set null');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('purchases', function (Blueprint $table) {
            $table->dropForeign(['contract_id']);
            $table->dropColumn('contract_id');
        });

        Schema::table('sales', function (Blueprint $table) {
            $table->dropForeign(['contract_id']);
            $table->dropColumn('contract_id');
        });

        Schema::dropIfExists('contracts');
    }
};
