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

class Dstb_process extends CI_Controller {
	public function __construct() {
        parent::__construct();

        $this->load->helper('az_auth');
        az_check_auth('dstb_process');

        $this->table = 'dstb_process';
        $this->load->helper('az_crud');
        $this->load->library('AZApp');
        $this->crud = $this->azapp->add_crud();
        $this->role_allow = array('cashier', 'administrator', '');
        $this->role_name = $this->session->userdata('role_name');
    }

    function check_role() {
    	if (!in_array($this->session->userdata('role_name'), $this->role_allow)) {
			show_404();
		}
    }

	public function index(){
		$azapp = $this->azapp;
		$crud = $this->crud;
		$crud->set_column(array(azlang('No'), 'Tanggal', 'Nomor DSTB', 'Kasir', 'Driver', 'Produksi', 'Total Bill', 'Total PCS', 'Status', azlang('Action')));
		$crud->set_width('10px,,,,,,,120px');
		$crud->set_id($this->table);
		$crud->set_default_url(true);
		$crud->set_btn_add(false);

		$btn = "<a href='".app_url().'dstb_process/add'."'><button class='btn btn-primary btn-add-dstb' type='button'><i class='fa fa-plus'></i> Tambah DSTB Proses</button></a>";
		$btn .= '&nbsp;<button class="btn btn-info" type="button" id="btn_scan"><i class="fa fa-qrcode"></i> Scan QR Code DSTB</button>';
		if (in_array($this->session->userdata('role_name'), $this->role_allow)) {
			$crud->set_btn_top_custom($btn);
		}
	
		$crud = $crud->render();
		$azapp->add_content($crud);
		$azapp->add_content("<div class='container-scanner hide'><button class='btn btn-danger btn-sm btn-close-scanner' type='button'>".azlang('Close')."</button><br><video class='scanner' id='scanner'></video></div>");

		$js = az_add_js('dstb_process/vjs_dstb_process_list');
		$azapp->add_js($js);

		$data_header['title'] = 'DSTB Proses';
		$data_header['breadcrumb'] = array('dstb_process');
		$azapp->set_data_header($data_header);
		
		echo $azapp->render();	
	}

	public function get() {
		$crud = $this->crud;
		$crud->set_select('iddstb_process, dstb_date, dstb_code, cashier.name as cashier_name, driver.name as driver_name, production.name as production_name, total_bill, total_pcs, dstb_process_status');
		$crud->set_select_table('iddstb_process, dstb_date, dstb_code, cashier_name, driver_name, production_name, total_bill, total_pcs, dstb_process_status');
		$crud->set_filter('dstb_date, dstb_code, cashier.name, driver.name, production.name, total_bill, total_pcs, dstb_process_status');
		$crud->set_sorting('dstb_date, dstb_code, cashier.name, driver.name, production.name, total_bill, total_pcs, dstb_process_status');
		$crud->set_id($this->table);
		$crud->add_join_manual('user cashier', 'dstb_process.idcashier = cashier.iduser', 'left');
		$crud->add_join_manual('user driver', 'dstb_process.iddriver = driver.iduser', 'left');
		$crud->add_join_manual('user production', 'dstb_process.idproduction = production.iduser', 'left');
		$crud->add_where("dstb_process.status > 0");
		$crud->set_table($this->table);
		$crud->set_edit(false);

		if (!aznav('role_delete_dstb_process')) {
			$crud->set_delete(false);			
		}

		if ($this->role_name == 'driver') {
			$crud->add_where('dstb_process.iddriver = "'.$this->session->userdata("iduser").'"');
		}
		else if($this->role_name == 'production') {
			$crud->add_where('dstb_process.idproduction = "'.$this->session->userdata("iduser").'"');
			$crud->add_where('dstb_process_status in("DIJEMPUT", "DIPROSES")');
		}
		
		if (strlen($this->session->userdata('idoutlet'))> 0) {
			$crud->add_where('dstb_process.idoutlet = "'.$this->session->userdata('idoutlet').'"');
		}
		if (!in_array($this->session->userdata('idrole'), array('', '1'))) {
			$crud->add_where("dstb_date >(NOW() - INTERVAL 2 DAY)");
		}
		$crud->set_order_by('dstb_date desc');

		$crud->set_custom_style('custom_style');

		echo $crud->get_table();
	}

