<?php

namespace App\Http\Controllers\Admin;

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

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

    /**
     * Display a listing of course offerings.
     *
     * @return \Illuminate\View\View
     */
    public function index(Request $request)
    {
        $query = CourseOffering::with('course');

        // Search functionality
        if ($request->has('search') && $request->search) {
            $search = $request->search;
            $query->where(function($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhereHas('course', function($courseQuery) use ($search) {
                      $courseQuery->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);
        }

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

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

    /**
     * Show the form for creating a new course offering.
     *
     * @return \Illuminate\View\View
     */
    public function create()
    {
        $courses = Course::where('is_active', true)->orderBy('name')->get();
        return view('admin.course-offerings.create', compact('courses'));
    }

    /**
     * Store a newly created course offering.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'course_id' => 'required|exists:courses,id',
            'name' => 'required|string|max:255',
            'start_date' => 'required|date',
            'end_date' => 'required|date|after:start_date',
            'enrollment_start_date' => 'required|date',
            'enrollment_end_date' => 'required|date|after:enrollment_start_date',
            'max_students' => 'nullable|integer|min:0',
            'status' => 'nullable|in:upcoming,active,completed,cancelled',
        ]);

        CourseOffering::create([
            'course_id' => $validated['course_id'],
            'name' => $validated['name'],
            'start_date' => $validated['start_date'],
            'end_date' => $validated['end_date'],
            'enrollment_start_date' => $validated['enrollment_start_date'],
            'enrollment_end_date' => $validated['enrollment_end_date'],
            'max_students' => $validated['max_students'] ?? 0,
            'current_students' => 0,
            'status' => $validated['status'] ?? 'upcoming',
        ]);

        return redirect()->route('admin.course-offerings.index')
            ->with('success', 'Course offering created successfully!');
    }

    /**
     * Display the specified course offering.
     *
     * @param  int  $id
     * @return \Illuminate\View\View
     */
    public function show($id)
    {
        $offering = CourseOffering::with(['course', 'enrollments.student'])->findOrFail($id);
        $enrollments = $offering->enrollments()->with('student')->get();
        
        // Calculate fees summary
        $totalFees = 0;
        $paidFees = 0;
        $studentFeesData = [];
        
        foreach ($enrollments as $enrollment) {
            if ($enrollment->student && $enrollment->course) {
                $courseFee = $enrollment->course->fees;
                $totalFees += $courseFee;
                
                // Get payments for this student and offering
                $payments = FeePayment::where('student_id', $enrollment->student_id)
                    ->where('course_offering_id', $offering->id)
                    ->sum('amount');
                
                $paidFees += $payments;
                
                $studentFeesData[$enrollment->student_id] = [
                    'student' => $enrollment->student,
                    'course_fee' => $courseFee,
                    'paid' => $payments,
                    'balance' => $courseFee - $payments,
                    'enrollment' => $enrollment,
                ];
            }
        }
        
        // Get all fee payments for this offering
        $feePayments = FeePayment::where('course_offering_id', $offering->id)
            ->with(['student', 'recordedBy'])
            ->orderBy('payment_date', 'desc')
            ->paginate(20);
        
        return view('admin.course-offerings.show', compact('offering', 'enrollments', 'totalFees', 'paidFees', 'studentFeesData', 'feePayments'));
    }

    /**
     * Show the form for editing the specified course offering.
     *
     * @param  int  $id
     * @return \Illuminate\View\View
     */
    public function edit($id)
    {
        $offering = CourseOffering::findOrFail($id);
        $courses = Course::where('is_active', true)->orderBy('name')->get();
        return view('admin.course-offerings.edit', compact('offering', 'courses'));
    }

    /**
     * Update the specified course offering.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(Request $request, $id)
    {
        $offering = CourseOffering::findOrFail($id);

        $validated = $request->validate([
            'course_id' => 'required|exists:courses,id',
            'name' => 'required|string|max:255',
            'start_date' => 'required|date',
            'end_date' => 'required|date|after:start_date',
            'enrollment_start_date' => 'required|date',
            'enrollment_end_date' => 'required|date|after:enrollment_start_date',
            'max_students' => 'nullable|integer|min:0',
            'status' => 'nullable|in:upcoming,active,completed,cancelled',
        ]);

        $offering->update($validated);

        return redirect()->route('admin.course-offerings.index')
            ->with('success', 'Course offering updated successfully!');
    }

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

        return redirect()->route('admin.course-offerings.index')
            ->with('success', 'Course offering deleted successfully!');
    }
}

