<?php

namespace App\Controllers;

use App\Models\UserRoleModel;

class User_Role extends BaseController
{
    public function index()
    {
        $model = new UserRoleModel();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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