	function custom_style($key, $value, $data) {
		if ($key == 'action') {
			$id = azarr($data, 'iddstb_process');
			$btn = "<a href='".app_url().'dstb_process/qr/'.az_encode_url($id)."' target='_blank'><button class='btn btn-xs btn-default'><i class='fa fa-qrcode'></i> Cetak QR</button></a>";
			$btn .= "<a href='".app_url().'dstb_process/detail/'.az_encode_url($id)."'><button class='btn btn-xs btn-info btn-detail'><i class='fa fa-list'></i> Detail</button></a>";

			
			if ($this->role_name == 'driver') {
				$btn = "<a href='".app_url().'dstb_process/detail/'.az_encode_url($id)."/driver'><button class='btn btn-xs btn-warning btn-detail'><i class='fa fa-check'></i> Verifikasi Driver</button></a>";
			}
			else if($this->role_name == 'production') {
				$btn = "<a href='".app_url().'dstb_process/detail/'.az_encode_url($id)."/production'><button class='btn btn-xs btn-success btn-detail'><i class='fa fa-check'></i> Verifikasi Produksi</button></a>";	
			}

			return $btn.$value;
		}
		else if ($key == 'dstb_process_status') {
			$lbl = 'primary';
			if ($value == 'DIJEMPUT') {
				$lbl = 'info';
			}
			else if ($value == 'DIPROSES') {
				$lbl = 'success';
			}

			return "<label class='label label-".$lbl."'>".$value."</label>";
		}
		return $value;
	}

	function add() {
		$this->check_role();

		$azapp = $this->azapp;

		$data_header['title'] = 'Tambah DSTB Proses';
		$data_header['breadcrumb'] = array('dstb_process');
		$azapp->set_data_header($data_header);

		$idoutlet = $this->input->get("idoutlet");
		if (strlen($this->session->userdata('idoutlet')) > 0) {
			$idoutlet = $this->session->userdata('idoutlet');
		}

		$this->db->where('transaction_group.idoutlet', $idoutlet);
		$this->db->where('transaction_group.status', 1);
		$this->db->join('customer', 'transaction_group.idcustomer = customer.idcustomer');
		$this->db->where('dstb_status', 'BARU');
		$data['data'] = $this->db->get('transaction_group');

		$arr_data = array();
		foreach ($data['data']->result() as $key => $value) {
			$this->db->where('idtransaction_group', $value->idtransaction_group);
			$check = $this->db->get('dstb_process_detail');
			if ($check->num_rows() == 0) {
				$arr_data[] = array(
					'idtransaction_group' => $value->idtransaction_group,
					'code' => $value->code,
					'customer_name' => $value->customer_name,
					'dstb_status' => $value->dstb_status,
					'total_pcs' => $value->total_pcs,
					'date' => $value->date,
					'date' => $value->date,
					'duedate' => $value->duedate,
					'note' => $value->note,
				);
			}
		}

		$data['arr_data'] = $arr_data;


		$this->db->where('status', 1);
		$data['outlet'] = $this->db->get('outlet');

		$date = $azapp->add_datetime();
		$date->set_id('dstb_date');
		$date->set_name('dstb_date');
		$date->set_value(Date('d-m-Y H:i:s'));
		$data['dstb_date'] = $date->render();


		$view = $this->load->view('dstb_process/v_dstb_process', $data, true);
		$azapp->add_content($view);

		$js = az_add_js('dstb_process/vjs_dstb_process');
		$azapp->add_js($js);

		$modal_detail = $azapp->add_modal();
		$modal_detail->set_id('detail');
		$modal_detail->set_modal_title(azlang('Detail'));
		$modal_detail->set_modal('');
		$azapp->add_content($modal_detail->render());
		
		echo $azapp->render();
	}

	function get_invoice() {
		$this->load->helper('az_core');
		$code = $this->input->post('code');
		$this->load->library('Laundry');
		$data = $this->laundry->invoice($code);

		$err_code = azarr($data, 'err_code');
		$err_message = azarr($data, 'err_message');

		$this->load->helper('az_config');
		$data['product_only'] = true;
		$view = $this->load->view('dstb_process/v_detail_product', $data, true);

		$return = array(
			'err_code' => $err_code,
			'err_message' => $err_message,
			'data' => $view
		);

		echo json_encode($return);
	}

