<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Student;
use App\Models\Course;
use App\Models\StudentCourse;
use Inertia\Inertia;

class StudentCourseController extends Controller
{


    public function index(Student $student)
    {
        $student->load(['courses' => function($query) {
            $query->withPivot(['payment_status', 'is_certified', 'enrollment_date', 'certification_date', 'certificate_number']);
        }]);
        
        $availableCourses = Course::where('is_active', true)
                                 ->whereNotIn('id', $student->courses->pluck('id'))
                                 ->get();

        return Inertia::render('Admin/StudentCourses', [
            'student' => $student,
            'availableCourses' => $availableCourses
        ]);
    }

    public function store(Request $request, Student $student)
    {
        $validated = $request->validate([
            'course_id' => 'required|exists:courses,id',
            'payment_status' => 'required|in:pending,paid,overdue',
            'enrollment_date' => 'required|date',
        ]);

        StudentCourse::create([
            'student_id' => $student->id,
            'course_id' => $validated['course_id'],
            'payment_status' => $validated['payment_status'],
            'enrollment_date' => $validated['enrollment_date'],
        ]);

        return redirect()->route('admin.student.courses', $student->id)
                        ->with('success', 'Course enrolled successfully!');
    }

    public function update(Request $request, Student $student, Course $course)
    {
        $validated = $request->validate([
            'is_certified' => 'boolean',
        ]);

        $studentCourse = StudentCourse::where('student_id', $student->id)
                                    ->where('course_id', $course->id)
                                    ->firstOrFail();

        // Only allow certification status updates, not payment status
        $studentCourse->update($validated);

        return redirect()->route('admin.student.courses', $student->id)
                        ->with('success', 'Course updated successfully!');
    }

    public function destroy(Student $student, Course $course)
    {
        StudentCourse::where('student_id', $student->id)
                    ->where('course_id', $course->id)
                    ->delete();

        return redirect()->route('admin.student.courses', $student->id)
                        ->with('success', 'Course enrollment removed!');
    }
}
