<?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('payments', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained('users')->onDelete('cascade');
            $table->foreignId('cart_id')->nullable()->constrained('carts')->onDelete('set null');

            // Payment reference
            $table->string('reference')->unique(); // internal reference e.g. PAY-000142
            $table->string('provider_reference')->nullable(); // Stripe/Paystack/Mpesa ref

            // Provider
            $table->enum('provider', [
                'stripe',
                'paystack',
                'mpesa',
                'bank_transfer',
                'manual'
            ])->default('mpesa');

            // Method
            $table->enum('method', [
                'card',
                'mpesa_stk',
                'mpesa_paybill',
                'bank_transfer',
                'manual'
            ])->default('mpesa_stk');

            // Amounts
            $table->string('currency')->default('KES');
            $table->decimal('amount', 14, 2);
            $table->decimal('fee', 14, 2)->default(0.00);
            $table->decimal('amount_received', 14, 2)->default(0.00);

            // Status
            $table->enum('status', [
                'pending',
                'processing',
                'succeeded',
                'failed',
                'refunded',
                'partially_refunded',
                'cancelled'
            ])->default('pending');

            // Refund
            $table->decimal('refund_amount', 14, 2)->default(0.00);
            $table->timestamp('refunded_at')->nullable();
            $table->text('refund_reason')->nullable();

            // Provider response
            $table->json('provider_payload')->nullable();
            $table->timestamp('paid_at')->nullable();
            $table->text('failure_reason')->nullable();

            // Billing details
            $table->string('billing_name')->nullable();
            $table->string('billing_email')->nullable();
            $table->string('billing_phone')->nullable();

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

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