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

class Cabang extends MY_Controller{

	public function __construct(){
        parent::__construct();
        $this->load->model('Cabang_m');
    }

	public function index(){
		$data['judul'] = 'Cabang';
		$data['aktif'] = 'cabang';
        $data['menu'] = $this->load->view('main_menu', $data, true);
		$data['content'] = $this->load->view('cabang/home', $data, true);
		$this->load->view('main_template', $data, false);
	}

	public function list_data(){
		$list = $this->Cabang_m->get_datatables();
		$data = array();
		$no = $_POST['start'];
		foreach ($list as $field) {
			$no++;
			$row = array();
			$row[] = $no;
			$row[] = $field->kode;
			$row[] = $field->nama;
			$row[] = (($field->flag == '1')?"PUSAT":"CABANG");

			if(in_array($this->session->userdata('level_user'), array("1"))) {
				$btn_edit = '<a href="#" class="text-warning" title="EDIT"> <i id="'.md5($field->id_cabang).'" class="btn_edit fa fa-edit (alias) "> </i></a>';
				if($field->flag == '1'){
					$btn_hapus = "";
				}else{
					$btn_hapus = '<a href="#" class="text-danger" title="HAPUS"><i id="'.md5($field->id_cabang).'" class="btn_delete fa fa-trash"></i></a>';
				}
				$row[] =$btn_edit.' '.$btn_hapus;
			}

			$data[] = $row;
		}

		$output = array("draw"            => $_POST['draw'],
						"recordsTotal"    => $this->Cabang_m->count_all(),
						"recordsFiltered" => $this->Cabang_m->count_filtered(),
						"data"            => $data);

		$output = __response($this->MY_response, $output);

		echo json_encode($output);
	}

	public function form($id=null){
		if($id==null){
			$this->load->view('cabang/form');
		}else{
			$data['data'] = $this->Cabang_m->getDataById($id);
			$this->load->view('cabang/form',$data);
		}

	}

	public function save(){
		$id = $this->input->post('id_cabang');
		$id_company = $this->session->userdata('id_company');

		$flag = $this->input->post('flag');

		if(empty($flag)){
			$flag = '2';
		}else{
			$flag = $flag;
		}

		$data = array('kode'		=>$this->input->post('kd_cabang'),
					'nama'			=>$this->input->post('nm_cabang'),
					'flag'			=>$flag,
					'id_company' 	=>$id_company);

		$this->Cabang_m->save($data,$id,$id_company);
	}

	public function registrasi(){
		$id_company = $this->input->post('id_company');
		$id = null;
		$data = array('kode'		=>'PST',
					'nama'			=>'PUSAT',
					'flag'			=>'1',
					'id_company' 	=>$id_company);

		$this->Cabang_m->save($data,$id,$id_company);
	}

	public function delete(){
		$id = $this->input->post("id_cabang");
		$this->Cabang_m->delete($id);
	}
}
