<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\CustomerModel;

class Customer extends BaseController
{
    protected $customerModel;

    public function __construct()
    {
        $this->customerModel = new CustomerModel();

        $session = session();
    if (!$session->get('logged_in') || $session->get('role') === 'kasir') {
        redirect()->to(base_url('admin/dashboard'))->send();
        exit;
    }
    }

    public function index()
    {
        return view('customer/index', [
            'title' => 'Data Customers',
            'customers' => $this->customerModel->findAll()
        ]);
    }

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

    public function store()
    {
        $this->customerModel->insert([
            'nama'       => $this->request->getPost('nama'),
            'telepon'    => $this->request->getPost('telepon'),
            'email'      => $this->request->getPost('email'),
            'alamat'     => $this->request->getPost('alamat'),
            'created_at' => date('Y-m-d H:i:s')
        ]);

        return redirect()->to(base_url('admin/customer'))->with('success', 'Customer berhasil ditambahkan.');
    }

    public function edit($id)
    {
        return view('customer/edit', [
            'title' => 'Edit Customer',
            'customer' => $this->customerModel->find($id)
        ]);
    }

    public function update($id)
    {
        $this->customerModel->update($id, [
            'nama'    => $this->request->getPost('nama'),
            'telepon' => $this->request->getPost('telepon'),
            'email'   => $this->request->getPost('email'),
            'alamat'  => $this->request->getPost('alamat'),
        ]);

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

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