<?php

namespace Modules\Academic\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;
use Illuminate\Http\RedirectResponse;
use Modules\Academic\Models\Classroom;
use Modules\Academic\Models\AcademicYear;
use Modules\Academic\Models\Subject;
use Modules\Academic\Http\Requests\StoreClassroomRequest;
use Modules\Academic\Http\Requests\UpdateClassroomRequest;

class ClassroomController extends Controller
{
    public function __construct()
    {
        $this->authorizeResource(Classroom::class, 'classroom');
    }

    /**
     * Display a listing of the resource.
     */
    public function index(Request $request): Response
    {
        $query = Classroom::with(['academicYear', 'subjects']);

        // Filter by academic year if provided
        if ($request->filled('academic_year_id')) {
            $query->where('academic_year_id', $request->academic_year_id);
        }

        // Search by name
        if ($request->filled('search')) {
            $query->where('name', 'like', '%' . $request->search . '%');
        }

        $classrooms = $query->latest()->paginate(20);
        $academicYears = AcademicYear::orderBy('start_date', 'desc')->get();

        return Inertia::render('Academic/Classrooms/Index', [
            'classrooms' => $classrooms,
            'academicYears' => $academicYears,
            'filters' => [
                'academic_year_id' => $request->academic_year_id,
                'search' => $request->search,
            ],
        ]);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create(): Response
    {
        $academicYears = AcademicYear::where('is_active', true)->get();
        $subjects = Subject::where('is_active', true)->get();

        return Inertia::render('Academic/Classrooms/Create', [
            'academicYears' => $academicYears,
            'subjects' => $subjects,
        ]);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreClassroomRequest $request): RedirectResponse
    {
        $validated = $request->validated();
        
        $classroom = Classroom::create($validated);

        // Attach subjects if provided
        if (isset($validated['subject_ids'])) {
            $classroom->subjects()->attach($validated['subject_ids']);
        }

        return redirect()->route('classrooms.index')
            ->with('success', 'Classroom created successfully.');
    }

    /**
     * Display the specified resource.
     */
    public function show(Classroom $classroom): Response
    {
        $classroom->load([
            'academicYear',
            'subjects.teachers',
            'enrollments.student.user',
            'results.student.user',
            'results.subject'
        ]);

        // Get enrollment statistics
        $enrollmentStats = [
            'total_students' => $classroom->enrollments()->active()->count(),
            'male_students' => $classroom->enrollments()->active()
                ->whereHas('student', function ($query) {
                    $query->where('gender', 'male');
                })->count(),
            'female_students' => $classroom->enrollments()->active()
                ->whereHas('student', function ($query) {
                    $query->where('gender', 'female');
                })->count(),
        ];

        // Get recent results
        $recentResults = $classroom->results()
            ->with(['student.user', 'subject', 'examType'])
            ->latest('entered_at')
            ->limit(10)
            ->get();

        return Inertia::render('Academic/Classrooms/Show', [
            'classroom' => $classroom,
            'enrollmentStats' => $enrollmentStats,
            'recentResults' => $recentResults,
        ]);
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Classroom $classroom): Response
    {
        $classroom->load(['subjects']);
        $academicYears = AcademicYear::all();
        $subjects = Subject::where('is_active', true)->get();

        return Inertia::render('Academic/Classrooms/Edit', [
            'classroom' => $classroom,
            'academicYears' => $academicYears,
            'subjects' => $subjects,
        ]);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateClassroomRequest $request, Classroom $classroom): RedirectResponse
    {
        $validated = $request->validated();
        
        $classroom->update($validated);

        // Sync subjects if provided
        if (isset($validated['subject_ids'])) {
            $classroom->subjects()->sync($validated['subject_ids']);
        }

        return redirect()->route('classrooms.index')
            ->with('success', 'Classroom updated successfully.');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Classroom $classroom): RedirectResponse
    {
        // Check if classroom has active enrollments
        if ($classroom->enrollments()->active()->exists()) {
            return redirect()->back()
                ->with('error', 'Cannot delete classroom with active enrollments.');
        }

        // Check if classroom has results
        if ($classroom->results()->exists()) {
            return redirect()->back()
                ->with('error', 'Cannot delete classroom with existing results.');
        }

        $classroom->delete();

        return redirect()->route('classrooms.index')
            ->with('success', 'Classroom deleted successfully.');
    }

    /**
     * Assign subjects to classroom
     */
    public function assignSubjects(Request $request, Classroom $classroom): RedirectResponse
    {
        $this->authorize('update', $classroom);

        $request->validate([
            'subject_ids' => 'required|array',
            'subject_ids.*' => 'exists:subjects,id',
        ]);

        $classroom->subjects()->sync($request->subject_ids);

        return redirect()->back()
            ->with('success', 'Subjects assigned successfully.');
    }

    /**
     * Get classroom students for enrollment management
     */
    public function students(Classroom $classroom): Response
    {
        $this->authorize('view', $classroom);

        $enrollments = $classroom->enrollments()
            ->with(['student.user', 'student.guardians'])
            ->active()
            ->get();

        return Inertia::render('Academic/Classrooms/Students', [
            'classroom' => $classroom,
            'enrollments' => $enrollments,
        ]);
    }
}
