<?php

namespace App\Listeners;

use App\Events\InvoicePaid;
use App\Jobs\SendEmailJob;
use App\Services\InvoicePdfService;
use App\Services\NotificationService;
use App\Traits\ChecksNotificationPreference;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

class SendInvoicePaidNotification implements ShouldQueue
{
    use InteractsWithQueue, ChecksNotificationPreference;

    protected InvoicePdfService $pdfService;

    public function __construct(InvoicePdfService $pdfService)
    {
        $this->pdfService = $pdfService;
    }

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

        // PRC-407 — Previously called `EmailManager::sendInvoicePaidNotification`
        // which doesn't exist on EmailManager (would throw BadMethodCallException
        // at runtime). Replaced with the canonical SendEmailJob::dispatch path
        // (matches SendInvoiceCreatedNotification). Also adds the
        // ChecksNotificationPreference gate (PRC-404 D-005 follow-up) so the
        // three lifecycle listeners share the same client-opt-out semantics.
        if ($client && $this->shouldSendNotification($client, 'invoice_payment')) {
            // PRC-421 — tmp disk write fail (permission/full/etc.) durumunda
            // email tamamen iptal yerine PDF'siz gönderiyoruz.
            $pdfAttachment = null;
            try {
                $pdfAttachment = $this->pdfService->prepareAttachment($invoice);
            } catch (\Throwable $e) {
                \Illuminate\Support\Facades\Log::error('Invoice PDF attachment skipped — payment email sent without PDF', [
                    'invoice_id' => $invoice->id,
                    'error' => $e->getMessage(),
                ]);
            }

            SendEmailJob::dispatch(
                'Invoice Payment Confirmation',
                'invoice',
                $invoice->id,
                null,
                null,
                null,
                $pdfAttachment ? [$pdfAttachment] : []
            );
        }

        // PRC-376 — Admin notification via multi-channel NotificationService.
        if (setting('notify_admin_on_invoice_paid', false)) {
            app(NotificationService::class)->notifyAdmins(
                type: 'Admin Invoice Paid Notification',
                subject: __('admin/billing.notify_admin_invoice_paid_subject', ['number' => $invoice->invoice_number]),
                message: __('admin/billing.notify_admin_invoice_paid_message', [
                    'number' => $invoice->invoice_number,
                    'client' => $client->first_name.' '.$client->last_name,
                    'total' => number_format($invoice->total_amount, 2),
                ]),
                data: [
                    'entity_type' => 'invoice',
                    'entity_id' => $invoice->id,
                    'invoice_number' => $invoice->invoice_number,
                    'client_id' => $invoice->client_id,
                    'total' => $invoice->total_amount,
                    'url' => route('admin.invoices.show', $invoice->id),
                ]
            );
        }
    }
}
