<?php

namespace App\Notifications;

use App\Models\CoachPlanPurchase;
use App\Models\Setting;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class CoachNewPlanPurchase extends Notification
{
    use Queueable;

    public function __construct(
        public CoachPlanPurchase $purchase,
        public string $eventType = 'new_purchase' // new_purchase, receipt_uploaded, paid, expired
    ) {}

    public function via($notifiable): array
    {
        return ['database', 'mail'];
    }

    public function toMail($notifiable): MailMessage
    {
        $siteName = Setting::get('site_name', 'CoachPro');
        $plan = $this->purchase->coachPlan;
        $clientName = $this->purchase->buyer_name ?? 'Cliente';
        $clientEmail = $this->purchase->buyer_email ?? '';
        $amount = number_format($this->purchase->amount, 2);
        $currency = $this->purchase->currency ?? 'DOP';

        return match ($this->eventType) {
            'receipt_uploaded' => (new MailMessage)
                ->subject("📎 Comprobante recibido - {$clientName}")
                ->greeting("¡Hola {$notifiable->name}!")
                ->line("Un cliente ha subido un comprobante de pago para tu plan.")
                ->line('')
                ->line("**Cliente:** {$clientName}")
                ->line("**Email:** {$clientEmail}")
                ->line("**Plan:** " . ($plan->name ?? 'N/A'))
                ->line("**Monto:** \${$amount} {$currency}")
                ->line('')
                ->line('Por favor revisa el comprobante y confirma el pago.')
                ->action('Revisar compra', url("/coach/my-plans/{$plan->id}"))
                ->salutation("Sistema de Notificaciones - {$siteName}"),

            'paid' => (new MailMessage)
                ->subject("✅ Pago confirmado - {$clientName}")
                ->greeting("¡Hola {$notifiable->name}!")
                ->line("Se ha confirmado el pago de un cliente para tu plan.")
                ->line('')
                ->line("**Cliente:** {$clientName}")
                ->line("**Plan:** " . ($plan->name ?? 'N/A'))
                ->line("**Monto:** \${$amount} {$currency}")
                ->line("**Válido hasta:** " . ($this->purchase->ends_at ? $this->purchase->ends_at->format('d/m/Y') : 'N/A'))
                ->line('')
                ->line('El cliente ya tiene acceso activo a tu plan.')
                ->action('Ver mis planes', url('/coach/my-plans'))
                ->salutation("Sistema de Notificaciones - {$siteName}"),

            'expired' => (new MailMessage)
                ->subject("⏰ Plan expirado - {$clientName}")
                ->greeting("¡Hola {$notifiable->name}!")
                ->line("El plan de un cliente ha expirado.")
                ->line('')
                ->line("**Cliente:** {$clientName}")
                ->line("**Plan:** " . ($plan->name ?? 'N/A'))
                ->line('')
                ->line('Puedes contactar al cliente para ofrecerle una renovación.')
                ->action('Ver mis planes', url('/coach/my-plans'))
                ->salutation("Sistema de Notificaciones - {$siteName}"),

            default => (new MailMessage)
                ->subject("🛒 Nueva compra pendiente - {$clientName}")
                ->greeting("¡Hola {$notifiable->name}!")
                ->line("¡Tienes una nueva compra pendiente de pago!")
                ->line('')
                ->line("**Cliente:** {$clientName}")
                ->line("**Email:** {$clientEmail}")
                ->line("**Plan:** " . ($plan->name ?? 'N/A'))
                ->line("**Monto:** \${$amount} {$currency}")
                ->line("**Método de pago:** " . $this->getPaymentMethodLabel())
                ->line('')
                ->line('El cliente recibirá las instrucciones de pago. Te notificaremos cuando suba el comprobante.')
                ->action('Ver compra', url("/coach/my-plans/{$plan->id}"))
                ->salutation("Sistema de Notificaciones - {$siteName}"),
        };
    }

    public function toArray($notifiable): array
    {
        $plan = $this->purchase->coachPlan;
        $clientName = $this->purchase->buyer_name ?? 'Cliente';

        $messages = [
            'new_purchase' => "🛒 Nueva compra pendiente de {$clientName} para el plan {$plan->name}",
            'receipt_uploaded' => "📎 {$clientName} subió un comprobante de pago para {$plan->name}",
            'paid' => "✅ Pago confirmado de {$clientName} para {$plan->name}",
            'expired' => "⏰ Plan {$plan->name} de {$clientName} ha expirado",
        ];

        return [
            'type' => 'coach_plan_' . $this->eventType,
            'purchase_id' => $this->purchase->id,
            'plan_id' => $this->purchase->coach_plan_id,
            'plan_name' => $plan->name ?? 'Plan',
            'client_name' => $clientName,
            'amount' => $this->purchase->amount,
            'status' => $this->purchase->status,
            'message' => $messages[$this->eventType] ?? $messages['new_purchase'],
        ];
    }

    private function getPaymentMethodLabel(): string
    {
        return match ($this->purchase->payment_method) {
            'paypal' => 'PayPal',
            'bank_dominican' => 'Transferencia bancaria (RD)',
            'bank_international' => 'Transferencia internacional',
            'western_union' => 'Western Union',
            default => $this->purchase->payment_method ?? 'No especificado',
        };
    }
}
