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

class Kelompok extends CI_Controller {

	public function __construct()
	{
		parent::__construct();
		$this->load->model('kelompok_model','kelompok');
		$this->load->helper('url');
		if ($this->session->userdata('username')=='') {
            redirect('login');
        } 
	}

	public function index()
	{
		$this->template->display('admin/kelompok');
	}
	public function balikin($str){
		$search = array ("'xpsijix'");
		$replace = array ("'");
		$str = preg_replace($search,$replace,$str);
		return $str;
	}
	public function ajax_list()
	{
		$list = $this->kelompok->get_datatables();
		$data = array();
		$no = $_POST['start'];
		foreach ($list as $kelompok) {
			$no++;
			$row = array();
			$row[] = $no;
			$row[] = '<a class="btn btn-white btn-primary btn-sm" href="javascript:void(0)" title="Edit kelompok" onclick="edit_kelompok('."'".$kelompok->id."'".')"><i class="glyphicon glyphicon-pencil"></i></a>
				  <a class="btn btn-white btn-danger btn-sm" href="javascript:void(0)" title="Hapus" onclick="delete_log('."'".$kelompok->id."'".')"><i class="glyphicon glyphicon-trash"></i></a>';
			$row[] = $kelompok->kode;
			$row[] = $kelompok->nama;
			$row[] = $kelompok->urut;
			$data[] = $row;
		}

			$output = array(
						"draw" => $_POST['draw'],
						"recordsTotal" => $this->kelompok->count_all(),
						"recordsFiltered" => $this->kelompok->count_filtered(),
						"data" => $data,
				);
		
		echo json_encode($output);
	}
	
	
	public function ajax_edit($id)
	{
		$data = $this->kelompok->get_by_id($id);
		echo json_encode($data);
	}
	public function ajax_add()
	{
		$this->_validate();
		$data = array(
				'kode' => $this->input->post('kode'),
				'nama' => $this->input->post('nama'),
				'urut' => $this->input->post('urut'),
			);

		$insert = $this->kelompok->save($data);

		echo json_encode(array("status" => TRUE));
	}
	public function ajax_update()
	{
		$this->_validate();
		$data = array(
				'kode' => $this->input->post('kode'),
				'nama' => $this->input->post('nama'),
				'urut' => $this->input->post('urut'),
			);

		$this->kelompok->update(array('id' => $this->input->post('id')), $data);
		echo json_encode(array("status" => TRUE));
	}
	public function ajax_delete($id)
	{
		$kelompok = $this->kelompok->get_by_id($id);
		$this->kelompok->delete_by_id($id);
		echo json_encode(array("status" => TRUE));
	}
	private function _validate()
	{
		$data = array();
		$data['error_string'] = array();
		$data['inputerror'] = array();
		$data['status'] = TRUE;

		if($this->input->post('kode') == '')
		{
			$data['inputerror'][] = 'kode';
			$data['error_string'][] = 'Kode wajib di isi';
			$data['status'] = FALSE;
		}
		if($this->input->post('nama') == '')
		{
			$data['inputerror'][] = 'nama';
			$data['error_string'][] = 'Nama wajib di isi';
			$data['status'] = FALSE;
		}
		if($data['status'] === FALSE)
		{
			echo json_encode($data);
			exit();
		}
	}

}
