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

class Services extends MY_Controller
{
	public function __construct()
	{
		parent::__construct();
		$this->require_login();
		$this->load->model('Service_model', 'services');
	}

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

	public function create()
	{
		$this->form_validation->set_rules('name', 'Nama layanan', 'trim|required|max_length[100]');
		$this->form_validation->set_rules('unit', 'Satuan', 'trim|required|max_length[20]');
		$this->form_validation->set_rules('price', 'Harga', 'trim|required|numeric');

		if ($this->input->method(TRUE) === 'POST' && $this->form_validation->run()) {
			$this->services->create(array(
				'name' => $this->input->post('name', TRUE),
				'unit' => $this->input->post('unit', TRUE),
				'price' => (float) $this->input->post('price', TRUE),
			));
			$this->session->set_flashdata('success', 'Layanan berhasil ditambahkan.');
			redirect('services');
		}

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

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

		$this->form_validation->set_rules('name', 'Nama layanan', 'trim|required|max_length[100]');
		$this->form_validation->set_rules('unit', 'Satuan', 'trim|required|max_length[20]');
		$this->form_validation->set_rules('price', 'Harga', 'trim|required|numeric');

		if ($this->input->method(TRUE) === 'POST' && $this->form_validation->run()) {
			$this->services->update($id, array(
				'name' => $this->input->post('name', TRUE),
				'unit' => $this->input->post('unit', TRUE),
				'price' => (float) $this->input->post('price', TRUE),
			));
			$this->session->set_flashdata('success', 'Layanan berhasil diubah.');
			redirect('services');
		}

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

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

