<?php

namespace App\Events;

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

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

    public Recharge $recharge;

    /**
     * Create a new event instance.
     */
    public function __construct(Recharge $recharge)
    {
        // user relation সহ লোড করে রাখি
        $this->recharge = $recharge->load('user');
    }

    /**
     * কোন channel এ broadcast হবে
     */
    public function broadcastOn(): array
    {
        // অন্যগুলো যেভাবে আলাদা channel ব্যবহার করতেছো, এটা সেই স্টাইলে
        return ['recharge-channel'];
    }

    /**
     * JS side এ event নাম
     */
    public function broadcastAs(): string
    {
        return 'recharge-event';
    }

    /**
     * Frontend এ যাবে যে payload
     */
    public function broadcastWith(): array
    {
        return [
            'id'           => $this->recharge->id,
            'amount'       => (float) $this->recharge->amount,
            'service_type' => $this->recharge->service_type,
            'status'       => $this->recharge->status,
            'txn_id'       => $this->recharge->txn_id,
            'msisdn'       => $this->recharge->msisdn,
            'reference'    => $this->recharge->reference,
            'user'         => [
                'id'    => $this->recharge->user?->id,
                'name'  => $this->recharge->user?->name,
                'phone' => $this->recharge->user?->phone,
            ],
            'created_at'   => optional($this->recharge->created_at)->toDateTimeString(),
        ];
    }
}
