<?php

namespace App\Domain\Financial\Listeners;

use App\Domain\Financial\Events\PaymentReceived;
use App\Domain\Notification\Services\NotificationService;
use App\Domain\Participant\Models\Participant;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;

class SendPaymentNotification implements ShouldQueue
{
    public function __construct(
        private NotificationService $notificationService,
    ) {}

    public function handle(PaymentReceived $event): void
    {
        $payment = $event->payment;

        // Only send notification if payer is a Participant
        if ($payment->payer_type !== Participant::class) {
            return;
        }

        try {
            $participant = Participant::with('person')->find($payment->payer_id);

            if (!$participant || !$participant->person) {
                Log::warning('SendPaymentNotification: participant or person not found', [
                    'payment_id' => $payment->id,
                    'payer_id' => $payment->payer_id,
                ]);
                return;
            }

            $person = $participant->person;

            // Format amount from piasters to pounds
            $formattedAmount = number_format($payment->amount / 100, 2);

            // Get Arabic method label
            $methodLabel = $payment->method?->label() ?? 'غير محدد';

            // Format payment date
            $paymentDate = $payment->payment_date?->format('Y-m-d') ?? '';

            $variables = [
                'participant_name' => $person->name_ar ?? $person->name ?? '',
                'amount' => $formattedAmount,
                'method' => $methodLabel,
                'date' => $paymentDate,
                'receipt_number' => $payment->reference ?? '',
                'invoice_number' => $payment->invoice?->number ?? '',
            ];

            $this->notificationService->send(
                eventType: 'payment.received',
                recipientType: 'participant',
                recipientId: $participant->id,
                academyId: $payment->academy_id,
                variables: $variables,
                recipientEmail: $person->email,
                recipientPhone: $person->phone,
            );
        } catch (\Throwable $e) {
            Log::error('SendPaymentNotification failed: ' . $e->getMessage(), [
                'payment_id' => $payment->id,
            ]);
        }
    }

    public function failed(PaymentReceived $event, \Throwable $exception): void
    {
        Log::critical('SendPaymentNotification PERMANENTLY FAILED', [
            'payment_id' => $event->payment->id,
            'error' => $exception->getMessage(),
        ]);
    }
}
