<?php

namespace App\Http\Controllers\Guru;

use App\Http\Controllers\Controller;
use App\Models\Kelas;
use App\Models\Mengajar;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class KelasController extends Controller
{
    public function index(Request $request)
    {
        $guru = Auth::guard('guru')->user();

        // Ambil hanya id_kelas yang diajar guru ini
        $kelasIds = Mengajar::where('id_guru', $guru->id_guru)
            ->pluck('id_kelas')
            ->unique();

        $query = Kelas::whereIn('id_kelas', $kelasIds);

        // SEARCH
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('nama_kelas', 'like', "%$search%")
                  ->orWhere('tingkat', 'like', "%$search%");
            });
        }

        $perPage = $request->get('perPage', 10);
        $kelass  = $query->orderBy('tingkat')
                         ->orderBy('nama_kelas')
                         ->paginate($perPage)
                         ->appends($request->all());

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