<?php

namespace App\Http\Controllers;

use App\Models\SchoolClass;
use App\Models\Teacher;
use App\Models\Classroom;
use Illuminate\Http\Request;

class SchoolClassController extends Controller
{
    public function index()
    {
        $classes = SchoolClass::with(['homeroomTeacher', 'classroom'])
            ->withCount('students')
            ->orderBy('grade_level')
            ->orderBy('name')
            ->paginate(20);

        $teachers   = Teacher::orderBy('name')->get();
        $classrooms = Classroom::orderBy('name')->get();

        return view('admin.classes.index', compact('classes', 'teachers', 'classrooms'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name'                 => 'required|string|max:20|unique:classes,name',
            'grade_level'          => 'required|integer|min:1|max:6',
            'homeroom_teacher_id'  => 'nullable|exists:teachers,id',
            'classroom_id'         => 'nullable|exists:classrooms,id',
            'capacity'             => 'nullable|integer|min:1',
        ]);

        SchoolClass::create($validated);

        return back()->with('success', 'Data kelas berhasil ditambahkan!');
    }

    public function edit(int $id)
    {
        $class      = SchoolClass::findOrFail($id);
        $teachers   = Teacher::orderBy('name')->get();
        $classrooms = Classroom::orderBy('name')->get();

        return view('admin.classes.edit', compact('class', 'teachers', 'classrooms'));
    }

    public function update(Request $request, int $id)
    {
        $class = SchoolClass::findOrFail($id);

        $validated = $request->validate([
            'name'                 => 'required|string|max:20|unique:classes,name,' . $class->id,
            'grade_level'          => 'required|integer|min:1|max:6',
            'homeroom_teacher_id'  => 'nullable|exists:teachers,id',
            'classroom_id'         => 'nullable|exists:classrooms,id',
            'capacity'             => 'nullable|integer|min:1',
        ]);

        $class->update($validated);

        return redirect()->route('classes.index')->with('success', 'Data kelas berhasil diperbarui!');
    }

    public function destroy(int $id)
    {
        SchoolClass::findOrFail($id)->delete();

        return back()->with('success', 'Data kelas berhasil dihapus.');
    }
}
