<?php

namespace App\Jobs;

use App\Models\Order;
use App\Services\MailjetService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\View;

class SendInvoiceEmail implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public int $tries = 3;
    public int $backoff = 60;

    public function __construct(
        public Order $order,
        public string $invoicePath
    ) {}

    public function handle(MailjetService $mailjetService): void
    {
        try {
            // Render the email view with proper view isolation
            // Use ViewNotFoundException handling for nested views
            try {
                $htmlContent = View::make('emails.invoice', [
                    'order' => $this->order,
                    'invoiceNumber' => $this->order->order_number,
                ])->render();
            } catch (\InvalidArgumentException $e) {
                // If the mail::message namespace isn't available, render without it
                // This is a fallback for when the mail views aren't published
                Log::warning('Mail views not published, using basic HTML template', [
                    'order_id' => $this->order->id,
                ]);
                $htmlContent = $this->getBasicInvoiceHtml();
            }

            // Get customer name (fallback to email if name not available)
            $customerName = $this->order->customer_name ?? explode('@', $this->order->customer_email)[0];

            // Send via Mailjet
            $success = $mailjetService->send(
                toEmail: $this->order->customer_email,
                toName: $customerName,
                subject: 'Invoice #' . $this->order->order_number . ' - ADDITIONAL DESIGN',
                htmlContent: $htmlContent,
                attachments: [$this->invoicePath]
            );

            if (!$success) {
                throw new \Exception('Mailjet send returned false');
            }

            Log::info('Invoice email sent successfully via Mailjet', [
                'order_id' => $this->order->id,
                'order_number' => $this->order->order_number,
                'customer_email' => $this->order->customer_email,
            ]);
        } catch (\Exception $e) {
            Log::error('Failed to send invoice email via Mailjet', [
                'order_id' => $this->order->id,
                'order_number' => $this->order->order_number,
                'customer_email' => $this->order->customer_email,
                'error' => $e->getMessage(),
                'attempt' => $this->attempts(),
            ]);

            // Re-throw to trigger queue retry mechanism
            throw $e;
        }
    }

    /**
     * Fallback basic HTML template for invoice email
     */
    private function getBasicInvoiceHtml(): string
    {
        return <<<HTML
        <html>
            <head>
                <style>
                    body { font-family: Arial, sans-serif; color: #333; }
                    .header { background-color: #f5f5f5; padding: 20px; text-align: center; }
                    .content { padding: 20px; }
                    .footer { background-color: #f5f5f5; padding: 20px; text-align: center; font-size: 12px; }
                    table { width: 100%; border-collapse: collapse; margin: 20px 0; }
                    th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
                    th { background-color: #f5f5f5; }
                </style>
            </head>
            <body>
                <div class="header">
                    <h1>Invoice #{$this->order->order_number}</h1>
                </div>
                <div class="content">
                    <p>Dear {$this->order->customer_name ?: 'Customer'},</p>
                    <p>Please find your invoice attached to this email.</p>
                    <h3>Order Details</h3>
                    <table>
                        <tr>
                            <th>Order Number</th>
                            <td>{$this->order->order_number}</td>
                        </tr>
                        <tr>
                            <th>Order Date</th>
                            <td>{$this->order->created_at->format('d M Y')}</td>
                        </tr>
                        <tr>
                            <th>Total Amount</th>
                            <td>R {$this->order->total}</td>
                        </tr>
                    </table>
                    <p>Thank you for your order!</p>
                </div>
                <div class="footer">
                    <p>&copy; 2025 ADDITIONAL DESIGN. All rights reserved.</p>
                </div>
            </body>
        </html>
        HTML;
    }

    public function failed(\Throwable $exception): void
    {
        Log::critical('Invoice email job failed permanently after all retries', [
            'order_id' => $this->order->id,
            'order_number' => $this->order->order_number,
            'customer_email' => $this->order->customer_email,
            'error' => $exception->getMessage(),
        ]);
    }
}
