<?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::dropIfExists('payment_collection_items');
        Schema::dropIfExists('payment_collections');
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        // Recreate payment_collections table
        Schema::create('payment_collections', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('collection_code', 100)->unique();
            $table->date('date');
            $table->unsignedBigInteger('customer_id');
            $table->unsignedBigInteger('rep_id')->nullable();
            $table->decimal('total_amount', 15, 2)->default(0);
            $table->text('remark')->nullable();
            $table->boolean('is_complete')->default(false);
            $table->unsignedBigInteger('created_by')->nullable();
            $table->unsignedBigInteger('updated_by')->nullable();
            $table->timestamps();

            $table->foreign('customer_id')->references('id')->on('customers')->onDelete('cascade');
            $table->foreign('rep_id')->references('id')->on('users')->onDelete('set null');
            $table->foreign('created_by')->references('id')->on('users')->onDelete('set null');
            $table->foreign('updated_by')->references('id')->on('users')->onDelete('set null');
        });

        // Recreate payment_collection_items table
        Schema::create('payment_collection_items', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('payment_collection_id');
            $table->string('collection_code', 100)->nullable();
            $table->unsignedBigInteger('invoice_id');
            $table->decimal('invoice_amount', 15, 2)->default(0);
            $table->decimal('paid_amount', 15, 2)->default(0);
            $table->decimal('balance_amount', 15, 2)->default(0);
            $table->timestamps();

            $table->foreign('payment_collection_id')
                ->references('id')->on('payment_collections')
                ->onDelete('cascade');
            $table->foreign('invoice_id')->references('id')->on('invoices')->onDelete('cascade');
        });
    }
};
