<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class StudentRegistrationController extends Controller
{
    /**
     * Show the registration form with courses grouped by Level and Semester.
     */
    public function create()
    {
        $courses = DB::table('courses')
            ->select('course_code', 'course_description', 'credits', 'level', 'semester')
            ->orderBy('level')
            ->orderBy('semester')
            ->orderBy('course_code')
            ->get()
            ->groupBy(fn($c) => "{$c->level} - {$c->semester}");

        return view('student.registration', compact('courses'));
    }

    /**
     * Store selected courses for the logged-in student.
     */
    public function store(Request $request)
    {
        $request->validate([
            'semester' => 'required|string',   // e.g., "Level 1 - Semester 2"
            'courses'  => 'required|array|min:1',
        ]);

        foreach ($request->courses as $code) {
            DB::table('course_registrations')->updateOrInsert(
                [
                    'user_id'     => Auth::id(),
                    'course_code' => $code,
                ],
                [
                    'semester'   => $request->semester,
                    'created_at' => now(),
                    'updated_at' => now(),
                ]
            );
        }

        return redirect()
            ->route('student.courses')
            ->with('success', 'Courses registered successfully.');
    }

    /**
     * Display the currently registered courses for the student.
     */
    public function registeredCourses()
    {
        $registrations = DB::table('course_registrations')
            ->where('course_registrations.user_id', Auth::id())
            ->join('courses', 'courses.course_code', '=', 'course_registrations.course_code')
            ->select(
                'course_registrations.id',
                'courses.course_code',
                'courses.course_description',
                'courses.credits',
                'courses.level',
                'courses.semester'
            )
            ->orderBy('courses.level')
            ->orderBy('courses.semester')
            ->orderBy('courses.course_code')
            ->get();

        return view('student.courses', compact('registrations'));
    }

    /**
     * Deregister a single course and delete related coursework.
     */
    public function deregister($id)
    {
        $user = Auth::user();
        $registrationNumber = $user->registration_number ?? strtoupper($user->username);

        // 1. Look up course_code being deregistered
        $course = DB::table('course_registrations')
            ->where('id', $id)
            ->where('user_id', Auth::id())
            ->first();

        if (!$course) {
            return back()->with('error', 'Course not found.');
        }

        // 2. Delete coursework for this course
        DB::table('coursework')
            ->where('registration_number', $registrationNumber)
            ->where('course_code', $course->course_code)
            ->delete();

        // 3. Delete course registration
        DB::table('course_registrations')
            ->where('id', $id)
            ->where('user_id', Auth::id())
            ->delete();

        return back()->with('success', 'Course deregistered and related coursework deleted.');
    }
}
