<?php

namespace App\Controllers;

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

class Supplier extends BaseController
{
    protected $supplierModel;

    public function __construct()
    {
        $this->supplierModel = new SupplierModel();
        
        $session = session();
    if (!$session->get('logged_in') || $session->get('role') === 'kasir') {
        redirect()->to(base_url('admin/dashboard'))->send();
        exit;
    }
    }

    public function index()
    {
        $data = [
            'title' => 'Data Supplier',
            'suppliers' => $this->supplierModel->orderBy('created_at', 'DESC')->findAll(),
        ];
        return view('supplier/index', $data);
    }

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

    public function store()
    {
        $this->supplierModel->save([
            'nama' => $this->request->getPost('nama'),
            'email' => $this->request->getPost('email'),
            'kontak_person' => $this->request->getPost('kontak_person'),
            'telepon' => $this->request->getPost('telepon'),
            'alamat' => $this->request->getPost('alamat'),
            'diubah' => date('Y-m-d H:i:s'),
        ]);
        return redirect()->to(base_url('admin/supplier'))->with('success', 'Supplier berhasil ditambahkan.');
    }

    public function edit($id)
    {
        $data = [
            'title' => 'Edit Supplier',
            'supplier' => $this->supplierModel->find($id),
        ];
        return view('supplier/edit', $data);
    }

    public function update($id)
    {
        $supplierModel = new \App\Models\SupplierModel();
        
        $this->supplierModel->update($id, [
            'nama' => $this->request->getPost('nama'),
            'email' => $this->request->getPost('email'),
            'kontak_person' => $this->request->getPost('kontak_person'),
            'telepon' => $this->request->getPost('telepon'),
            'alamat' => $this->request->getPost('alamat'),
            'diubah' => date('Y-m-d H:i:s'),
        ]);


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

    public function delete($id)
    {
        $this->supplierModel->delete($id);
        return redirect()->to(base_url('admin/supplier'))->with('success', 'Supplier berhasil dihapus.');
    }
}
