<?php

namespace App\Notifications;

use App\Models\Invoice;
use App\Models\Setting;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Storage;

class InvoicePaid extends Notification implements ShouldQueue
{
    use Queueable;

    /**
     * Create a new notification instance.
     */
    public function __construct(
        public Invoice $invoice
    ) {}

    /**
     * Get the notification's delivery channels.
     *
     * @return array<int, string>
     */
    public function via(object $notifiable): array
    {
        return ['database', 'mail'];
    }

    /**
     * Get the mail representation of the notification.
     */
    public function toMail(object $notifiable): MailMessage
    {
        $siteName = Setting::get('site_name', 'CoachPro');
        $currency = Setting::get('currency', 'USD');
        
        $mail = (new MailMessage)
            ->subject("Pago Confirmado - Factura {$this->invoice->invoice_number}")
            ->greeting("¡Hola {$notifiable->name}!")
            ->line("Tu pago ha sido procesado exitosamente. Gracias por tu compra.")
            ->line('')
            ->line('**Detalles del Pago:**')
            ->line("Factura: {$this->invoice->invoice_number}")
            ->line("Subtotal: \${$this->invoice->subtotal} {$currency}")
            ->line("Impuestos: \${$this->invoice->tax} {$currency}")
            ->line("**Total Pagado: \${$this->invoice->total} {$currency}**")
            ->line("Método de Pago: " . $this->getPaymentMethodName())
            ->line("Fecha: " . $this->invoice->paid_at->format('d/m/Y H:i'))
            ->action('Ver Mi Suscripción', route('coach.subscription.index'))
            ->line("Tu suscripción ha sido activada correctamente.")
            ->salutation("Saludos,\nEl equipo de {$siteName}");

        // Attach PDF if exists
        if ($this->invoice->pdf_path && Storage::disk('public')->exists($this->invoice->pdf_path)) {
            $mail->attach(
                Storage::disk('public')->path($this->invoice->pdf_path),
                [
                    'as' => "Factura-{$this->invoice->invoice_number}.pdf",
                    'mime' => 'application/pdf',
                ]
            );
        }

        return $mail;
    }

    /**
     * Get the array representation of the notification.
     *
     * @return array<string, mixed>
     */
    public function toArray(object $notifiable): array
    {
        return [
            'type' => 'invoice_paid',
            'invoice_id' => $this->invoice->id,
            'invoice_number' => $this->invoice->invoice_number,
            'total' => $this->invoice->total,
            'payment_method' => $this->invoice->payment_method,
            'paid_at' => $this->invoice->paid_at,
            'message' => "✅ Pago confirmado: Factura {$this->invoice->invoice_number} por \${$this->invoice->total}",
            'title' => 'Pago confirmado',
            'url' => route('coach.subscription.invoices'),
        ];
    }

    /**
     * Get human-readable payment method name.
     */
    protected function getPaymentMethodName(): string
    {
        return match($this->invoice->payment_method) {
            'stripe' => 'Tarjeta de Crédito/Débito (Stripe)',
            'paypal' => 'PayPal',
            'bank_transfer' => 'Transferencia Bancaria',
            default => ucfirst($this->invoice->payment_method ?? 'Desconocido'),
        };
    }
}
