<?php

namespace App\Controllers;

use App\Models\PupukModel;

class Pupuk extends BaseController
{
    protected $pupukM;
    public function __construct()
    {
        $this->pupukM = new PupukModel();
    }

    public function index()
    {
        $data = ['title' => 'Stok Pupuk', 'pupuk' => $this->pupukM->findAll()];
        return view('pupuk/index', $data);
    }

    public function simpan()
    {
        $this->pupukM->save($this->request->getPost());
        return redirect()->to('/pupuk')->with('success', 'Jenis pupuk baru <b>berhasil didaftarkan</b>.');
    }

    public function update($id)
    {
        $this->pupukM->update($id, $this->request->getPost());
        return redirect()->to('/pupuk')->with('success', 'Data stok/harga pupuk <b>berhasil diperbarui</b>.');
    }

    public function hapus($id)
    {
        try {
            $this->pupukM->delete($id);
            return redirect()->to('/pupuk')->with('success', 'Data pupuk <b>berhasil dihapus</b>.');
        } catch (\Exception $e) {
            return redirect()->to('/pupuk')->with('error', 'Gagal menghapus! Data pupuk ini mungkin sudah terikat dengan transaksi.');
        }
    }
}
