<?php

namespace App\Controllers;

use App\Models\ClassStatusModel;

class Class_Status extends BaseController
{
    public function index()
    {
        $model = new ClassStatusModel();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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