	function save_dstb() {
	    $err_code = 0;
	    $err_message = '';
	
	    $chk = $this->input->post('chk');
	    $iddriver = $this->input->post("iddriver");
	    $idproduction = $this->input->post("idproduction");
	    $idoutlet = $this->input->post('idoutlet');
	    $dstb_date = $this->input->post('dstb_date');
	    $dstb_note = $this->input->post('dstb_note');

	    $sess_idoutlet = $this->session->userdata('idoutlet');
	    if (strlen($sess_idoutlet) > 0) {
	    	$idoutlet = $sess_idoutlet;
	    }

	    if (strlen($iddriver) == 0) {
	    	$err_code++;
	    	$err_message = 'Driver harus diisi';
	    }

	    if ($err_code == 0) {
	    	if (strlen($idproduction) == 0) {
	    		$err_code++;
	    		$err_message = 'Produksi harus diisi';
	    	}
	    }

	    if ($err_code == 0) {
	    	if (strlen($dstb_date) == 0) {
	    		$err_code++;
	    		$err_message = 'Tanggal harus diisi';
	    	}
	    }

	    if ($err_code == 0) {
	    	if (strlen($idoutlet) == 0) {
	    		$err_code++;
	    		$err_message = 'Outlet harus diisi';
	    	}
	    }

	    if ($err_code == 0) {
	    	if (count($chk) == 0) {
	    		$err_code++;
	    		$err_message = 'Harap melakukan checklist pada Bill';
	    	}
	    }

	    $this->db->trans_begin();
	    if ($err_code == 0) {

	    	$dstb_number = 1;
	    	$this->db->where('status', 1);
	    	$this->db->order_by('dstb_number', 'desc');
	    	$this->db->where('date(dstb_date)', Date('Y-m-d', strtotime($dstb_date)));
	    	$data_dstb = $this->db->get('dstb_process', 1);

	    	if ($data_dstb->num_rows() > 0) {
	    		$dstb_number = $data_dstb->row()->dstb_number;
	    		$dstb_number++;
	    	}

	    	$this->db->where('idoutlet', $idoutlet);
	    	$outlet_code = $this->db->get('outlet')->row()->outlet_code;

	    	$dstb_code = $outlet_code.'-'.Date('dmY', strtotime($dstb_date)).'-'.sprintf('%03d', $dstb_number);

	    	$total_bill = count($chk);

	    	$total_pcs = 0;
	    	foreach ((array) $chk as $key => $value) {
	    		$this->db->where('idtransaction_group', $value);
	    		$tg = $this->db->get('transaction_group');
	    		if ($tg->num_rows() > 0) {
	    			$tg_pcs = $tg->row()->total_pcs;
	    			$total_pcs += $tg_pcs;
	    		}
	    	}


	    	$arr_data = array(
	    		'idoutlet' => $idoutlet,
	    		'idcashier' => $this->session->userdata('iduser'),
	    		'iddriver' => $iddriver,
	    		'idproduction' => $idproduction,
	    		'dstb_date' => az_crud_date($dstb_date),
	    		'dstb_number' => $dstb_number,
	    		'dstb_code' => $dstb_code,
	    		'total_bill' => $total_bill,
	    		'total_pcs' => $total_pcs,
	    		'dstb_note' => $dstb_note
	    	);

	    	$save = az_crud_save('', 'dstb_process', $arr_data);
	    	$iddstb_process = azarr($save, 'insert_id');

	    	foreach ((array) $chk as $key => $value) {
	    		$arr_detail = array(
	    			'iddstb_process' => $iddstb_process,
	    			'idtransaction_group' => $value
	    		);
	    		az_crud_save('', 'dstb_process_detail', $arr_detail);
	    	}
    		// $arr_tg = array(
    		// 	'dstb_status' => 'DIJEMPUT'
    		// );
    		// $this->db->where_in('idtransaction_group', $chk);
    		// $this->db->update('transaction_group', $arr_tg);
	    }

	    if ($this->db->trans_status() === FALSE || $err_code > 0) {
	        $this->db->trans_rollback();
	    }
	    else {
	        $this->db->trans_commit();
	    }

	
	    $return = array(
	        'err_code' => $err_code,
	        'err_message' => $err_message
	    );
	
	    echo json_encode($return);
	}
	
