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

class Kepala_cabang extends MY_Controller {

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

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

	public function list_data(){
		$list = $this->Kepala_cabang_m->get_datatables();
		$data = array();
		$no = $_GET['start'];
		foreach ($list as $field) {
			$no++;
			$row = array();
			$row[] = $no;
			$row[] = $field->nik." - ".$field->nama_lengkap;
			if($field->jumlah_cabang > 1){
				$select_cabang = $this->Kepala_cabang_m->getCabang(md5($field->id_karyawan));
				
				$cabang = "";
				foreach($select_cabang as $rows){
					if($rows->flag == "1"){
						$badge = "badge-secondary";
					}else{
						$badge = "badge-primary";
					}

					$cabang .= "<h6 class='badge ".$badge."'>".$rows->kode_cabang." - ".$rows->nama_cabang."</h6>";
					$cabang .=" ";
					
				}
			}else{
				$cabang = "<label class='badge badge-secondary'>".$field->kode_cabang." - ".$field->nama_cabang."</label>";
			}
			
			$row[] = $cabang;

			if(in_array($this->session->userdata("level_user"),['1'])){
				$row[] = '<a href="#" class="text-warning" title="EDIT">
								<i id="'.md5($field->id_karyawan).'" class="btn_edit fa fa-edit (alias) "> </i>
							</a>';
			}
	
			$data[] = $row;
		}
	
			$output = array("draw"            => $_GET['draw'],
							"recordsTotal"    => $this->Kepala_cabang_m->count_all(),
							"recordsFiltered" => $this->Kepala_cabang_m->count_filtered(),
							"data"            => $data);
	
		$output = __response($this->MY_response, $output);
				
		echo json_encode($output);
	}

	public function form($id_karyawan=null){
		$data_karyawan = $this->Kepala_cabang_m->getKaryawan($id_karyawan);
		$data["karyawan"] = $data_karyawan;

		$data["cabang"] = $this->Kepala_cabang_m->getCabang($id_karyawan);

		$this->load->view('pengaturan/kepala_cabang/form',$data);
	}

	public function update(){
		$id_company = $this->session->userdata("id_company");
		$id_karyawan = $this->input->post('id_karyawan');
		$data_cabang = $this->input->post('data_cabang');
		$data_insert = [];

		$nextId = $this->fungsi->getNextId('p_kacab','id',$id_company,3);
		$nomor_urut = substr($nextId,-3);
		foreach($data_cabang as $rows){
			$id = substr_replace($nextId,(sprintf("%03d",$nomor_urut)),-3);

			$data_insert[] = array("id" =>$id,
								"id_karyawan" => $id_karyawan,
								"id_cabang" => $rows["cabang"],
								"id_company" => $id_company);

			$nomor_urut++;
		}
	
		$this->Kepala_cabang_m->update($data_insert,$id_karyawan,$id_company); 
	}
}
