<?php

namespace App\Events;

use App\Models\MobileTransaction;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class MobileTransactionRequested implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public MobileTransaction $transaction;

    public function __construct(MobileTransaction $transaction)
    {
        // gateway + user relation দরকার হলে এখানে load
        $this->transaction = $transaction->loadMissing('gateway', 'user');
    }

    /**
     * JS এ যেটা subscribe করবে: "mobile-transaction-channel"
     */
    public function broadcastOn(): Channel
    {
        return new Channel('mobile-transaction-channel');
    }

    /**
     * JS event name: "mobile-transaction-event"
     */
    public function broadcastAs(): string
    {
        return 'mobile-transaction-event';
    }

    /**
     * Frontend এ যা data যাবে
     */
    public function broadcastWith(): array
    {
        $gw = $this->transaction->gateway;

        return [
            'id'             => $this->transaction->id,
            'amount'         => (float) $this->transaction->amount,
            'status'         => $this->transaction->status,
            'gateway_id'     => $this->transaction->gateway_id,
            'gateway_code'   => $gw?->code,
            'gateway_name'   => $gw?->name,
            'account_number' => $this->transaction->account_number,
            'channel'        => $this->transaction->channel,   // agent/personal
            'reference'      => $this->transaction->reference,
            'user_id'        => $this->transaction->user_id,
            'user_name'      => $this->transaction->user?->name,
            'created_at'     => optional($this->transaction->created_at)->toDateTimeString(),
        ];
    }
}
