<?php

namespace App\Http\Controllers\Admin\DataUmum;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Kelas;
use App\Models\User;

class KelasController extends Controller
{
    public function store(Request $request)
    {
        $data = $request->validate([
            'nama' => 'required|string|max:255',
            'fase' => 'required|in:A,B,C',
            'tingkat' => 'required|integer|min:1|max:6',
            'rombel' => 'nullable|string|max:10',
            'walikelas_id' => 'nullable|exists:users,id',
        ]);

        try {
            Kelas::create($data);
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'Gagal menyimpan kelas: ' . $e->getMessage());
        }

        return redirect()->back()->with('success', 'Kelas berhasil ditambahkan.');
    }

    public function update(Request $request, $id)
    {
        $kelas = Kelas::findOrFail($id);

        $data = $request->validate([
            'nama' => 'required|string|max:255',
            'fase' => 'required|in:A,B,C',
            'tingkat' => 'required|integer|min:1|max:6',
            'rombel' => 'nullable|string|max:10',
            'walikelas_id' => 'nullable|exists:users,id',
        ]);

        $kelas->update($data);

        return redirect()->back()->with('success', 'Kelas berhasil diperbarui.');
    }

    public function destroy($id)
    {
        $kelas = Kelas::findOrFail($id);
        $kelas->delete();

        return redirect()->back()->with('success', 'Kelas berhasil dihapus.');
    }
}
