<?php

namespace App\Http\Controllers\Public;

use App\Http\Controllers\Controller;
use App\Models\Quiz;
use App\Models\QuizInvitation;
use App\Models\QuizAttempt;
use App\Services\QuizInvitationService;
use App\Services\QuizService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class QuizController extends Controller
{
    protected $quizInvitationService;
    protected $quizService;

    public function __construct(QuizInvitationService $quizInvitationService, QuizService $quizService)
    {
        $this->quizInvitationService = $quizInvitationService;
        $this->quizService = $quizService;
    }

    /**
     * Test method to debug routing
     */
    public function test()
    {
        return response()->json([
            'message' => 'Quiz controller is working!',
            'timestamp' => now(),
            'routes' => [
                'quiz.public' => route('quiz.public', ['quiz' => 'test']),
                'quiz.attempt' => route('quiz.attempt', ['quiz' => 'test', 'token' => 'test-token']),
            ]
        ]);
    }

    /**
     * Show quiz information page (before attempting)
     */
    public function show($uniqueUrl)
    {
        $quiz = Quiz::where('unique_url', $uniqueUrl)->firstOrFail();
        
        if (!$quiz->is_published) {
            abort(404, 'Quiz not found');
        }

        if ($quiz->is_expired) {
            return view('public.quiz-expired', compact('quiz'));
        }

        return view('public.quiz-info', compact('quiz'));
    }

    /**
     * Show quiz attempt page (requires authentication and valid token)
     */
    public function attempt($uniqueUrl, $token)
    {
        \Log::info('Quiz attempt route hit', ['uniqueUrl' => $uniqueUrl, 'token' => $token]);
        
        $quiz = Quiz::where('unique_url', $uniqueUrl)->firstOrFail();
        $invitation = $this->quizInvitationService->getInvitationByToken($token);

        if (!$invitation || $invitation->quiz_id !== $quiz->id) {
            abort(404, 'Invalid invitation');
        }

        // Validate invitation
        $errors = $this->quizInvitationService->validateInvitation($invitation);
        if (!empty($errors)) {
            return view('public.quiz-error', compact('quiz', 'errors'));
        }

        // Check if user is authenticated
        if (!Auth::check()) {
            session(['quiz_attempt_url' => route('quiz.attempt', ['quiz' => $uniqueUrl, 'token' => $token])]);
            return redirect()->route('login')->with('error', 'Please login to take this quiz.');
        }

        // Check if user can attempt the quiz
        if (!$quiz->canBeAttemptedBy(Auth::user())) {
            return view('public.quiz-error', [
                'quiz' => $quiz,
                'errors' => ['You are not allowed to take this quiz.']
            ]);
        }

        // Check for existing in-progress attempt
        $existingAttempt = $quiz->getInProgressAttempt(Auth::user());
        if ($existingAttempt) {
            return view('public.quiz-resume', compact('quiz', 'existingAttempt'));
        }

        // Mark invitation as opened
        $this->quizInvitationService->markAsOpened($invitation);

        return view('public.quiz-attempt', compact('quiz', 'invitation'));
    }

    /**
     * Start a new quiz attempt
     */
    public function startAttempt(Request $request, $uniqueUrl, $token)
    {
        $quiz = Quiz::where('unique_url', $uniqueUrl)->firstOrFail();
        $invitation = $this->quizInvitationService->getInvitationByToken($token);

        if (!$invitation || $invitation->quiz_id !== $quiz->id) {
            abort(404, 'Invalid invitation');
        }

        if (!Auth::check()) {
            return redirect()->route('login')->with('error', 'Please login to take this quiz.');
        }

        // Validate invitation
        $errors = $this->quizInvitationService->validateInvitation($invitation);
        if (!empty($errors)) {
            return back()->withErrors($errors);
        }

        // Check if user can attempt the quiz
        if (!$quiz->canBeAttemptedBy(Auth::user())) {
            return back()->withErrors(['You are not allowed to take this quiz.']);
        }

        // Check for existing in-progress attempt
        $existingAttempt = $quiz->getInProgressAttempt(Auth::user());
        if ($existingAttempt) {
            return redirect()->route('quiz.attempt', ['quiz' => $uniqueUrl, 'token' => $token]);
        }

        try {
            // Create new attempt
            $attempt = $this->quizService->createAttempt($quiz, Auth::user(), [
                'invitation_id' => $invitation->id,
                'started_at' => now(),
            ]);

            return redirect()->route('quiz.attempt', ['quiz' => $uniqueUrl, 'token' => $token]);

        } catch (\Exception $e) {
            Log::error('Failed to start quiz attempt', [
                'quiz_id' => $quiz->id,
                'user_id' => Auth::id(),
                'error' => $e->getMessage()
            ]);

            return back()->withErrors(['Failed to start quiz. Please try again.']);
        }
    }

    /**
     * Submit quiz attempt
     */
    public function submitAttempt(Request $request, $uniqueUrl, $token)
    {
        $quiz = Quiz::where('unique_url', $uniqueUrl)->firstOrFail();
        $invitation = $this->quizInvitationService->getInvitationByToken($token);

        if (!$invitation || $invitation->quiz_id !== $quiz->id) {
            abort(404, 'Invalid invitation');
        }

        if (!Auth::check()) {
            return redirect()->route('login')->with('error', 'Please login to take this quiz.');
        }

        // Get current attempt
        $attempt = $quiz->getInProgressAttempt(Auth::user());
        if (!$attempt) {
            return back()->withErrors(['No active attempt found.']);
        }

        try {
            // Submit the attempt
            $result = $this->quizService->submitAttempt($attempt, $request->all());

            // Mark invitation as completed
            $this->quizInvitationService->markAsCompleted($invitation);

            return view('public.quiz-result', compact('quiz', 'attempt', 'result'));

        } catch (\Exception $e) {
            Log::error('Failed to submit quiz attempt', [
                'quiz_id' => $quiz->id,
                'attempt_id' => $attempt->id,
                'user_id' => Auth::id(),
                'error' => $e->getMessage()
            ]);

            return back()->withErrors(['Failed to submit quiz. Please try again.']);
        }
    }
}
