<?php

namespace App\Controllers;

use App\Models\ClassTypeModel;

class Class_Type extends BaseController
{
    public function index()
    {
        $model = new ClassTypeModel();

        $data['classTypes'] = $model->whereIn('status', [1, 2])->orderBy('created_datetime', 'DESC')->findAll();

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

    public function save()
    { log_message('debug', 'Controller reached successfully');
        $model = new ClassTypeModel();

        $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',
                'Class type saved successfully.'
            );
        } else {
            session()->setFlashdata(
                'error',
                'Unable to save class type.'
            );
        }

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

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

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

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

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

        $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',
                'Class type updated successfully.'
            );
        } else {
            session()->setFlashdata(
                'error',
                'Unable to update class type.'
            );
        }

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

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

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

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

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

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