<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Customers extends MY_Controller
{
	public function __construct()
	{
		parent::__construct();
		$this->require_login();
		$this->load->model('Customer_model', 'customers');
	}

	public function index()
	{
		$this->render('customers/index', array(
			'title' => 'Pelanggan',
			'rows' => $this->customers->all(),
		));
	}

	public function create()
	{
		$this->form_validation->set_rules('name', 'Nama', 'trim|required|max_length[100]');
		$this->form_validation->set_rules('phone', 'No. HP', 'trim|max_length[30]');
		$this->form_validation->set_rules('address', 'Alamat', 'trim|max_length[255]');

		if ($this->input->method(TRUE) === 'POST' && $this->form_validation->run()) {
			$this->customers->create(array(
				'name' => $this->input->post('name', TRUE),
				'phone' => $this->input->post('phone', TRUE),
				'address' => $this->input->post('address', TRUE),
			));
			$this->session->set_flashdata('success', 'Pelanggan berhasil ditambahkan.');
			redirect('customers');
		}

		$this->render('customers/form', array(
			'title' => 'Tambah Pelanggan',
			'mode' => 'create',
			'row' => null,
		));
	}

	public function edit($id)
	{
		$row = $this->customers->find($id);
		if (!$row) {
			show_404();
		}

		$this->form_validation->set_rules('name', 'Nama', 'trim|required|max_length[100]');
		$this->form_validation->set_rules('phone', 'No. HP', 'trim|max_length[30]');
		$this->form_validation->set_rules('address', 'Alamat', 'trim|max_length[255]');

		if ($this->input->method(TRUE) === 'POST' && $this->form_validation->run()) {
			$this->customers->update($id, array(
				'name' => $this->input->post('name', TRUE),
				'phone' => $this->input->post('phone', TRUE),
				'address' => $this->input->post('address', TRUE),
			));
			$this->session->set_flashdata('success', 'Pelanggan berhasil diubah.');
			redirect('customers');
		}

		$this->render('customers/form', array(
			'title' => 'Edit Pelanggan',
			'mode' => 'edit',
			'row' => $row,
		));
	}

	public function delete($id)
	{
		if ($this->input->method(TRUE) !== 'POST') {
			show_error('Metode tidak diizinkan', 405);
		}
		$this->customers->delete($id);
		$this->session->set_flashdata('success', 'Pelanggan berhasil dihapus.');
		redirect('customers');
	}
}

