<?php

namespace App\Listeners\Sales;

use App\Events\Sales\PaymentReceived;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Log;

class UpdateInvoicePaymentStatus implements ShouldQueue
{
    use InteractsWithQueue;

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

        Log::info('Payment received for invoice', [
            'invoice_id' => $invoice->id,
            'invoice_no' => $invoice->invoice_no,
            'amount' => $event->amount,
            'payment_method' => $event->paymentMethod,
            'reference_no' => $event->referenceNo,
            'triggered_by' => $event->userId,
        ]);

        // Refresh invoice to get updated totals
        $invoice->refresh();

        // Check if invoice is fully paid
        $paidAmount = $invoice->payments()->sum('amount');
        $grandTotal = $invoice->grand_total ?? 0;

        if ($paidAmount >= $grandTotal) {
            $invoice->update(['payment_status' => 'paid']);

            Log::info('Invoice fully paid', [
                'invoice_id' => $invoice->id,
                'total_paid' => $paidAmount,
            ]);
        }
    }
}
