<?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('platform_orders', function (Blueprint $table) {
            $table->id();
            $table->foreignId('merchant_id')->constrained('merchants')->cascadeOnDelete();
            $table->foreignId('plan_id')->nullable()->constrained('plans')->nullOnDelete();
            $table->foreignId('site_subscription_id')->nullable()->constrained('site_subscriptions')->nullOnDelete();
            $table->foreignId('created_by_admin_id')->nullable()->constrained('admins')->nullOnDelete();
            $table->string('order_no', 50)->unique();
            $table->string('order_type', 30)->default('new_purchase');
            $table->string('status', 30)->default('pending');
            $table->string('payment_status', 30)->default('unpaid');
            $table->string('payment_channel', 30)->nullable();
            $table->string('plan_name', 100)->nullable();
            $table->string('billing_cycle', 30)->nullable();
            $table->unsignedInteger('period_months')->default(1);
            $table->unsignedInteger('quantity')->default(1);
            $table->decimal('list_amount', 10, 2)->default(0);
            $table->decimal('discount_amount', 10, 2)->default(0);
            $table->decimal('payable_amount', 10, 2)->default(0);
            $table->decimal('paid_amount', 10, 2)->default(0);
            $table->timestamp('placed_at')->nullable();
            $table->timestamp('paid_at')->nullable();
            $table->timestamp('activated_at')->nullable();
            $table->timestamp('cancelled_at')->nullable();
            $table->timestamp('refunded_at')->nullable();
            $table->json('plan_snapshot')->nullable();
            $table->json('meta')->nullable();
            $table->text('remark')->nullable();
            $table->timestamps();

            $table->index(['merchant_id', 'status']);
            $table->index(['payment_status', 'status']);
            $table->index(['plan_id', 'status']);
            $table->index('placed_at');
            $table->index('paid_at');
        });
    }

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