<?php

namespace App\Controllers\Master;

use App\Controllers\BaseController;
use App\Models\RombelModel;

class Rombel extends BaseController
{
    protected $rombel;

    public function __construct()
    {
        $this->rombel = new RombelModel();
    }

    public function index()
    {
        return view('master/rombel/index');
    }

    public function data()
    {
        $request = service('request');

        $draw   = $request->getGet('draw');
        $start  = $request->getGet('start');
        $length = $request->getGet('length');
        $search = $request->getGet('search')['value'];

        $builder = $this->rombel
            ->select('rombel.id, kelas.nama_kelas, rombel.nama_rombel, rombel.wali_kelas')
            ->join('kelas', 'kelas.id = rombel.kelas_id');

        if ($search) {
            $builder
                ->groupStart()
                ->like('kelas.nama_kelas', $search)
                ->orLike('rombel.nama_rombel', $search)
                ->orLike('rombel.wali_kelas', $search)
                ->groupEnd();
        }

        $totalFiltered = $builder->countAllResults(false);

        $data = $builder
            ->orderBy('kelas.nama_kelas', 'ASC')
            ->findAll($length, $start);

        return $this->response->setJSON([
            'draw'            => intval($draw),
            'recordsTotal'    => $this->rombel->countAll(),
            'recordsFiltered' => $totalFiltered,
            'data'            => $data
        ]);
    }
}
