<?php 
namespace App\Controllers;

use App\Models\UnitModel;
use CodeIgniter\Controller;

class Unit extends Controller
{
    protected $model;

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

    public function index()
    {
        $data = [
            'title' => 'Data Satuan Unit',
            'units' => $this->model->findAll()
        ];
        return view('unit/index', $data);
    }

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

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

    $data = [
        'title' => 'Edit Unit',
        'unit'  => $unit
    ];

    return view('unit/edit', $data);
}

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

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

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


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