	function detail($id, $type = 'cashier') {

		$azapp = $this->azapp;

		$data_header['title'] = 'Detail DSTB Proses';
		$data_header['breadcrumb'] = array('dstb_process');
		$azapp->set_data_header($data_header);

		$db_data = $this->get_db_detail($id);
		$data['data'] = $db_data;

		$page_type = 'cashier';
		if (strlen($type) > 0) {
			$page_type = $type;
		}

		$page_type = $this->session->userdata('role_name');

		$data['page_type'] = $page_type;

		$azapp->add_content("<div class='container-scanner hide'><button class='btn btn-danger btn-sm btn-close-scanner' type='button'>".azlang('Close')."</button><br><video class='scanner' id='scanner'></video></div>");		

		$view = $this->load->view('dstb_process/v_dstb_detail', $data, true);
		$azapp->add_content($view);

		$js = az_add_js('dstb_process/vjs_dstb_detail');
		$azapp->add_js($js);

		$js = az_add_js('dstb_process/vjs_dstb_process');
		$azapp->add_js($js);

		$modal_detail = $azapp->add_modal();
		$modal_detail->set_id('detail');
		$modal_detail->set_modal_title(azlang('Detail'));
		$modal_detail->set_modal('');
		$azapp->add_content($modal_detail->render());
		
		echo $azapp->render();
	}	      

	private function get_db_detail($id) {
		$id = az_decode_url($id);
		$this->db->where('dstb_process_detail.iddstb_process', $id);
		$this->db->join('transaction_group', 'dstb_process_detail.idtransaction_group = transaction_group.idtransaction_group');
		$this->db->join('outlet', 'transaction_group.idoutlet = outlet.idoutlet');
		$this->db->join('customer', 'transaction_group.idcustomer = customer.idcustomer');
		$this->db->join('dstb_process', 'dstb_process_detail.iddstb_process = dstb_process.iddstb_process');
		$this->db->join('user cashier', 'dstb_process.idcashier = cashier.iduser', 'left');
		$this->db->join('user driver', 'dstb_process.iddriver = driver.iduser', 'left');
		$this->db->join('user production', 'dstb_process.idproduction = production.iduser', 'left');		
		$this->db->where('transaction_group.status', 1);
		$this->db->select('*, cashier.name as cashier_name, driver.name as driver_name, production.name as production_name, dstb_process.total_pcs as total_pcs_dstb, transaction_group.total_pcs');
		$data = $this->db->get('dstb_process_detail');

		return $data;
	}

	function print_detail() {
		$id = $this->input->get('id');
		$type = $this->input->get('type');

		$data['page_type'] = $type;

		$data['data'] = $this->get_db_detail($id);

		$this->load->view('dstb_process/v_print_dstb_detail', $data);

	}

	function qr($id) {
		$id = az_decode_url($id);

		$this->db->where('iddstb_process', $id);
		$this->db->join('user cashier', 'dstb_process.idcashier = cashier.iduser', 'left');
		$this->db->join('user driver', 'dstb_process.iddriver = driver.iduser', 'left');
		$this->db->join('user production', 'dstb_process.idproduction = production.iduser', 'left');		
		$this->db->join('outlet', 'dstb_process.idoutlet = outlet.idoutlet');
		$this->db->select('*, cashier.name as cashier_name, driver.name as driver_name, production.name as production_name');
		$data['data'] = $this->db->get('dstb_process')->row();

		$this->load->view('dstb_process/v_qr', $data);
	}

	function remove_list() {
	    $err_code = 0;
	    $err_message = '';
	
	    $id = $this->input->post('id');
	    $id = az_decode_url($id);

	    $this->db->where('iddstb_process_detail', $id);
	    $old_data = $this->db->get('dstb_process_detail');

	    $iddstb_process = $old_data->row()->iddstb_process;

	    $this->db->where('iddstb_process_detail', $id);
	    $this->db->delete('dstb_process_detail');


	    $this->db->where("iddstb_process", $iddstb_process);
	    $arr_bill = $this->db->get('dstb_process_detail');
	    $total_bill = $arr_bill->num_rows();

    	$total_pcs = 0;
    	foreach ($arr_bill->result() as $key => $value) {
    		$this->db->where('idtransaction_group', $value->idtransaction_group);
    		$tg = $this->db->get('transaction_group');
    		if ($tg->num_rows() > 0) {
    			$tg_pcs = $tg->row()->total_pcs;
    			$total_pcs += $tg_pcs;
    		}
    	}

    	$arr_tot = array(
    		'total_bill' => $total_bill,
    		'total_pcs' => $total_pcs
    	);
    	$this->db->where('iddstb_process', $iddstb_process);
    	$this->db->update('dstb_process', $arr_tot);
	
	    $return = array(
	        'err_code' => $err_code,
	        'err_message' => $err_message
	    );
	
	    echo json_encode($return);
	}
	
