<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Enrollment;
use App\Models\Course;
use App\Models\CourseOffering;
use App\Models\User;
use Illuminate\Http\Request;

class EnrollmentController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware(['auth', 'role:admin']);
    }

    /**
     * Display a listing of enrollments.
     *
     * @return \Illuminate\View\View
     */
    public function index(Request $request)
    {
        $query = Enrollment::with(['student', 'course', 'courseOffering']);

        // Search functionality
        if ($request->has('search') && $request->search) {
            $search = $request->search;
            $query->whereHas('student', function($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('school_id', 'like', "%{$search}%");
            })->orWhereHas('course', function($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('code', 'like', "%{$search}%");
            });
        }

        // Filter by status
        if ($request->has('status') && $request->status !== '') {
            $query->where('status', $request->status);
        }

        // Filter by course
        if ($request->has('course_id') && $request->course_id) {
            $query->where('course_id', $request->course_id);
        }

        // Filter by course offering
        if ($request->has('course_offering_id') && $request->course_offering_id) {
            $query->where('course_offering_id', $request->course_offering_id);
        }

        $enrollments = $query->orderBy('enrollment_date', 'desc')->paginate(20);
        $courses = Course::where('is_active', true)->orderBy('name')->get();
        $offerings = CourseOffering::orderBy('start_date', 'desc')->get();

        return view('admin.enrollments.index', compact('enrollments', 'courses', 'offerings'));
    }

    /**
     * Show the form for creating a new enrollment.
     *
     * @return \Illuminate\View\View
     */
    public function create()
    {
        $students = User::where('role', 'student')->orderBy('name')->get();
        $courses = Course::where('is_active', true)->orderBy('name')->get();
        $offerings = CourseOffering::where('status', '!=', 'cancelled')->orderBy('start_date', 'desc')->get();
        return view('admin.enrollments.create', compact('students', 'courses', 'offerings'));
    }

    /**
     * Store a newly created enrollment.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'student_id' => 'required|exists:users,id',
            'course_id' => 'required|exists:courses,id',
            'course_offering_id' => 'nullable|exists:course_offerings,id',
            'enrollment_date' => 'required|date',
            'status' => 'nullable|in:active,inactive,completed,withdrawn',
        ]);

        // Check if enrollment already exists
        $existing = Enrollment::where('student_id', $validated['student_id'])
            ->where('course_id', $validated['course_id'])
            ->where('course_offering_id', $validated['course_offering_id'] ?? null)
            ->first();

        if ($existing) {
            return back()->withInput()->withErrors(['student_id' => 'Student is already enrolled in this course/offering.']);
        }

        Enrollment::create([
            'student_id' => $validated['student_id'],
            'course_id' => $validated['course_id'],
            'course_offering_id' => $validated['course_offering_id'] ?? null,
            'enrollment_date' => $validated['enrollment_date'],
            'status' => $validated['status'] ?? 'active',
        ]);

        // Update course offering student count if applicable
        if ($validated['course_offering_id']) {
            $offering = CourseOffering::find($validated['course_offering_id']);
            if ($offering) {
                $offering->increment('current_students');
            }
        }

        return redirect()->route('admin.enrollments.index')
            ->with('success', 'Enrollment created successfully!');
    }

    /**
     * Display the specified enrollment.
     *
     * @param  int  $id
     * @return \Illuminate\View\View
     */
    public function show($id)
    {
        $enrollment = Enrollment::with(['student', 'course', 'courseOffering'])->findOrFail($id);
        return view('admin.enrollments.show', compact('enrollment'));
    }

    /**
     * Show the form for editing the specified enrollment.
     *
     * @param  int  $id
     * @return \Illuminate\View\View
     */
    public function edit($id)
    {
        $enrollment = Enrollment::findOrFail($id);
        $students = User::where('role', 'student')->orderBy('name')->get();
        $courses = Course::where('is_active', true)->orderBy('name')->get();
        $offerings = CourseOffering::where('status', '!=', 'cancelled')->orderBy('start_date', 'desc')->get();
        return view('admin.enrollments.edit', compact('enrollment', 'students', 'courses', 'offerings'));
    }

    /**
     * Update the specified enrollment.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(Request $request, $id)
    {
        $enrollment = Enrollment::findOrFail($id);
        $oldOfferingId = $enrollment->course_offering_id;

        $validated = $request->validate([
            'student_id' => 'required|exists:users,id',
            'course_id' => 'required|exists:courses,id',
            'course_offering_id' => 'nullable|exists:course_offerings,id',
            'enrollment_date' => 'required|date',
            'status' => 'nullable|in:active,inactive,completed,withdrawn',
        ]);

        $enrollment->update($validated);

        // Update course offering student counts
        if ($oldOfferingId != ($validated['course_offering_id'] ?? null)) {
            if ($oldOfferingId) {
                $oldOffering = CourseOffering::find($oldOfferingId);
                if ($oldOffering && $oldOffering->current_students > 0) {
                    $oldOffering->decrement('current_students');
                }
            }
            if ($validated['course_offering_id']) {
                $newOffering = CourseOffering::find($validated['course_offering_id']);
                if ($newOffering) {
                    $newOffering->increment('current_students');
                }
            }
        }

        return redirect()->route('admin.enrollments.index')
            ->with('success', 'Enrollment updated successfully!');
    }

    /**
     * Remove the specified enrollment.
     *
     * @param  int  $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function destroy($id)
    {
        $enrollment = Enrollment::findOrFail($id);
        $offeringId = $enrollment->course_offering_id;
        $enrollment->delete();

        // Update course offering student count
        if ($offeringId) {
            $offering = CourseOffering::find($offeringId);
            if ($offering && $offering->current_students > 0) {
                $offering->decrement('current_students');
            }
        }

        return redirect()->route('admin.enrollments.index')
            ->with('success', 'Enrollment deleted successfully!');
    }
}

