<?php

namespace App\Controllers\Owner;

use App\Controllers\BaseController;
use App\Models\SupplierModel;

class Supplier extends BaseController
{
    protected $supplier;

    public function __construct()
    {
        $this->supplier = new SupplierModel();
    }

    public function index()
    {
        $data = [
            'title' => 'Data Supplier',
            'suppliers' => $this->supplier->orderBy('id_supplier','DESC')->findAll()
        ];

        return view('owner/supplier/index', $data);
    }

    public function create()
    {
        return view('owner/supplier/create',[
            'title'=>'Tambah Supplier'
        ]);
    }

    public function store()
    {
        $this->supplier->save([

            'nama_supplier'=>$this->request->getPost('nama_supplier'),

            'kontak'=>$this->request->getPost('kontak'),

            'alamat'=>$this->request->getPost('alamat')

        ]);

        return redirect()->to(base_url('owner/supplier'))
            ->with('success','Supplier berhasil ditambahkan');
    }

    public function edit($id)
    {
        $supplier=$this->supplier->find($id);

        if(!$supplier){

            return redirect()->to(base_url('owner/supplier'))
                ->with('error','Supplier tidak ditemukan');

        }

        return view('owner/supplier/edit',[
            'title'=>'Edit Supplier',
            'supplier'=>$supplier
        ]);
    }

    public function update($id)
    {
        $this->supplier->update($id,[

            'nama_supplier'=>$this->request->getPost('nama_supplier'),

            'kontak'=>$this->request->getPost('kontak'),

            'alamat'=>$this->request->getPost('alamat')

        ]);

        return redirect()->to(base_url('owner/supplier'))
            ->with('success','Supplier berhasil diupdate');
    }

    public function delete($id)
    {
        $this->supplier->delete($id);

        return redirect()->to(base_url('owner/supplier'))
            ->with('success','Supplier berhasil dihapus');
    }
}