<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Kelas;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;


class KelasController extends Controller
{
    public function index(Request $request)
    {
        $query = Kelas::query();

        // SEARCH
        if ($request->has('search')) {
            $search = $request->search;
            $query->where('nama_kelas', 'like', "%$search%")
                  ->orWhere('id_kelas', 'like', "%$search%");
        }

        // SHOW PER PAGE
        $perPage = $request->get('perPage', 10);

        $kelass = $query->paginate($perPage)->appends($request->all());

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

    public function store(Request $request)
{
    $validated = $request->validate([
    'nama_kelas' => [
        'required',
        'string',
        'max:50',
        Rule::unique('kelas')->where(function ($query) use ($request) {
            return $query->where('tingkat', $request->tingkat);
        }),
    ],
    'tingkat' => 'required|in:X,XI,XII',
], [
    'nama_kelas.unique' => 'Nama kelas sudah ada di tingkat ini!',
]);

Kelas::create([
    'nama_kelas' => $validated['nama_kelas'],
    'tingkat' => $validated['tingkat'],
]);

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


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

        $validated = $request->validate([
    'nama_kelas' => [
        'required',
        'string',
        'max:50',
        Rule::unique('kelas')->where(function ($query) use ($request) {
            return $query->where('tingkat', $request->tingkat);
        })->ignore($id, 'id_kelas'),
    ],
    'tingkat' => 'required|in:X,XI,XII',
], [
    'nama_kelas.unique' => 'Nama kelas sudah ada di tingkat ini!',
]);


        $kelas->update($validated);

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

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

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