<?php  
namespace App\Controllers;

use App\Models\CategoryModel;
use CodeIgniter\Controller;

class Category extends Controller
{
    protected $model;

    public function __construct()
    {
        $this->model = new CategoryModel();

        $session = session();
    if (!$session->get('logged_in') || $session->get('role') === 'kasir') {
        redirect()->to(base_url('admin/dashboard'))->send();
        exit;
    }
    }

    public function index()
    {
        $data = [
            'title' => 'Data Categories',
            'categories' => $this->model->findAll()
        ];
        return view('category/index', $data);
    }

    public function save()
    {
        $this->model->save([
            'nama' => $this->request->getPost('nama')
        ]);
        return redirect()->to('/admin/category');
    }

    public function delete($id)
    {
        $this->model->delete($id);
        return redirect()->to('/admin/category');
    }

    public function edit($id)
    {
        $category = $this->model->find($id);
        if (!$category) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound('Kategori tidak ditemukan.');
        }

        $data['category'] = $category;
        return view('category/category_form', $data);
    }

    public function update($id)
    {
        $category = $this->model->find($id);
        if (!$category) {
            return redirect()->to('/admin/category')->with('error', 'Kategori tidak ditemukan.');
        }

        $this->model->update($id, [
            'nama' => $this->request->getPost('nama'),
        ]);

        return redirect()->to('/admin/category')->with('success', 'Kategori berhasil diperbarui.');
    }
}
