<?php

namespace App\Controllers;

use App\Models\GradeModel;

class Grade extends BaseController
{
    public function index()
    {
        $model = new GradeModel();

        $data['grades'] = $model->whereIn('status', [1, 2])->orderBy("CAST(REPLACE(name, 'Grade ', '') AS UNSIGNED)", '', false)->findAll();

        return view('grade', $data);
    }

    public function save()
    { 
        $model = new GradeModel();

        $result = $model->save([
            'name' => $this->request->getPost('name'),
            'code' => strtoupper($this->request->getPost('code')),
            'description' => $this->request->getPost('description'),
            'status' => $this->request->getPost('status')
        ]);

        if ($result) {
            session()->setFlashdata(
                'success',
                'Grade saved successfully.'
            );
        } else {
            session()->setFlashdata(
                'error',
                'Unable to save Grade.'
            );
        }

        return redirect()->to('/grade');
    }

    public function get($id)
    {
        $model = new GradeModel();

        $data = $model->find($id);

        return $this->response->setJSON($data);
    }

    public function update()
    {
        $model = new GradeModel();

        $id = $this->request->getPost('updid');

        $result = $model->update($id, [
            'code' => strtoupper($this->request->getPost('updcode')),
            'name' => $this->request->getPost('updname'),
            'description' => $this->request->getPost('upddescription'),
            'status' => $this->request->getPost('updstatus'),
        ]);

        if ($result) {
            session()->setFlashdata(
                'success',
                'Grade updated successfully.'
            );
        } else {
            session()->setFlashdata(
                'error',
                'Unable to update Grade.'
            );
        }

        return redirect()->to('/grade');
    }

    public function delete()
    {
        $model = new GradeModel();

        $id = $this->request->getPost('delid');

        $result = $model->update($id, [
            'status' => 3
        ]);

        if ($result) {
            session()->setFlashdata(
                'success',
                'Grade deleted successfully.'
            );
        } else {
            session()->setFlashdata(
                'error',
                'Unable to delete Grade.'
            );
        }

        return redirect()->to('/grade');
    }
}