	function scan_data() {
	    $err_code = 0;
	    $err_message = '';
		
		$code = $this->input->post('code');
		$type = $this->input->post('type');

		$this->db->where('code', $code);
		$this->db->where('status', 1);
		$tg = $this->db->get('transaction_group');	    
		if ($tg->num_rows() == 0) {
			$err_code++;
			$err_message = 'Data tidak ditemukan';
		}
		else {
			$arr_tg = array();
			if ($type == 'driver') {
				$arr_tg['dstb_status'] = 'DIJEMPUT';
			}
			else if ($type == 'production') {
				$arr_tg['dstb_status'] = 'DIPROSES';
			}

			$idtransaction_group = $tg->row()->idtransaction_group;
			$this->db->where('idtransaction_group', $idtransaction_group);
			$this->db->update('transaction_group', $arr_tg);
		}
	
	    $return = array(
	        'err_code' => $err_code,
	        'err_message' => $err_message
	    );
	
	    echo json_encode($return);
	}
	      
	function verif_driver() {
	    $err_code = 0;
	    $err_message = '';
	
	    $id = $this->input->post('id');
	    $id = az_decode_url($id);

	    $type = $this->session->userdata('role_name');

	    $this->db->where('iddstb_process', $id);
	    $this->db->join('transaction_group', 'dstb_process_detail.idtransaction_group = transaction_group.idtransaction_group');
	    if ($type == 'driver') {
	    	$this->db->where('dstb_status !=', 'DIJEMPUT');
	    }
	    else if ($type == 'production') {
	    	$this->db->where('dstb_status !=', 'DIPROSES');
	    }
	    $this->db->where('transaction_group.status', 1);

	    $data = $this->db->get('dstb_process_detail');
	    if ($data->num_rows() > 0) {
	    	$err_code++;
	    	$err_message = 'Terdapat data yang belum diverifikasi';
	    }

	    if ($err_code == 0) {
	    	if ($type == 'driver') {
		    	$arr_up = array(
		    		'dstb_process_status' => 'DIJEMPUT',
		    		'tgl_dijemput' => Date("Y-m-d H:i:s")
		    	);	    		
	    	}
	    	else if ($type == 'production') {
	    		$arr_up = array(
	    			'dstb_process_status' => 'DIPROSES',
		    		'tgl_diproses' => Date("Y-m-d H:i:s")
	    		);
	    	}
	    	$this->db->where('iddstb_process', $id);
	    	$this->db->update('dstb_process', $arr_up);
	    }
	
	    $return = array(
	        'err_code' => $err_code,
	        'err_message' => $err_message
	    );
	
	    echo json_encode($return);
	}
	      
	public function delete() {
		$id = $this->input->post("id");
		az_crud_delete('dstb_process', $id);

		$this->db->where_in('iddstb_process', $id);
		$data = $this->db->get('dstb_process_detail');
		foreach ($data->result() as $key => $value) {
			$arr_update = array(
				'dstb_status' => 'BARU'
			);
			$this->db->where('idtransaction_group', $value->idtransaction_group);
			$this->db->update('transaction_group', $arr_update);
		}

		$this->db->where_in('iddstb_process', $id);
		$this->db->delete('dstb_process_detail');
	}

	function scan($code) {
		$this->db->where('dstb_code', $code);
		$this->db->where('status', 1);
		$data = $this->db->get('dstb_process');

		if ($data->num_rows() == 0) {
			redirect(app_url().'dstb_process');
		}
		else {
			redirect(app_url().'dstb_process/detail/'.az_encode_url($data->row()->iddstb_process));
		}
	}
}