<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

/**
 * mportal_payment_intents — online-payment intent (SIFA Phase 8, patient_portal
 * → billing → make_payment).
 *
 * ⚠️ STUB — BACKLOG. This records an INTENT to pay an ERP invoice from the
 * portal and lets staff MARK IT PAID manually. No real payment gateway
 * (Stripe/PayTabs/Fawry/…) is wired — the ERP transaction + transaction_payments
 * remain the source of truth. `transaction_id` references the ERP transactions.id
 * the intent is against (nullable for a generic top-up). business_id-scoped.
 */
return new class extends Migration {
    public function up(): void
    {
        if (Schema::hasTable('mportal_payment_intents')) {
            return;
        }

        Schema::create('mportal_payment_intents', function (Blueprint $t) {
            $t->bigIncrements('id');
            $t->unsignedInteger('business_id');
            $t->unsignedInteger('patient_id');                 // clc_patients.id
            $t->unsignedInteger('transaction_id')->nullable(); // ERP transactions.id (invoice)
            $t->decimal('amount', 22, 4)->default(0);
            $t->enum('status', ['pending', 'paid', 'failed'])->default('pending');
            $t->enum('method', ['cash', 'card', 'online', 'insurance', 'other'])->default('online');
            $t->string('reference', 191)->nullable();          // stub external ref / manual note
            $t->unsignedInteger('marked_by')->nullable();      // users.id who marked paid
            $t->timestamp('paid_at')->nullable();
            $t->timestamps();

            $t->index(['business_id', 'patient_id'], 'mportal_pi_biz_patient_idx');
            $t->index(['business_id', 'status'], 'mportal_pi_biz_status_idx');
        });
    }

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