<?php

namespace App\Observers;

use App\Core\Hook\HookBridge;
use App\Models\Transaction;

/**
 * TransactionObserver
 *
 * Fires WHMCS-named action hooks on Transaction lifecycle events.
 *
 * Hook coverage:
 *   - AddTransaction (fired on created)
 *
 * WHMCS param → PROCP field mapping:
 *   id          → $txn->id
 *   userid      → client_id
 *   currency    → currency_id
 *   gateway     → payment_gateway
 *   date        → created_at->toDateTimeString()
 *   description → description
 *   amountin    → amount_in (fallback: amount)
 *   fees        → bank_fee
 *   amountout   → amount_out
 *   rate        → (no rate column — always 1.0)
 *   transid     → transaction_id
 *   invoiceid   → invoice_id
 *   refundid    → (no refund_id column — always null)
 */
class TransactionObserver
{
    /**
     * Handle the Transaction "created" event.
     * Fires: AddTransaction
     */
    public function created(Transaction $txn): void
    {
        app(HookBridge::class)->fireAction('AddTransaction', [
            'id'          => $txn->id,
            'transaction' => $txn,
            'userid'      => $txn->client_id,
            'currency'    => $txn->currency_id,
            'gateway'     => $txn->payment_gateway,
            'date'        => optional($txn->created_at)->toDateTimeString(),
            'description' => $txn->description,
            'amountin'    => (float) ($txn->amount_in ?? $txn->amount ?? 0),
            'fees'        => (float) ($txn->bank_fee ?? 0),
            'amountout'   => (float) ($txn->amount_out ?? 0),
            'rate'        => 1.0,
            'transid'     => $txn->transaction_id,
            'invoiceid'   => $txn->invoice_id,
            'refundid'    => null,
        ]);
    }
}
