<?php

namespace App\Http\Controllers;

use App\Models\Course;
use App\Models\CourseEnrollment;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class CourseEnrollmentController extends Controller
{
    public function __construct()
    {
        $this->middleware('permission:course_enrollments view',   ['only' => ['index']]);
        $this->middleware('permission:course_enrollments update', ['only' => ['edit','update']]);
        $this->middleware('permission:course_enrollments create', ['only' => ['create','store']]);
        $this->middleware('permission:course_enrollments delete', ['only' => ['destroy']]);
    }

    /**
     * Master Admin: all enrollments
     * Teacher: only enrollments of their courses (students -> only name + id on blade)
     * Student: only own enrollments
     */
    public function index()
{
    $user = Auth::user();

    $query = CourseEnrollment::with([
        'course.category',
        'course.teacher',
        'student'
    ])->latest();

    // 👨‍🏫 Teacher → Only own course enrollments
    if ($user->hasRole('teacher')) {
        $query->whereHas('course', function ($q) use ($user) {
            $q->where('teacher_id', $user->id);
        });
    }

    // 🎓 Student → Only own enrollment
    elseif ($user->hasRole('student')) {
        $query->where('student_id', $user->id);
    }

    // 🧑‍💼 Master Admin → No filter (see all)
    // No condition needed (full access)

    $enrollments = $query->get();

    audit_log(
        'course_enrollments',
        null,
        'listed',
        'Course enrollments listed',
        ['count' => $enrollments->count()]
    );

    return view('course_enrollments.index', compact('enrollments'));
}

    /**
     * Student: enroll form (only course list)
     * Master Admin: can choose course + student
     * Teacher: normally not needed, but kept if you want teacher to enroll a student
     */
public function create()
{
    $user = Auth::user();

    // ❌ Teacher ko enroll create allow nahi (proposal ke hisaab se)
    // if ($user->hasRole('teacher')) {
    //     abort(403);
    // }

    // ✅ Approved Courses
    $coursesQuery = Course::with('category')
        ->where('status', 'approved')
        ->latest();

    // (Optional) Agar kabhi teacher ko allow karein to:
    // if ($user->hasRole('teacher')) {
    //     $coursesQuery->where('teacher_id', $user->id);
    // }

    $courses = $coursesQuery->get();

    // ✅ Students (Spatie role based)
    $students = collect();

    if ($user->hasRole('master-admin')) {
        $students = User::role('student')   // 👈 Spatie role filter
            ->select('id', 'name')          // Proposal: email hidden
            ->latest()
            ->get();
    }

    return view('course_enrollments.create', compact('courses', 'students'));
}

    /**
     * Student: self-enroll (student_id = auth user)
     * Master Admin: enroll any student
     */
public function store(Request $request)
{
    $user = Auth::user();

    // ❌ Teacher not allowed
    if ($user->hasRole('teacher')) {
        abort(403);
    }

    $data = $request->validate([
        'course_id'  => 'required|exists:courses,id',
        'student_id' => 'nullable|exists:users,id',
    ]);

    // 🎓 Student → self enroll only
    if ($user->hasRole('student')) {
        $data['student_id'] = $user->id;
    }

    // 🧑‍💼 Master Admin → must select student
    if ($user->hasRole('master admin') && empty($data['student_id'])) {
        return back()->withErrors([
            'student_id' => 'Please select a student.'
        ])->withInput();
    }

    // 🚫 Duplicate check
    $exists = CourseEnrollment::where('course_id', $data['course_id'])
        ->where('student_id', $data['student_id'])
        ->exists();

    if ($exists) {
        return back()->with('error', 'Already enrolled.')->withInput();
    }

    CourseEnrollment::create($data);

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

    /**
     * Master Admin: can delete any
     * Teacher: only enrollments of their courses
     * Student: normally not allowed (permission not given)
     */

public function edit(CourseEnrollment $course_enrollment)
{
    $user = Auth::user();

    // ❌ Teacher cannot edit
    if ($user->hasRole('teacher')) {
        abort(403);
    }

    // 🎓 Student can only edit own enrollment
    if ($user->hasRole('student') && $course_enrollment->student_id !== $user->id) {
        abort(403);
    }

    // 🧑‍💼 Master Admin can edit any (no restriction)

    $courses = Course::with('category')
        ->where('status', 'approved')
        ->latest()
        ->get();

    $students = collect();

    // Only Master Admin sees student dropdown
    if ($user->hasRole('master-admin')) {
        $students = User::role('student')
            ->select('id', 'name')
            ->latest()
            ->get();
    }

    return view('course_enrollments.edit', compact(
        'course_enrollment',
        'courses',
        'students'
    ));
}


public function update(Request $request, CourseEnrollment $course_enrollment)
{
    $user = Auth::user();

    // ❌ Teacher not allowed
    if ($user->hasRole('teacher')) {
        abort(403);
    }

    $data = $request->validate([
        'course_id'  => 'required|exists:courses,id',
        'student_id' => 'nullable|exists:users,id',
    ]);

    // 🎓 Student → can only update own enrollment
    if ($user->hasRole('student')) {

        if ($course_enrollment->student_id !== $user->id) {
            abort(403);
        }

        $data['student_id'] = $user->id;
    }

    // 🧑‍💼 Master Admin → must select student
    if ($user->hasRole('master admin') && empty($data['student_id'])) {
        return back()->withErrors([
            'student_id' => 'Please select a student.'
        ])->withInput();
    }

    // 🚫 Prevent duplicate (except current)
    $exists = CourseEnrollment::where('course_id', $data['course_id'])
        ->where('student_id', $data['student_id'])
        ->where('id', '!=', $course_enrollment->id)
        ->exists();

    if ($exists) {
        return back()->with('error', 'Already enrolled.')->withInput();
    }

    $course_enrollment->update($data);

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


public function destroy(CourseEnrollment $courseEnrollment)
{
    $user = Auth::user();

    if ($user->hasRole('teacher')) {
        $courseEnrollment->load('course');
        abort_unless($courseEnrollment->course->teacher_id === $user->id, 403);
    }

    audit_log(
        'course_enrollments',
        $courseEnrollment->id,
        'deleted',
        'Enrollment deleted successfully',
        $courseEnrollment->toArray()
    );

    $courseEnrollment->delete();

    return back()->with('success', 'Enrollment deleted successfully.');
}
}