<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\BukuModel;

class Buku extends BaseController
{
    protected $buku;

    public function __construct()
    {
        $this->buku = new BukuModel();
    }

    public function index()
    {
        $data['buku'] = $this->buku->findAll();
        return view('buku/index', $data);
    }

    public function create()
    {
        return view('buku/create');
    }

    public function store()
    {
        $this->buku->save([
            'kode_buku' => $this->request->getPost('kode_buku'),
            'judul'     => $this->request->getPost('judul'),
            'penulis'   => $this->request->getPost('penulis'),
            'penerbit'  => $this->request->getPost('penerbit'),
            'tahun'     => $this->request->getPost('tahun'),
            'rak'       => $this->request->getPost('rak'),
            'kategori'  => $this->request->getPost('kategori'),
            'stok'      => $this->request->getPost('stok'),
        ]);

        return redirect()->to('/buku')->with('success', 'Data buku berhasil ditambahkan');
    }

    public function edit($id)
    {
        $data['buku'] = $this->buku->find($id);
        return view('buku/edit', $data);
    }

    public function update($id)
    {
        $this->buku->update($id, [
            'kode_buku' => $this->request->getPost('kode_buku'),
            'judul'     => $this->request->getPost('judul'),
            'penulis'   => $this->request->getPost('penulis'),
            'penerbit'  => $this->request->getPost('penerbit'),
            'tahun'     => $this->request->getPost('tahun'),
            'rak'       => $this->request->getPost('rak'),
            'kategori'  => $this->request->getPost('kategori'),
            'stok'      => $this->request->getPost('stok'),
        ]);

        return redirect()->to('/buku')->with('success', 'Data buku berhasil diubah');
    }

    public function delete($id)
    {
        $this->buku->delete($id);
        return redirect()->to('/buku')->with('success', 'Data buku berhasil dihapus');
    }
}