<?php

namespace App\Controllers;

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

class Category extends Controller
{
    public function index()
    {
        $model = new CategoryModel();
        $data['categories'] = $model->findAll();
        return view('categorylist', $data);
    }

    public function add()
    {
        return view('categoryAdd');
    }

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

        $data = [
            'category_name' => $this->request->getPost('category_name'),
            'description'   => $this->request->getPost('description'),
        ];

        $model->insert($data);

        return redirect()->to('/category')->with('success', 'Category added successfully!');
    }

    public function edit($id)
    {
        $model = new CategoryModel();
        $data['category'] = $model->find($id);
        return view('categoryedit', $data);
    }

    public function update($id)
    {
        $model = new CategoryModel();

        $data = [
            'category_name' => $this->request->getPost('category_name'),
            'description'   => $this->request->getPost('description'),
        ];

        $model->update($id, $data);

        return redirect()->to('/category')->with('success', 'Category updated successfully!');
    }

    public function delete($id)
    {
        $model = new CategoryModel();
        $model->delete($id);
        return redirect()->to('/category')->with('success', 'Category deleted successfully!');
    }
}
