<?php

namespace App\Http\Controllers;

use App\Models\Student;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class AdminStudentController extends Controller
{
    public function index(): View
    {
        $students = Student::orderBy('kohort')->orderBy('program')->orderBy('kelas')->paginate(10);

        return view('admin.students.index', compact('students'));
    }

    public function create(): View
    {
        return view('admin.students.form', [
            'student' => new Student(),
            'mode' => 'create',
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $data = $this->validateData($request);
        Student::create($data);

        return redirect()->route('admin.students.index')
            ->with('status', 'Rekod pelajar kelas berjaya ditambah.');
    }

    public function edit(Student $student): View
    {
        return view('admin.students.form', [
            'student' => $student,
            'mode' => 'edit',
        ]);
    }

    public function update(Request $request, Student $student): RedirectResponse
    {
        $data = $this->validateData($request);
        $student->update($data);

        return redirect()->route('admin.students.index')
            ->with('status', 'Rekod pelajar kelas berjaya dikemaskini.');
    }

    public function destroy(Student $student): RedirectResponse
    {
        $student->delete();

        return back()->with('status', 'Rekod pelajar kelas dipadam.');
    }

    protected function validateData(Request $request): array
    {
        return $request->validate([
            'kohort' => ['required', 'string', 'max:50'],
            'peringkat' => ['required', 'string', 'max:50'],
            'program' => ['required', 'string', 'max:255'],
            'kelas' => ['required', 'string', 'max:50'],
            'bil_lelaki' => ['required', 'integer', 'min:0'],
            'bil_perempuan' => ['required', 'integer', 'min:0'],
            'bil_asrama_lelaki' => ['required', 'integer', 'min:0'],
            'bil_asrama_perempuan' => ['required', 'integer', 'min:0'],
            'bil_bukan_asrama' => ['required', 'integer', 'min:0'],
            'agama_islam' => ['required', 'integer', 'min:0'],
            'agama_bukan_islam' => ['required', 'integer', 'min:0'],
            'kaum_melayu' => ['required', 'integer', 'min:0'],
            'kaum_cina' => ['required', 'integer', 'min:0'],
            'kaum_india' => ['required', 'integer', 'min:0'],
            'kaum_lain' => ['required', 'integer', 'min:0'],
        ]);
    }
}

