<?php

namespace App\Controllers;

use App\Models\KelasModel;

class Kelas extends BaseController
{
    protected $kelasModel;

    public function __construct()
    {
        $this->kelasModel = new KelasModel();
    }

    public function index()
    {
        $data = [
            'title' => 'Manajemen Kelas',
            'kelas' => $this->kelasModel->findAll()
        ];
        return view('kelas/index', $data);
    }

    public function create()
    {
        return view('kelas/create', ['title' => 'Tambah Kelas']);
    }

    public function store()
    {
        $this->kelasModel->save([
            'nama_kelas' => $this->request->getPost('nama_kelas'),
            'jumlah_murid' => $this->request->getPost('jumlah_murid'),
            'tahun_ajaran' => $this->request->getPost('tahun_ajaran'),
        ]);
        return redirect()->to('/kelas')->with('success', 'Data kelas berhasil ditambahkan.');
    }

    public function edit($id)
    {
        $kelas = $this->kelasModel->find($id);
        if (!$kelas) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound('Kelas tidak ditemukan');
        }
        return view('kelas/edit', ['title' => 'Edit Kelas', 'kelas' => $kelas]);
    }

    public function update($id)
    {
        $this->kelasModel->update($id, [
            'nama_kelas' => $this->request->getPost('nama_kelas'),
            'jumlah_murid' => $this->request->getPost('jumlah_murid'),
            'tahun_ajaran' => $this->request->getPost('tahun_ajaran'),
        ]);
        return redirect()->to('/kelas')->with('success', 'Data kelas berhasil diperbarui.');
    }

    public function delete($id)
    {
        $this->kelasModel->delete($id);
        return redirect()->to('/kelas')->with('success', 'Data kelas berhasil dihapus.');
    }
}
