<?php

namespace App\Helpers;

use App\Jobs\SendEmailJob;
use App\Models\Client;
use App\Models\Invoice;
use App\Models\Order;
use App\Models\Setting;
use Illuminate\Support\Facades\Log;

class NotificationHelper
{
    /**
     * Send order confirmation email to client
     */
    public static function sendOrderConfirmation(Order $order)
    {
        try {
            $client = $order->client;
            $invoice = $order->invoice;

            if (! $client || ! $client->email) {
                Log::warning('Cannot send order confirmation: no client or email', [
                    'order_id' => $order->id,
                ]);

                return false;
            }

            // Check if order confirmation emails are enabled
            if (! Setting::getValue('enable_order_confirmation_emails', true)) {
                return false;
            }

            // Prepare merge fields for email template
            $mergeFields = [
                'firstname' => $client->first_name,
                'lastname' => $client->last_name,
                'clientname' => $client->first_name.' '.$client->last_name,
                'clientemail' => $client->email,
                'clientphone' => $client->phone ?? '',
                'clientcompany' => $client->company_name ?? '',
                'orderid' => $order->order_number,
                'ordernumber' => $order->order_number,
                'orderdate' => $order->created_at->format('d.m.Y H:i'),
                'ordertotal' => number_format($order->total, 2).' '.($order->currency->code ?? 'TRY'),
                'orderstatus' => $order->status,
                'orderurl' => $invoice ? route('store.payment.show', $invoice->id) : route('store.auth.dashboard'),
                'paymenturl' => $invoice ? route('store.payment.show', $invoice->id) : '',
                'clientareaurl' => route('store.auth.dashboard'),
            ];

            // Add invoice fields if available
            if ($invoice) {
                $mergeFields = array_merge($mergeFields, [
                    'invoiceid' => $invoice->invoice_number,
                    'invoicenumber' => $invoice->invoice_number,
                    'invoicedate' => $invoice->issued_at->format('d.m.Y'),
                    'invoiceduedate' => $invoice->due_date->format('d.m.Y'),
                    'invoicetotal' => number_format($invoice->total_amount, 2).' '.($invoice->currency->code ?? 'TRY'),
                    'invoicestatus' => $invoice->status,
                    'invoiceurl' => route('store.payment.show', $invoice->id),
                ]);
            }

            SendEmailJob::dispatch(
                'Order Confirmation',
                'order',
                $order->id,
                $mergeFields
            );

            Log::info('Order confirmation email dispatched', [
                'order_id' => $order->id,
                'client_email' => $client->email,
                'template' => 'Order Confirmation',
            ]);

            return true;

        } catch (\Exception $e) {
            Log::error('Failed to dispatch order confirmation email', [
                'order_id' => $order->id,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);

            return false;
        }
    }

    /**
     * Send payment confirmation email to client
     */
    public static function sendPaymentConfirmation(Order $order, Invoice $invoice)
    {
        try {
            $client = $order->client;

            if (! $client || ! $client->email) {
                Log::warning('Cannot send payment confirmation: no client or email', [
                    'order_id' => $order->id,
                    'invoice_id' => $invoice->id,
                ]);

                return false;
            }

            // Check if payment confirmation emails are enabled
            if (! Setting::getValue('enable_payment_confirmation_emails', true)) {
                return false;
            }

            // Prepare merge fields for email template
            $mergeFields = [
                'client_id' => $client->id,
                'client_name' => $client->first_name.' '.$client->last_name,
                'client_email' => $client->email,
                'client_phone' => $client->phone,
                'client_company' => $client->company_name ?? '',
                'order_id' => $order->id,
                'order_number' => $order->order_number,
                'order_date' => $order->created_at->format('d.m.Y H:i'),
                'order_total' => number_format($order->total, 2).' '.($order->currency->code ?? 'TRY'),
                'order_status' => $order->status,
                'invoice_id' => $invoice->id,
                'invoice_number' => $invoice->invoice_number,
                'invoice_date' => $invoice->issued_at->format('d.m.Y'),
                'invoice_due_date' => $invoice->due_date->format('d.m.Y'),
                'invoice_total' => number_format($invoice->total_amount, 2).' '.($invoice->currency->code ?? 'TRY'),
                'invoice_status' => $invoice->status,
                'client_area_url' => route('store.auth.dashboard'),
                'invoice_url' => route('store.payment.show', $invoice->id),
            ];

            SendEmailJob::dispatch(
                'Invoice Payment Confirmation',
                'invoice',
                $invoice->id,
                $mergeFields
            );

            Log::info('Payment confirmation email dispatched', [
                'order_id' => $order->id,
                'invoice_id' => $invoice->id,
                'client_email' => $client->email,
                'template' => 'Invoice Payment Confirmation',
            ]);

            return true;

        } catch (\Exception $e) {
            Log::error('Failed to dispatch payment confirmation email', [
                'order_id' => $order->id,
                'invoice_id' => $invoice->id,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);

            return false;
        }
    }

    /**
     * Send invoice reminder email to client
     */
    private static array $invoiceTemplateMap = [
        // PRC-624 — Title Case taksonomi (spec §2.2).
        'first' => 'Invoice Overdue First Reminder',
        'second' => 'Invoice Overdue Second Reminder',
        'third' => 'Invoice Overdue Third Reminder',
        'final' => 'Invoice Overdue Final Reminder',
    ];

    public static function sendInvoiceReminder(Invoice $invoice, string $reminderType = 'first', array $extraMergeFields = [])
    {
        try {
            $client = $invoice->client;

            if (!$client || !$client->email) {
                Log::warning('Cannot send invoice reminder: no client or email', [
                    'invoice_id' => $invoice->id,
                ]);

                return false;
            }

            if (!Setting::getValue('enable_invoice_reminder_emails', true)) {
                return false;
            }

            // Honour client group notification preference (VIP / protected groups can opt out)
            if ($client->group_id && $client->group
                && $client->group->getNotificationPreference('invoice_payment_reminder') === false) {
                return false;
            }

            $templateKey = self::$invoiceTemplateMap[$reminderType] ?? 'Invoice Overdue First Reminder';

            $mergeFields = array_merge([
                'REMINDER_TYPE' => $reminderType,
                'PAYMENT_URL' => route('store.payment.show', $invoice->id),
                'CLIENT_AREA_URL' => route('store.auth.dashboard'),
                'DAYS_OVERDUE' => (int) abs(now()->diffInDays($invoice->due_date)),
            ], $extraMergeFields);

            SendEmailJob::dispatch(
                $templateKey,
                'invoice',
                $invoice->id,
                $mergeFields
            );

            Log::info('Invoice reminder email dispatched', [
                'invoice_id' => $invoice->id,
                'reminder_type' => $reminderType,
                'template' => $templateKey,
                'client_email' => $client->email,
            ]);

            return true;

        } catch (\Exception $e) {
            Log::error('Failed to dispatch invoice reminder email', [
                'invoice_id' => $invoice->id,
                'reminder_type' => $reminderType,
                'error' => $e->getMessage(),
            ]);

            return false;
        }
    }

    /**
     * Send account welcome email to new client
     */
    public static function sendWelcomeEmail(Client $client, ?string $temporaryPassword = null)
    {
        try {
            if (! $client || ! $client->email) {
                Log::warning('Cannot send welcome email: no client or email', [
                    'client_id' => $client->id ?? null,
                ]);

                return false;
            }

            // Check if welcome emails are enabled
            if (! Setting::getValue('enable_welcome_emails', true)) {
                return false;
            }

            $mergeFields = [
                'temporary_password' => $temporaryPassword,
                'login_url' => route('store.auth.login'),
                'client_area_url' => route('store.auth.dashboard'),
                'support_url' => route('store.contact'),
            ];

            SendEmailJob::dispatch(
                'Client Welcome Email',
                'client',
                $client->id,
                $mergeFields
            );

            Log::info('Welcome email dispatched', [
                'client_id' => $client->id,
                'client_email' => $client->email,
            ]);

            return true;

        } catch (\Exception $e) {
            Log::error('Failed to dispatch welcome email', [
                'client_id' => $client->id ?? null,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);

            return false;
        }
    }

    /**
     * Send service activation email to client
     */
    public static function sendServiceActivationEmail(Order $order)
    {
        try {
            $client = $order->client;

            if (! $client || ! $client->email) {
                Log::warning('Cannot send service activation email: no client or email', [
                    'order_id' => $order->id,
                ]);

                return false;
            }

            // Check if service activation emails are enabled
            if (! Setting::getValue('enable_service_activation_emails', true)) {
                return false;
            }

            $mergeFields = [
                'client_area_url' => route('store.auth.dashboard'),
                'support_url' => route('store.contact'),
            ];

            SendEmailJob::dispatch(
                'Service Activation',
                'order',
                $order->id,
                $mergeFields
            );

            Log::info('Service activation email dispatched', [
                'order_id' => $order->id,
                'client_email' => $client->email,
            ]);

            return true;

        } catch (\Exception $e) {
            Log::error('Failed to dispatch service activation email', [
                'order_id' => $order->id,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);

            return false;
        }
    }

    // PRC-621 — sendAdminOrderNotification kaldırıldı (hiçbir çağıranı yoktu;
    // ölü tek-e-posta yolu). Yeni sipariş admin bildirimi artık (PRC-622)
    // OrderObserver::created → OrderCreated → config/communication_events.php
    // events köprüsü → CommunicationDispatcher → notifyAdmins('New Order Notification')
    // üzerinden çok-kanallı NotificationService ile gider.
}
