<?php

namespace App\Services;

use App\Models\Quiz;
use App\Models\QuizInvitation;
use App\Notifications\QuizInvitationNotification;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Log;

class QuizInvitationService
{
    /**
     * Send invitations to multiple emails
     */
    public function sendInvitations(Quiz $quiz, array $emails, string $customMessage = ''): array
    {
        $results = [
            'success' => [],
            'errors' => [],
            'duplicates' => []
        ];

        foreach ($emails as $email) {
            try {
                // Check if invitation already exists
                $existingInvitation = QuizInvitation::where('quiz_id', $quiz->id)
                    ->where('email', $email)
                    ->first();

                if ($existingInvitation) {
                    $results['duplicates'][] = $email;
                    continue;
                }

                // Create invitation
                $invitation = QuizInvitation::create([
                    'quiz_id' => $quiz->id,
                    'email' => $email,
                    'message' => $customMessage,
                    'status' => QuizInvitation::STATUS_PENDING,
                ]);

                // Send notification
                Notification::route('mail', $email)
                    ->notify(new QuizInvitationNotification($quiz, $invitation, $customMessage));

                // Mark as sent
                $invitation->markAsSent();

                $results['success'][] = $email;

                Log::info("Quiz invitation sent successfully", [
                    'quiz_id' => $quiz->id,
                    'email' => $email,
                    'invitation_id' => $invitation->id
                ]);

            } catch (\Exception $e) {
                $results['errors'][] = [
                    'email' => $email,
                    'error' => $e->getMessage()
                ];

                Log::error("Failed to send quiz invitation", [
                    'quiz_id' => $quiz->id,
                    'email' => $email,
                    'error' => $e->getMessage()
                ]);
            }
        }

        return $results;
    }

    /**
     * Resend invitation
     */
    public function resendInvitation(QuizInvitation $invitation): bool
    {
        try {
            Notification::route('mail', $invitation->email)
                ->notify(new QuizInvitationNotification($invitation->quiz, $invitation, $invitation->message));

            $invitation->markAsSent();

            Log::info("Quiz invitation resent successfully", [
                'invitation_id' => $invitation->id,
                'email' => $invitation->email
            ]);

            return true;

        } catch (\Exception $e) {
            Log::error("Failed to resend quiz invitation", [
                'invitation_id' => $invitation->id,
                'email' => $invitation->email,
                'error' => $e->getMessage()
            ]);

            return false;
        }
    }

    /**
     * Get invitation statistics
     */
    public function getInvitationStats(Quiz $quiz): array
    {
        $invitations = $quiz->invitations();

        return [
            'total' => $invitations->count(),
            'pending' => $invitations->pending()->count(),
            'sent' => $invitations->sent()->count(),
            'opened' => $invitations->opened()->count(),
            'completed' => $invitations->completed()->count(),
        ];
    }

    /**
     * Get invitation by token
     */
    public function getInvitationByToken(string $token): ?QuizInvitation
    {
        return QuizInvitation::where('token', $token)->first();
    }

    /**
     * Validate invitation
     */
    public function validateInvitation(QuizInvitation $invitation): array
    {
        $errors = [];

        if ($invitation->isExpired()) {
            $errors[] = 'This invitation has expired.';
        }

        if ($invitation->status === QuizInvitation::STATUS_COMPLETED) {
            $errors[] = 'This quiz has already been completed.';
        }

        if (!$invitation->quiz->is_published) {
            $errors[] = 'This quiz is not available.';
        }

        if ($invitation->quiz->is_expired) {
            $errors[] = 'This quiz has expired.';
        }

        return $errors;
    }

    /**
     * Mark invitation as opened
     */
    public function markAsOpened(QuizInvitation $invitation): void
    {
        $invitation->markAsOpened();
    }

    /**
     * Mark invitation as completed
     */
    public function markAsCompleted(QuizInvitation $invitation): void
    {
        $invitation->markAsCompleted();
    }

    /**
     * Delete invitation
     */
    public function deleteInvitation(QuizInvitation $invitation): bool
    {
        try {
            $invitation->delete();
            return true;
        } catch (\Exception $e) {
            Log::error("Failed to delete quiz invitation", [
                'invitation_id' => $invitation->id,
                'error' => $e->getMessage()
            ]);
            return false;
        }
    }

    /**
     * Bulk delete invitations
     */
    public function bulkDeleteInvitations(array $invitationIds): array
    {
        $results = [
            'success' => 0,
            'errors' => []
        ];

        foreach ($invitationIds as $invitationId) {
            try {
                $invitation = QuizInvitation::findOrFail($invitationId);
                $invitation->delete();
                $results['success']++;
            } catch (\Exception $e) {
                $results['errors'][] = [
                    'id' => $invitationId,
                    'error' => $e->getMessage()
                ];
            }
        }

        return $results;
    }
}


