<?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('settlements', function (Blueprint $table) {
            $table->id();
            $table->foreignId('vendor_id')->constrained()->cascadeOnDelete();
            $table->string('reference')->unique(); // e.g. SET-20260618-0001
            $table->decimal('gross_amount', 12, 2);
            $table->decimal('commission_deducted', 12, 2);
            $table->decimal('net_amount', 12, 2);
            $table->enum('method', ['bank', 'easypaisa', 'jazzcash']);
            $table->string('account_name');
            $table->string('account_number');
            $table->enum('status', ['pending', 'approved', 'processing', 'paid', 'failed'])->default('pending');
            $table->foreignId('approved_by')->nullable()->constrained('admins')->nullOnDelete();
            $table->timestamp('approved_at')->nullable();
            $table->timestamp('paid_at')->nullable();
            $table->string('payment_proof')->nullable();
            $table->text('notes')->nullable();
            $table->date('period_from');
            $table->date('period_to');
            $table->timestamps();
        });

        // Links settlement to specific order items
        Schema::create('settlement_items', function (Blueprint $table) {
            $table->id();
            $table->foreignId('settlement_id')->constrained()->cascadeOnDelete();
            $table->foreignId('order_item_id')->constrained()->cascadeOnDelete();
            $table->decimal('amount', 10, 2);
            $table->timestamps();
        });

        Schema::create('wallet_transactions', function (Blueprint $table) {
            $table->id();
            $table->morphs('owner'); // user or delivery_partner
            $table->enum('type', ['credit', 'debit']);
            $table->string('purpose'); // refund, cashback, earning, withdrawal, cod_collected
            $table->decimal('amount', 12, 2);
            $table->decimal('balance_before', 12, 2);
            $table->decimal('balance_after', 12, 2);
            $table->string('reference')->nullable();
            $table->text('description')->nullable();
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('wallet_transactions');
        Schema::dropIfExists('settlement_items');
        Schema::dropIfExists('settlements');
    }
};
