<?php

namespace App\Http\Controllers;

use App\Mail\RejectMessage;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\Course;
use Illuminate\Support\Facades\Mail;
use function Symfony\Component\Clock\now;

class RevisorController extends Controller
{
    public function index()
    {
        $user = Auth::user();
        if ($user->role_id != 4) {
            return redirect()->route('homePage');
        }
        $coursesToReview = Course::where('status', 'review')->with('owner')->get();
        return view('pages.revisor.index', compact('coursesToReview'));
    }

    public function course($id)
    {
        $user = Auth::user();
        if ($user->role_id != 4) {
            return redirect()->route('homePage');
        }

        // 1) Cargar el curso con todas sus relaciones necesarias
        $courseInfo = Course::with([
            'owner',
            'subcategory.category',
            'chapters' => function($query) {
                $query->orderBy('chapter_number');
            },
            'chapters.exercises' => function($query) {
                $query->orderBy('exercise_number');
            },
            'chapters.exercises.options' => function($query) {
                $query->orderBy('answer');
            }
        ])->findOrFail($id);

        // 2) Calcular estadísticas del curso
        $stats = [
            'total_chapters' => $courseInfo->chapters->count(),
            'total_exercises' => $courseInfo->chapters->sum(function($chapter) {
                return $chapter->exercises->count();
            }),
            'total_lessons' => $courseInfo->chapters->where('is_exam', false)->count(),
            'has_exam' => $courseInfo->chapters->where('is_exam', true)->count() > 0
        ];

        // 3) Preparar la información para la vista
        $courseData = [
            'course' => $courseInfo,
            'stats' => $stats,
            'chapters' => $courseInfo->chapters->map(function($chapter) {
                return [
                    'id' => $chapter->id,
                    'title' => $chapter->title,
                    'chapter_number' => $chapter->chapter_number,
                    'is_exam' => $chapter->is_exam,
                    'content' => $chapter->content,
                    'description' => $chapter->description,
                    'exercises' => $chapter->exercises->map(function($exercise) {
                        return [
                            'id' => $exercise->id,
                            'title' => $exercise->title,
                            'type' => $exercise->type,
                            'content' => $exercise->content,
                            'options' => $exercise->options->map(function($option) {
                                return [
                                    'id' => $option->id,
                                    'content' => $option->answer,
                                    'is_correct' => $option->is_correct
                                ];
                            })
                        ];
                    })
                ];
            })
        ];

        return view('pages.revisor.course', compact('courseData'));
    }

    public function approve($id) {
        $user = Auth::user();
        if ($user->role_id != 4) {
            return redirect()->route('homePage');
        }

        $course = Course::findOrFail($id);
        $course->status = 'published';
        $course->save();

        return redirect()->route('revisorPage')
            ->with('success', 'Course approved successfully')
            ->with('course_id', $course->id);
    }

    public function undo($id) {
        $user = Auth::user();
        if ($user->role_id != 4) {
            return redirect()->route('homePage');
        }

        $course = Course::findOrFail($id);
        $course->status = 'review';
        $course->published_date = now();
        $course->save();

        return redirect()->route('revisorPage')->with('success2', "Course {$course->title} successfully returned to draft.");

    }

    public function reject(Request $request, $id) {
        $request->validate([
            'message' => 'required|string|max:2000',
        ]);

        $course = Course::findOrFail($id);

        $userEmail = $course->owner->email;
        $userName = $course->owner->name;
        $courseTitle = $course->title;

        // Eliminar el dd() y enviar el correo
        Mail::to($userEmail)->send(new RejectMessage($userEmail, $userName, $request->message, $courseTitle));

        return redirect()->route('revisorPage')->with('success', 'Curso rechazado y notificación enviada al creador.');
    }
}
