<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Mapel;
use App\Models\Kelas;
use App\Models\Mengajar;
use Illuminate\Http\Request;

class MapelController extends Controller
{

    public function index(Request $request)
    {
        $query = Mapel::with('kelas');

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

        // FILTER KELAS
        if ($request->filter_kelas) {
            $query->whereHas('kelas', function ($q) use ($request) {
                $q->where('kelas.id_kelas', $request->filter_kelas);
            });
        }

        $perPage = $request->get('perPage', 10);

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

        $kelass = Kelas::orderBy('tingkat')
            ->orderBy('nama_kelas')
            ->get();

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



    public function store(Request $request)
    {

        $request->validate([
            'nama_mapel' => 'required|max:100',
            'kelas' => 'required|array'
        ]);

        $mapel = Mapel::create([
            'nama_mapel' => $request->nama_mapel
        ]);

        foreach ($request->kelas as $kelas) {

            Mengajar::create([
                'id_mapel' => $mapel->id_mapel,
                'id_kelas' => $kelas,
                'id_guru' => null
            ]);
        }

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



    public function update(Request $request, $id)
    {

        $request->validate([
            'nama_mapel' => 'required|max:100',
            'kelas' => 'required|array'
        ]);

        $mapel = Mapel::findOrFail($id);

        $mapel->update([
            'nama_mapel' => $request->nama_mapel
        ]);

        // hapus relasi lama
        Mengajar::where('id_mapel', $mapel->id_mapel)->delete();

        // simpan relasi baru
        foreach ($request->kelas as $kelas) {

            Mengajar::create([
                'id_mapel' => $mapel->id_mapel,
                'id_kelas' => $kelas,
                'id_guru' => null
            ]);
        }

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



    public function destroy($id)
    {

        $mapel = Mapel::findOrFail($id);

        Mengajar::where('id_mapel', $id)->delete();

        $mapel->delete();

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