<?php

namespace App\Notifications;

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

class QuizInvitationNotification extends Notification
{
    use Queueable;

    public function __construct(
        public Quiz $quiz,
        public QuizInvitation $invitation,
        public string $customMessage = ''
    ) {
        //
    }

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

    /**
     * Get the mail representation of the notification.
     */
    public function toMail(object $notifiable): MailMessage
    {
        $quizUrl = $this->invitation->quiz_url;
        $companyName = Setting::where('key', 'company_name')->value('value') ?? 'Quiz Platform';
        $quizTitle = $this->quiz->title;
        $quizDescription = $this->quiz->description;
        $duration = $this->quiz->duration_minutes ? $this->quiz->duration_minutes . ' minutes' : 'No time limit';
        $totalQuestions = $this->quiz->total_questions;
        $totalPoints = $this->quiz->total_points;

        $mailMessage = (new MailMessage)
            ->subject("You're invited to take a quiz: {$quizTitle}")
            ->greeting("Hello!")
            ->line("You've been invited to take a quiz by {$companyName}.")
            ->line("**Quiz Details:**")
            ->line("• **Title:** {$quizTitle}")
            ->line("• **Description:** {$quizDescription}")
            ->line("• **Duration:** {$duration}")
            ->line("• **Questions:** {$totalQuestions}")
            ->line("• **Total Points:** {$totalPoints}");

        if ($this->customMessage) {
            $mailMessage->line("**Personal Message:**")
                       ->line($this->customMessage);
        }

        $mailMessage->line("Click the button below to start the quiz. You'll need to register or login before taking the quiz.")
                   ->action('Take Quiz', $quizUrl)
                   ->line("This invitation is valid for 30 days.")
                   ->line("If you have any questions, please contact us.")
                   ->salutation("Best regards,\nThe {$companyName} Team");

        return $mailMessage;
    }

    /**
     * Get the array representation of the notification.
     */
    public function toArray(object $notifiable): array
    {
        return [
            'quiz_id' => $this->quiz->id,
            'quiz_title' => $this->quiz->title,
            'invitation_id' => $this->invitation->id,
            'quiz_url' => $this->invitation->quiz_url,
        ];
    }
}
