<?php

// app/Controllers/DataKelasMurid.php

namespace App\Controllers;

use App\Models\DataKelasMuridModel;
use App\Models\SiswaModel;
use App\Models\KelasModel;

class DataKelasMurid extends BaseController
{
    protected $dataKelasMuridModel;
    protected $siswaModel;
    protected $kelasModel;

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

    public function index()
    {
        $data['data_kelas_murid'] = $this->dataKelasMuridModel->getDataKelasMurid();
        return view('dashboard/data_kelas_murid/index', $data);
    }

    public function create()
    {
        $data['siswa'] = $this->siswaModel->findAll();
        $data['kelas'] = $this->kelasModel->findAll();
        return view('dashboard/data_kelas_murid/create', $data);
    }

    public function store()
    {
        $this->dataKelasMuridModel->save([
            'id_siswa' => $this->request->getPost('id_siswa'),
            'id_kelas' => $this->request->getPost('id_kelas')
        ]);

        return redirect()->to('/data-kelas-murid');
    }

    public function edit($id)
    {
        $data['data_kelas_murid'] = $this->dataKelasMuridModel->find($id);
    
        if (!$data['data_kelas_murid'] || !isset($data['data_kelas_murid']['id_siswa'])) {
            throw new \CodeIgniter\Exceptions\PageNotFoundException('Data Kelas Murid tidak ditemukan atau tidak lengkap.');
        }
    
        $data['siswa'] = $this->siswaModel->findAll();
        $data['kelas'] = $this->kelasModel->findAll();
    
        return view('dashboard/data_kelas_murid/edit', $data);
    }
    

    public function update($id)
    {
        $this->dataKelasMuridModel->update($id, [
            'id_siswa' => $this->request->getPost('id_siswa'),
            'id_kelas' => $this->request->getPost('id_kelas')
        ]);

        return redirect()->to('/data-kelas-murid');
    }

    public function delete($id)
    {
        $this->dataKelasMuridModel->delete($id);
        return redirect()->to('/data-kelas-murid');
    }
}
