<?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('invoices', function (Blueprint $table) {
            $table->id();
            $table->string('invoice_number')->unique(); // MS-INV-2024-0045
            $table->foreignId('order_id')->constrained('orders')->cascadeOnDelete();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->string('title'); // e.g. "Booking Deposit (20%)", "Customs & Port Duty", "Final Balance"
            $table->decimal('amount_bdt', 14, 2);
            $table->decimal('paid_bdt', 14, 2)->default(0);
            $table->decimal('due_bdt', 14, 2);
            $table->date('due_date');
            $table->enum('status', ['unpaid', 'partially_paid', 'paid', 'cancelled'])->default('unpaid');
            $table->text('notes')->nullable();
            $table->timestamps();
        });

        Schema::create('payments', function (Blueprint $table) {
            $table->id();
            $table->string('payment_reference')->unique(); // MS-PAY-2024-0102
            $table->foreignId('invoice_id')->nullable()->constrained('invoices')->nullOnDelete();
            $table->foreignId('order_id')->constrained('orders')->cascadeOnDelete();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();

            $table->decimal('amount_bdt', 14, 2);
            $table->enum('payment_method', ['bank_transfer', 'bkash', 'nagad', 'cash', 'card', 'cheque'])->default('bank_transfer');
            $table->string('transaction_id')->nullable()->index();
            $table->string('bank_name')->nullable();
            $table->string('bank_branch')->nullable();
            $table->string('sender_phone_or_account')->nullable();
            $table->string('receipt_document_url')->nullable();

            $table->enum('status', ['pending', 'verified', 'rejected', 'refunded'])->default('pending');
            $table->foreignId('verified_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamp('verified_at')->nullable();
            $table->text('admin_notes')->nullable();

            $table->timestamps();
        });
    }

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