<?php

namespace App\Listeners;

use App\Events\InvoiceCreated;
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 SendInvoiceCreatedNotification implements ShouldQueue
{
    use InteractsWithQueue, ChecksNotificationPreference;

    protected InvoicePdfService $pdfService;

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

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

        if (! $invoice->client) {
            return;
        }

        // Check client group notification preference
        if (! $this->shouldSendNotification($invoice->client, 'invoice_created')) {
            return;
        }

        // Fatura PDF'i hazırla. PRC-421 — tmp disk write fail (permission,
        // disk space, vb.) olursa email tamamen iptal etmek yerine PDF
        // eksik şekilde göndermeye devam ediyoruz. Müşteri en azından
        // bildirim alır; admin error log ile root cause'u görür.
        $pdfAttachment = null;
        try {
            $pdfAttachment = $this->pdfService->prepareAttachment($invoice);
        } catch (\Throwable $e) {
            \Illuminate\Support\Facades\Log::error('Invoice PDF attachment skipped — email sent without PDF', [
                'invoice_id' => $invoice->id,
                'error' => $e->getMessage(),
            ]);
        }

        // Müşteriye fatura bildirimi gönder (Unified system ile)
        SendEmailJob::dispatch(
            'Invoice Created',
            'invoice',
            $invoice->id,
            null,
            null,
            null,
            $pdfAttachment ? [$pdfAttachment] : []
        );

        // PRC-376 — Admin notification via multi-channel NotificationService
        // (email + slack + telegram + discord + pushover + whatsapp + sms,
        // per `notification_channels_invoice_created` setting + per-admin
        // overrides). Drops the legacy single-email fallback.
        if (setting('notify_admin_on_invoice_created', false)) {
            app(NotificationService::class)->notifyAdmins(
                type: 'Admin Invoice Created Notification',
                subject: __('admin/billing.notify_admin_invoice_created_subject', ['number' => $invoice->invoice_number]),
                message: __('admin/billing.notify_admin_invoice_created_message', [
                    'number' => $invoice->invoice_number,
                    'client' => $invoice->client->first_name.' '.$invoice->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),
                ]
            );
        }
    }
}
