<?php

namespace App\Notifications;

use App\Models\Client;
use App\Models\EmailTemplate;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class ClientPortalActivated extends Notification implements ShouldQueue
{
    use Queueable;

    protected Client $client;
    protected string $password;
    protected string $coachName;

    /**
     * Create a new notification instance.
     */
    public function __construct(Client $client, string $password, string $coachName)
    {
        $this->client = $client;
        $this->password = $password;
        $this->coachName = $coachName;
    }

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

    /**
     * Get the mail representation of the notification.
     */
    public function toMail(object $notifiable): MailMessage
    {
        $appName = config('app.name', 'CoachPro');
        $loginUrl = url('/login');

        // Try to use email template first
        $template = EmailTemplate::getBySlug('client-portal-activated');

        if ($template) {
            $rendered = $template->render([
                'app_name' => $appName,
                'client_name' => $this->client->name,
                'coach_name' => $this->coachName,
                'email' => $notifiable->email,
                'password' => $this->password,
                'login_url' => $loginUrl,
            ]);

            return (new MailMessage)
                ->subject($rendered['subject'])
                ->view('emails.template', ['body' => $rendered['body']]);
        }

        // Fallback to default notification
        return (new MailMessage)
            ->subject("🎉 ¡Tu portal de cliente está activo! - {$appName}")
            ->greeting("¡Hola {$this->client->name}!")
            ->line("Tu entrenador **{$this->coachName}** ha activado tu acceso al portal de clientes.")
            ->line('---')
            ->line('**Tus credenciales de acceso:**')
            ->line("📧 **Email:** {$notifiable->email}")
            ->line("🔑 **Contraseña:** {$this->password}")
            ->line('---')
            ->line('**¿Qué puedes hacer en tu portal?**')
            ->line('✅ Ver tus rutinas de entrenamiento personalizadas')
            ->line('✅ Consultar tu plan de alimentación')
            ->line('✅ Registrar tu progreso y peso')
            ->line('✅ Subir fotos de tu transformación')
            ->line('✅ Comunicarte con tu entrenador')
            ->line('✅ Descargar tus planes en PDF')
            ->action('Acceder a mi Portal', $loginUrl)
            ->line('---')
            ->line('**Recomendaciones de seguridad:**')
            ->line('🔒 Te recomendamos cambiar tu contraseña después del primer inicio de sesión.')
            ->line('📱 Puedes instalar la aplicación en tu móvil para acceso rápido.')
            ->salutation("¡Éxito en tu transformación!\nEquipo {$appName}");
    }

    /**
     * Get the array representation of the notification.
     *
     * @return array<string, mixed>
     */
    public function toArray(object $notifiable): array
    {
        return [
            'client_id' => $this->client->id,
            'message' => 'Portal de cliente activado',
        ];
    }
}
