<?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
    {
        if (!Schema::hasTable('billing_history')) {
            Schema::create('billing_history', function (Blueprint $table) {
                $table->id();
                $table->foreignId('user_id')->constrained('users')->onDelete('cascade');
                $table->foreignId('subscription_id')->nullable()->constrained('subscriptions')->onDelete('set null');
                $table->foreignId('payment_method_id')->nullable()->constrained('payment_methods')->onDelete('set null');
                $table->string('invoice_number')->unique();
                $table->date('billing_date');
                $table->decimal('amount', 10, 2);
                $table->string('currency', 3)->default('USD');
                $table->enum('status', ['pending', 'paid', 'failed', 'refunded'])->default('pending');
                $table->string('plan_name')->nullable();
                $table->string('billing_period')->nullable(); // e.g., "2024-01"
                $table->string('invoice_url')->nullable();
                $table->string('pdf_url')->nullable();
                $table->string('payment_gateway')->nullable();
                $table->string('gateway_transaction_id')->nullable();
                $table->text('notes')->nullable();
                $table->timestamps();
                
                $table->index(['user_id', 'billing_date']);
                $table->index(['user_id', 'status']);
                $table->index('invoice_number');
            });
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('billing_history');
    }
};
