<?php

namespace App\Controllers\View;

use App\Controllers\BaseController;
use App\Models\SupplyCategoryModel;


class SupplyCategoryController extends BaseController
{
    protected $model;

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

    public function index()
    {
        return view('inventory/categories_index', [
            'categories' => $this->model->orderBy('name')->findAll(),
        ]);
    }

    public function create()
    {
        return view('inventory/categories_form', [
            'title' => 'Add Category',
            'action' => site_url('inventory/categories/store'),
            'category' => null,
        ]);
    }

    public function store()
    {
        $data = $this->request->getPost(['name']);
        if (!$this->model->save($data)) {
            return redirect()->back()->withInput()->with('error', implode("\n", $this->model->errors()));
        }
        return redirect()->to(site_url('inventory/categories'))->with('success', 'Category saved.');
    }

    public function edit($id)
    {
        $cat = $this->model->find($id);
        if (!$cat) return redirect()->to('inventory/categories')->with('error', 'Not found.');
        return view('inventory/categories_form', [
            'title' => 'Edit Category',
            'action' => site_url('inventory/categories/update/'.$id),
            'category' => $cat,
        ]);
    }

    public function update($id)
    {
        $data = $this->request->getPost(['name']);
        $data['id'] = (int) $id;
        if (!$this->model->save($data)) {
            return redirect()->back()->withInput()->with('error', implode("\n", $this->model->errors()));
        }
        return redirect()->to(site_url('inventory/categories'))->with('success', 'Category updated.');
    }

    public function delete($id)
    {
        $this->model->delete($id);
        return redirect()->to(site_url('inventory/categories'))->with('success', 'Category deleted.');
    }
}
