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

/*	
 *	Author 	: Tagor
 *	Tanggal : 05-08-2014	
 *	Revisi 	: Fachri
 */ 

class Daily_production extends CI_Controller {
	// inisialisasi manual
	public $menu_id 	= 257;
	public $code 		= "Batch Number";
	public $name 		= "Batch Description";
	public $trans_data 	= array();
	
    public function __construct() {
        parent::__construct();
		$this->load->helper('message');	
		$this->load->helper('status');			
		$this->load->helper('convert_date');
		$this->load->helper('approval');
		
		$this->load->model('m_menu');
		$this->load->model('m_production');
		$this->load->model('m_items');
		$this->load->model('m_inventories');
		$this->load->model('m_delivery_order');	
	}
	
	//Function Index
    public function index()	{	
		if ($this->session->userdata("login") == TRUE) { 
            $group_menu             = $this->session->userdata('group_menu');
            $arr_group_id           = $this->m_menu->get_menu_by_group($group_menu, $this->menu_id);
            if(!empty($arr_group_id)){
				$data['available_menu'] = array_unique($arr_group_id);
				if(!in_array($this->menu_id, $data['available_menu'])) { 
					redirect(base_url() . 'error', 'refresh');	
				}
				else{
					//untuk ambil data dari session dan hak akses
					$group_menu 		= $this->session->userdata('group_menu');
					
					// set data
					$data['menu_id'] =  $this->menu_id;

					// get link from tbl_menu 
					$data['menu_label'] =  $this->m_menu->get_menulabel($this->menu_id);
					$data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
					
					//panggil model hak akses untuk autoriti
					$data['group_user'] = $this->m_menu->group_user_autority($this->menu_id, $group_menu);
					
					$this->load->view('v_header');
					$this->load->view('daily_production/v_daily_production', $data);	
					$this->load->view('v_footer');
				}
			}
			else{
				redirect(base_url() . 'error', 'refresh');
			}
        }
        else {
            redirect(base_url() . 'login', 'refresh');
        }
	}
	
	 //Functiom Add Form
    public function add(){
		if ($this->session->userdata("login") == TRUE) { 
            $group_menu             = $this->session->userdata('group_menu');
			/*
				untuk di index/list = get_menu_by_group, 
				untuk di add = get_menu_by_group_add
				untuk di edit = get_menu_by_group_edit
			*/
            $arr_group_id           = $this->m_menu->get_menu_by_group_add($group_menu, $this->menu_id);
			//--------------------------end-----------------------------------------------------------
            if(!empty($arr_group_id)){
				$data['available_menu'] = array_unique($arr_group_id);
				if(!in_array($this->menu_id, $data['available_menu'])) { 
					redirect(base_url() . 'error', 'refresh');	
				}
				else{
					/*
						modul untuk akses add masing masing modul berebda 
						jangan lupa copy $data nya (jika dia bener langsung ke add)
					*/
					//untuk ambil data dari session dan hak akses
					$group_menu 		= $this->session->userdata('group_menu');
					
					// set data
					$data['date_now'] =  date('d-m-Y');
					$data['menu_id'] =  $this->menu_id;

					// get link from tbl_menu 
					$data['menu_label'] =  $this->m_menu->get_menulabel($this->menu_id);
					$data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
					
					//panggil model hak akses untuk autoriti
					$data['group_user'] = $this->m_menu->group_user_autority($this->menu_id, $group_menu);
					
					$data['Prod_number']=$this->m_production->create_preq_number();
					
					$this->load->view('v_header');
					$this->load->view('daily_production/v_new_daily_production', $data);	
					$this->load->view('v_footer');
				}
			}
			else{
				redirect(base_url() . 'error', 'refresh');
			}
        }
        else {
            redirect(base_url() . 'login', 'refresh');
        }	
    }
	
	//Function Form Insert
	public function insert() {
		$detail 			= $this->input->post('detail');
		$txt_batch_no		= $this->input->post('txt_Prod_no');
		$txt_date			= $this->input->post('txt_date');
		$txa_description	= $this->input->post('txa_description');
		$detail 			= json_decode($detail);
	
		$data 				= array (
			'BranchCode'	=> $this->session->userdata('branch'),
			'BranchFor'		=> $this->session->userdata('branch'),
			'ProdNumber' 	=> $txt_batch_no,
			'ProdDate' 		=> date("Y-m-d", strtotime($txt_date)),		
			'ProdDesc' 		=> $txa_description,
			'TransStatus'	=> 6,
			'LastUser' 		=> $this->session->userdata("username")
		);

        /*================= insert daily production ========================*/       
		//$this->m_production->insert($data);
		$this->trans_data['insert_group']['data'] = $data;
		
		if($detail > 0) {  
			
			foreach($detail as $row) {			
				$jurnal_amount = 0;
				
				$detail_data = array(
					'ProdNumber' 	=> $txt_batch_no,
					'ItemCode' 		=> $row->ItemCode,
					'itemUnit'		=> $row->ItemUnit,
					'itemQty'		=> $row->ItemQty,
					'itemDesc'		=> $row->Description,
					//'ItemWHTypeID'	=> $row->warehouse_id,
					'LastUser' 		=> $this->session->userdata("username")				
				);             
				
				//$result_insert = $this->m_production->insert_detail($detail_data);
				//if($result_insert == 0) {$this->trans_rollback('insert');}
				$this->trans_data['insert_detail']['data'][] = $detail_data;
				
				$category_temp = $this->m_items->get_category_by_item($row->ItemCode);
				
				// get item average dari inventories
//				$amount_temp = $this->m_inventories->get_item_hpp($row->ItemCode);
//				$tmp_jurnal_amount = doubleval($amount_temp) * 0;
//				$jurnal_amount = doubleval($jurnal_amount) + doubleval($tmp_jurnal_amount);
				@$CategoryAmount[$category_temp] += $jurnal_amount;
			}
			
			//if($CategoryAmount != "") {	
				// insert ke jurnal
				$total = 0;
				foreach ($CategoryAmount as $key => $value) {
					$CogsdAccount = $this->m_delivery_order->get_item_account('COGS',$key);
					echo $this->db->last_query();
					die();
					$InventoryAccount = $this->m_delivery_order->get_item_account('Inventory',$key);
					
					if($CogsdAccount == false || $InventoryAccount == false){
						$result_insert = 0;
                    	$this->trans_rollback('journal');
					}
					else{ 
						$data_journal_credit = array(
							'ProdDate' 			=> date("Y-m-d", strtotime($txt_date)),
							'ProdNumber' 		=> $txt_batch_no,
							'ProdAccountNumber'	=> $InventoryAccount->AccountNumber,
							'ProdSaldoDebet' 	=> 0,
							'ProdSaldoCredit' 	=> $value,
							'ProdSignStatus' 	=> 1,
							'LastUser' 			=> $this->session->userdata('username')
						);
						
						//$result_insert = $this->m_production->insert_journal_credit($data_journal_credit);
						//if($result_insert == 0) {$this->trans_rollback('insert');}
						$this->trans_data['insert_journal']['data'][] = $data_journal_credit;
                                                
                      	$data_journal_debit = array(
							'ProdDate' 			=> date("Y-m-d", strtotime($txt_date)),
							'ProdNumber' 		=> $txt_batch_no,
							'ProdAccountNumber'	=> $CogsdAccount->AccountNumber, 
							'ProdSaldoDebet' 	=> $value,
							'ProdSaldoCredit' 	=> 0,
							'ProdSignStatus' 	=> 0,
							'LastUser' 			=> $this->session->userdata('username')
						);
						
						$total = $total + $value;
						//$result_insert = $this->m_production->insert_journal_debet($data_journal_debit);
						//if($result_insert == 0) {$this->trans_rollback('insert');}
						$this->trans_data['insert_journal']['data'][] = $data_journal_debit;
					}
				}
			//}
						
			$result_return 		= $this->m_production->insert_transsaction($this->trans_data);

			$this->trans_data 	= [];

			if($result_return){
				$result['status'] 	= true;
				$result['message']	= get_notification_transaksi($this->name,'insert',1,$txt_batch_no);
			}else{
				$result['status'] 	= false;
				$result['message']	= get_notification_transaksi($this->name,'insert',0,$txt_batch_no);
			}

			echo json_encode($result);
		}
		else {
			$result['status'] = false;
			$result['message'] = msg_qty_not_nol();
			echo json_encode($result);
		}
	}
	
	//Function Form Edit
	public function edit(){
		if ($this->session->userdata("login") == TRUE) { 
            $group_menu             = $this->session->userdata('group_menu');
			/*
				untuk di index/list = get_menu_by_group, 
				untuk di add = get_menu_by_group_add
				untuk di edit = get_menu_by_group_edit
			*/
            $arr_group_id           = $this->m_menu->get_menu_by_group_edit($group_menu, $this->menu_id);
			//--------------------------end-----------------------------------------------------------
            if(!empty($arr_group_id)){
				$data['available_menu'] = array_unique($arr_group_id);
				if(!in_array($this->menu_id, $data['available_menu'])) { 
					redirect(base_url() . 'error', 'refresh');	
				}
				else{
					/*
						modul untuk akses add masing masing modul berebda 
						jangan lupa copy $data nya (jika dia bener langsung ke add)
					*/
					//untuk ambil data dari session dan hak akses
					$group_menu 		= $this->session->userdata('group_menu');
					
					// set data
					$data['menu_id'] =  $this->menu_id;
					
					// get link from tbl_menu 
					$data['menu_label'] =  $this->m_menu->get_menulabel($this->menu_id);
					$data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
					
					// inisialisasi additional parameter
					$id = str_replace($data['menu_link'].'/edit/',"",$this->uri->uri_string());
					$data['detail'] = $this->m_production->get_detail($id);
					
					//panggil model hak akses untuk autoriti
					$data['group_user'] = $this->m_menu->group_user_autority($this->menu_id, $group_menu);
					
					if($data['detail'] != false){
						// set for view
						$this->load->view('v_header');
						$this->load->view('daily_production/v_edit_daily_production',$data);
						$this->load->view('v_footer');
					}
				}
			}
			else{
				redirect(base_url() . 'error', 'refresh');
			}
        }
        else {
            redirect(base_url() . 'login', 'refresh');
        }
	}
	
	// Function Update
	public function update() {
		$id 				= $this->input->post('id');
		$txt_date			= $this->input->post('txt_date');
		$txa_description	= $this->input->post('txa_description');
		$result_update = 0;
		$txt_batch_no		= $this->input->post('txt_Prod_no');
		$detail = $this->input->post('detail');
		
		$chk_suspended = $this->input->post('chk_suspended');
		if($chk_suspended == 1) { 
			$TransStatus = 3; 
		} 
		else { 
			$TransStatus = $this->m_production->get_transstatus($id);
		}
		
		$data = array (
			'ProdDate' 		=> date("Y-m-d", strtotime($txt_date)),		
			'ProdDesc' 		=> $txa_description,
			'TransStatus' 	=> $TransStatus,
			'LastUser' 		=> $this->session->userdata("username")
		);
		
		
		//$result_update = $this->m_production->update($data, $id);
		//if($result_update == 0) {$this->trans_rollback('update');}
		$this->trans_data['update_group']['data'] 			= $data;
		$this->trans_data['update_group']['TransNumber'] 	= $id;
		
		//$result_update = $this->m_production->delete_journal($id);
		//if($result_update == 0) {$this->trans_rollback('update');}
		$this->trans_data['delete_journal']['TransNumber'] = $id;
					
		//$result_update = $this->m_production->delete_detail_grid_2($id);
		//if($result_update == 0) {$this->trans_rollback('update');}
		$this->trans_data['delete_detail']['TransNumber'] = $id;
							
		$detail = json_decode($detail);
		if($detail > 0) { 
			foreach($detail as $row){
				$jurnal_amount = 0;
		
				$detail_data = array(
					'ProdNumber' 	=> $id,
					'ItemCode' 		=> $row->ItemCode,
					'itemUnit'		=> $row->ItemUnit,
					'itemQty'		=> $row->ItemQty,
					'itemDesc'		=> $row->ItemDesc,
					'LastUser' 		=> $this->session->userdata("username")				
				);             
				
				//$result_update = $this->m_production->insert_detail($detail_data);
				//if($result_update == 0) {$this->trans_rollback('update');}
				$this->trans_data['insert_detail']['data'][] = $detail_data;
				
				$category_temp = $this->m_items->get_category_by_item($row->ItemCode);
				
				// get item average dari inventories
				$amount_temp = $this->m_inventories->get_item_hpp($row->ItemCode);
				$tmp_jurnal_amount = doubleval($amount_temp) * 0;
				$jurnal_amount = doubleval($jurnal_amount) + doubleval($tmp_jurnal_amount);
				@$CategoryAmount[$category_temp] += $jurnal_amount;
			}
			
			foreach ($CategoryAmount as $key => $value) {
				$CogsdAccount = $this->m_delivery_order->get_item_account('COGS',$key);
				$InventoryAccount = $this->m_delivery_order->get_item_account('Inventory',$key);
				
				if($CogsdAccount == false || $InventoryAccount == false){
					$result_update = 0;
                    $this->trans_rollback('journal');
				}
				else{ 
					$data_journal_debit = array(
						'ProdDate' 			=> date("Y-m-d", strtotime($txt_date)),
						'ProdNumber' 		=> $txt_batch_no,
						'ProdAccountNumber'	=> $CogsdAccount->AccountNumber, 
						'ProdSaldoDebet' 	=> $value,
						'ProdSaldoCredit' 	=> 0,
						'ProdSignStatus' 	=> 0,
						'LastUser' 			=> $this->session->userdata('username')
					);
					
					//$result_update = $this->m_production->insert_journal_debet($data_journal_debit);
					//if($result_update == 0) {$this->trans_rollback('update');}
					$this->trans_data['insert_journal']['data'][] = $data_journal_debit;
					
					$data_journal_credit = array(
						'ProdDate' 			=> date("Y-m-d", strtotime($txt_date)),
						'ProdNumber' 		=> $txt_batch_no,
						'ProdAccountNumber'	=> $InventoryAccount->AccountNumber,
						'ProdSaldoDebet' 	=> 0,
						'ProdSaldoCredit' 	=> $value,
						'ProdSignStatus' 	=> 1,
						'LastUser' 			=> $this->session->userdata('username')
					);
					
					//$result_update = $this->m_production->insert_journal_credit($data_journal_credit);
					//if($result_update == 0) {$this->trans_rollback('update');}
					$this->trans_data['insert_journal']['data'][] = $data_journal_credit;
				}
			}
				
			$result_return = $this->m_production->update_transsaction($this->trans_data);

			$this->trans_data = [];

			if($result_return){
				$result['status'] 	= true;
				$result['message']	= get_notification_transaksi($this->name,'update',1,$txt_batch_no);
			}else{
				$result['status']	= false;
				$result['message']	= get_notification_transaksi($this->name,'update',0,$txt_batch_no);
			}

			echo json_encode($result);
		}
		else {
			$result['status'] = false;
			$result['message'] = msg_qty_not_nol();
		}	
		echo json_encode($result);
	}
	
	public function delete_row() {
		$id 				= $this->input->post('id');
		$txt_date			= $this->input->post('txt_date');
		$txa_description	= $this->input->post('txa_description');
		$result_update = 0;
		$txt_batch_no		= $this->input->post('txt_Prod_no');
		
		$detail = $this->input->post('detail');
		$detail = json_decode($detail);
		
			$this->db->trans_begin();
			foreach($detail as $row){
				$jurnal_amount = 0;
				 if ($row->Modus_Type == 3) {
					$result_update = $this->m_production->delete_detail_grid($row->ProdDetailID);
					if($result_update == 0) {$this->trans_rollback('update');}
				 }
				 else{
				 	$category_temp = $this->m_items->get_category_by_item($row->ItemCode);
				
					// get item average dari inventories
					$amount_temp = $this->m_inventories->get_item_hpp($row->ItemCode);
					$tmp_jurnal_amount = doubleval($amount_temp) * 0;
					$jurnal_amount = doubleval($jurnal_amount) + doubleval($tmp_jurnal_amount);
					@$CategoryAmount[$category_temp] += $jurnal_amount;
					
					$result_update = $this->m_production->delete_journal($id);
					if($result_update == 0) {$this->trans_rollback('update');}
				 }
			}
			
			$total = 0;
			foreach ($CategoryAmount as $key => $value) {
				$CogsdAccount = $this->m_delivery_order->get_item_account('COGS',$key);
				$InventoryAccount = $this->m_delivery_order->get_item_account('Inventory',$key);
				
				if($CogsdAccount == false || $InventoryAccount == false){
					$result_update = 0;
                    $this->trans_rollback('journal');
				}
				else{ 
					$akun_inventori = $InventoryAccount->AccountNumber;
					$COGS = $CogsdAccount->AccountNumber;
		
					$data_journal_debit = array(
						'ProdDate' 			=> date("Y-m-d", strtotime($txt_date)),
						'ProdNumber' 		=> $txt_batch_no,
						'ProdAccountNumber'	=> $CogsdAccount->AccountNumber, 
						'ProdSaldoDebet' 	=> $value,
						'ProdSaldoCredit' 	=> 0,
						'ProdSignStatus' 	=> 0,
						'LastUser' 			=> $this->session->userdata('username')
					);
					
					$result_update = $this->m_production->insert_journal_debet($data_journal_debit);
					if($result_update == 0) {$this->trans_rollback('update');}
					
					$data_journal_credit = array(
						'ProdDate' 			=> date("Y-m-d", strtotime($txt_date)),
						'ProdNumber' 		=> $txt_batch_no,
						'ProdAccountNumber'	=> $InventoryAccount->AccountNumber,
						'ProdSaldoDebet' 	=> 0,
						'ProdSaldoCredit' 	=> $value,
						'ProdSignStatus' 	=> 1,
						'LastUser' 			=> $this->session->userdata('username')
					);
					
					$result_update = $this->m_production->insert_journal_credit($data_journal_credit);
					if($result_update == 0) {$this->trans_rollback('update');}
				}
			}
				
			if($result_update == 0) {
				$this->db->trans_rollback();
				$result['status'] = false;
				$result['message'] = get_notification('update', 0);
			}
			else {
				$this->db->trans_commit();
				$result['status'] = true;
				$result['message'] = get_notification('update', 1);
			}		
		
		echo json_encode($result);
	}
	
	public function suspend_data() {
		// inisialisasi additional parameter
        $id = $this->input->post('id');
		$result_trans = 0;
		$TransStatus = $this->m_production->get_transstatus($id);
		
		$this->db->trans_begin();
		
		$result_trans = $this->m_production->set_trans_status($id, 3);
		if($result_trans == 0) {$this->trans_rollback('update');}	
		
		if($result_trans == 0){
			$this->db->trans_rollback();
			$result['status'] = false;
			$result['message'] = get_notification('Data gagal', 0);
		}
		else{
			$this->db->trans_commit();
			$result['status'] = true;
			$result['message'] = get_notification('Data berhasil', 1);
		}	
		
		echo json_encode($result);		
	}
	
	// Function Approval Direksi
	public function approval_dir() {
		$id = $this->input->post('id');
		$detail = $this->input->post('detail');	
		$branch = $this->input->post('branch_code');
		
		$detail = json_decode($detail);
		foreach($detail as $row_data){
			$get_inventori_code = $this->m_production->get_inventori_by_item($row_data->ItemCode, $branch);
			
			if(!empty($get_inventori_code->ItemCode)){
				if($get_inventori_code->LockStatus == 1){
					$this->db->trans_rollback();
					$result['status']   = false;
					$result['message']  = "Masi Ada Item Yang Di Adjustment, Silhakan Lihat kembali";
					
					echo json_encode($result);
					die();
				}
			}
			
		}
		
		$result_approv_dir = 0;			
		$data = array (				
			'AppLevel2Status' 	=> 1,
			'AppFinished' 		=> 1,
			'AppLevel2Code'     => $this->session->userdata("username"),
			'AppLevel2Date'		=> date("Y-m-d"),	
			'LastUser' 			=> $this->session->userdata("username")
		);
		
		$this->db->trans_begin();
		
		$result_approv_dir = $this->m_production->update($data, $id);
		if($result_approv_dir == 0) {$this->trans_rollback('update');}
		
		if($this->m_production->get_transstatus($id) == 4){
			$trans_status		= 2;
		}
		else{
			$trans_status		= 5;
		}
		$result_approv_dir = $this->m_production->set_trans_status($id, $trans_status);
		if($result_approv_dir == 0) {$this->trans_rollback('update');}
		
		if($this->m_production->get_transstatus($id) == 2){	
			if($detail){
				foreach($detail as $row){
					$kode_item = $row->ItemCode;
					$item_qty = $row->ItemQty;
					
					$row_inventoris = $this->m_production->get_inventori_by_item($row->ItemCode, $branch);
				
					if(empty($row_inventoris->ItemCode)){
						$insert_data = array(
							'ItemCode' 		=> $kode_item,
							'BranchCode' 	=> $this->session->userdata("branch"),
							'ItemQty' 		=> $item_qty ,
							'ItemValue' 	=> 0,
							'ItemAverage' 	=> 0,
							'LastUser' 		=> $this->session->userdata("username")
						);
						
						$result_approv_dir = $this->m_production->insert_inventori($insert_data);
						if($result_approv_dir == 0) {$this->trans_rollback('update');}
					}
					else{
						$ItemQty_Inv 	= $row_inventoris->ItemQty;
						$ItemAverage_Inv 	= $row_inventoris->ItemAverage;
						$ItemValue_Inv 	= $row_inventoris->ItemValue;
					
						$total 		= $ItemAverage_Inv * ($item_qty + $ItemQty_Inv);
						$Nilai 		= $total + $ItemValue_Inv;
						$Total_Qty 	= $ItemQty_Inv + $item_qty;
						$Average 	= $total / $Total_Qty;
						
						$update_invetoris = array(
							'ItemQty' 		=> $Total_Qty,
							//'ItemAverage' 		=> $ItemAverage_Inv,
							'ItemValue' 	=> $total,
							'ItemAverage' 	=> $Average
						);
						
						$result_approv_dir = $this->m_production->update_inventories($update_invetoris, $kode_item, $branch);
						if($result_approv_dir == 0) {$this->trans_rollback('update');}
					}
					
				}
			}
		
		}
			
		if($result_approv_dir == 0) {
			$this->db->trans_rollback();
			$result['status'] = false;
			$result['message'] = 'Approval Gagal';
		}
		else {
			$this->db->trans_commit();
			$result['status'] = true;
			$result['message'] = 'Approval Berhasil';
		}					
		
		echo json_encode($result);
	}
	
	// Function Approval Manager
	public function approval_mgr() {
		$id 	= $this->input->post('id');
		$detail = $this->input->post('detail');	
		$branch = $this->input->post('branch_code');	
		
		$detail = json_decode($detail);
		foreach($detail as $row_data){
			$get_inventori_code = $this->m_production->get_inventori_by_item($row_data->ItemCode, $branch);
			
			if(!empty($get_inventori_code->ItemCode)){
				if($get_inventori_code->LockStatus == 1){
					$this->db->trans_rollback();
					$result['status']   = false;
					$result['message']  = "Masi Ada Item Yang Di Adjustment, Silhakan Lihat kembali";
					
					echo json_encode($result);
					die();
				}
			}
			
		}
					
		$txt_date = $this->m_production->get_date_by_id($id);
		$result_approv_mgr = 0;
		$data = array (				
			'AppLevel1Status' 	=> 1,
			'AppFinished' 		=> 1,
			'AppLevel1Code'     => $this->session->userdata("username"),
			'AppLevel1Date'		=> date("Y-m-d"),	
			'LastUser' 			=> $this->session->userdata("username")
		);
		
		$this->db->trans_begin();
		
		$result_approv_mgr = $this->m_production->update($data, $id);
		if($result_approv_mgr == 0) {$this->trans_rollback('update');}
		
		if($this->m_production->get_transstatus($id) == 5){
			$trans_status		= 2;
		}
		else{
			$trans_status		= 4;
		}
		$result_approv_mgr = $this->m_production->set_trans_status($id, $trans_status);
		if($result_approv_mgr == 0) {$this->trans_rollback('update');}
		
		if($this->m_production->get_transstatus($id) == 2){	
		if($detail){
			foreach($detail as $row){
				$kode_item = $row->ItemCode;
				$item_qty = $row->ItemQty;
				
				$row_inventoris = $this->m_production->get_inventori_by_item($row->ItemCode, $branch);
				
				if(empty($row_inventoris->ItemCode)){
					$insert_data = array(
						'ItemCode' 		=> $kode_item,
						'BranchCode' 	=> $this->session->userdata("branch"),
						'ItemQty' 		=> $item_qty ,
						'ItemValue' 	=> 0,
						'ItemAverage' 	=> 0,
						'LastUser' 		=> $this->session->userdata("username")
					);
					
					$result_approv_dir = $this->m_production->insert_inventori($insert_data);
					if($result_approv_dir == 0) {$this->trans_rollback('update');}
				}
				else{
					$ItemQty_Inv 	= $row_inventoris->ItemQty;
					$ItemAverage_Inv 	= $row_inventoris->ItemAverage;
					$ItemValue_Inv 	= $row_inventoris->ItemValue;
					
					$total 		= $ItemAverage_Inv * ($item_qty + $ItemQty_Inv);
					$Nilai 		= $total + $ItemValue_Inv;
					$Total_Qty 	= $ItemQty_Inv + $item_qty;
					$Average 	= $total / $Total_Qty;
				
					$update_invetoris = array(
						'ItemQty' 		=> $Total_Qty,
						//'ItemAverage' 		=> $ItemAverage_Inv,
						'ItemValue' 	=> $total,
						'ItemAverage' 	=> $Average
					);
							
					$result_approv_dir = $this->m_production->update_inventories($update_invetoris, $kode_item, $branch);
					if($result_approv_dir == 0) {$this->trans_rollback('update');}
				}
			}
		}
			
		}
		
		if($result_approv_mgr == 0) {
			$this->db->trans_rollback();
			$result['status'] = false;
			$result['message'] = 'Approval Gagal';
		}
		else {
			$this->db->trans_commit();
			$result['status'] = true;
			$result['message'] = 'Approval Berhasil';
		}					
		
		echo json_encode($result);
	}
	
	//Function preview data
    public function to_preview(){
        // set data
        $data['menu_id'] =  $this->menu_id;
        $data['menu_label'] =  $this->m_menu->get_menulabel($this->menu_id);
        $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
		
        $data['list'] = $this->m_production->get_all();              
                
        $this->load->view('v_header');
        $this->load->view('daily_production/v_preview_daily_production', $data);
        $this->load->view('v_footer');	
    }
	
	//Function To Print
	public function to_print(){	
		 // set data
		$data['menu_id'] =  $this->menu_id;
		$data['menu_label'] =  $this->m_menu->get_menulabel($this->menu_id);
		
		$data['list'] = $this->m_production->get_all();
		
		$this->load->view('v_header');
		$this->load->view('daily_production/v_print_daily_production', $data);
		$this->load->view('v_footer');	
	}
	
	function to_print_journal(){	
	    $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
		$data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);
		
		// set data	 
		$id = str_replace($data['menu_link'].'/to_print_journal/',"",$this->uri->uri_string());
		$data['detail'] = $this->m_production->get_detail($id);
		$data['list']   = $this->m_production->get_journal_by_number($id);		
		$this->load->view('v_header');
		$this->load->view('daily_production/v_print_journal_dailyproduction',$data);	
		$this->load->view('v_footer');	
	}
	
	function to_preview_journal(){	
	    $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
		$data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);
		
		// set data 
		$id = str_replace($data['menu_link'].'/to_preview_journal/',"",$this->uri->uri_string());
		$data['detail'] = $this->m_production->get_detail($id);
		$data['list']   = $this->m_production->get_journal_by_number($id);		
		$this->load->view('v_header');
		$this->load->view('daily_production/v_preview_journal_dailyproduction',$data);	
		$this->load->view('v_footer');	
	}
	
    public function ajax(){
		$page	= ($this->input->post('page')) ? intval($this->input->post('page')) : 1;
		$rows	= ($this->input->post('rows')) ? intval($this->input->post('rows')) : 150;
		
		$hasil = array();
		/*===========rows*page tidak boleh melebihi dari jumlah data======= */
		
		/*=================================post dari find di kiri====================================================*/
		$param 			= $this->input->post('param');
		$Number			= isset($param['txt_IDNumber']) ? $param['txt_IDNumber'] : ''; 
		$Desc			= isset($param['txt_Description']) ? $param['txt_Description'] : ''; 
		
		$DateFrom		= isset($param['txt_DateFrom']) ? $param['txt_DateFrom'] : '';
		$DateTo			= isset($param['txt_DateTo']) ? $param['txt_DateTo'] : '';
		$TransStatus	= isset($param['chk_TransStatus']) ? $param['chk_TransStatus'] : '';
		$BranchCode		= isset($param['cmb_branch']) ? $param['cmb_branch'] : '';
		/*============================================end============================================================*/
		/*========================jika kondisi tidak sama dengan kosong di find lakukan proses di if=================*/
		if($BranchCode != ""){
			$this->db->where('BranchCode', $BranchCode);
		}
		else{
			$this->db->where('BranchCode', $this->session->userdata('branch'));
		}
		
		if($Number != ""){$this->db->like('ProdNumber', $Number);}
		if($Desc != ""){$this->db->like('ProdDesc', $Desc);} 
		if($TransStatus!=''){ 
			$this->db->where_in('TransStatus', $TransStatus);
		}
		else{
			/*
				default adalah 2,6. Finished dan Need Approval
			*/
			$this->db->where_in('TransStatus',array(2,6)); 
		}
		
		
		if((($DateFrom != '') && ($DateTo != ''))){
            if($DateFrom <= $DateTo){
				$this->db->where('at_production.ProdDate >=', date("Y-m-d", strtotime($DateFrom)));
            	$this->db->where('at_production.ProdDate <=', date("Y-m-d", strtotime($DateTo)));
			}
        }
		/*==========================end=================================================================*/
		
		$count_data = $this->db->count_all_results('at_production');
		$offset 	= $count_data - ($rows * $page);
		if($offset > 0){
			$rows = $rows;
		}
		else{
			$rows = $count_data - ($rows*($page-1));
		}
		/*========================end=======================================*/
		$result = $this->m_production->get_all();
		
		for($i=0; $i<=($rows-1); $i++){
			// kalau master ambil dari get_status_master(), kalau transaksi get_status()
			$TransStatus = get_status($result[$i]->TransStatus);

            $hasil[] = array(
				'BranchName' 	=>	$result[$i]->BranchName, 
				'ProdNumber' 	=>	$result[$i]->ProdNumber, 
				'ProdDate' 		=>	$result[$i]->ProdDate,
				'ProdDesc' 		=>	$result[$i]->ProdDesc,
				'Status' 		=>	$TransStatus
			);
		}
		
		if(empty($hasil)){
			$emptyVar = array();
			echo json_encode($emptyVar);
		}
		else{
			$result = array();
			$result['total'] = $count_data;
			$result['rows'] = $hasil;
			echo json_encode($result);
		}
    }
	
	public function ajax_item(){		
		$uri4 = $this->uri->segment(4);
		
        $uri5 = $this->uri->segment(5);
        $uri6 = $this->uri->segment(6);
		$uri7 = $this->uri->segment(7);
		//$uri8 = $this->uri->segment(8);
		$id = $uri4."/".$uri5."/".$uri6;
		//$id = str_replace($data['menu_link'].'/ajax_item/',"",$this->uri->uri_string());
		
		$result = $this->m_production->get_detail_item($id, $uri7);
		
		foreach($result as $row) {
			$hasil[] = array(
				'ProdDetailID' => $row->ProdDetailID,
				'ProdNumber' => $row->ProdNumber,
				'ItemCode' => $row->ItemCode,
				'ItemQty' => $row->ItemQty,
				'ItemUnit' => $row->ItemUnit,
				'ItemDesc' => $row->ItemDesc,
				'Modus_Type' => $row->Modus_Type
				//'LockStatus' => $row->LockStatus
			); 
		}
		
		echo json_encode($hasil);	
	}
	
	public function trans_rollback($modus) {
        $this->db->trans_rollback();
        $result['status']   = false;

        if ($modus == 'journal') {
            $result['message'] = 'Pengaturan Preference Journal Template belum lengkap, silahkan atur ulang';
        }
        else{
            $result['message']  = get_notification_transaksi($this->name, $modus, 0);
        }
                
        echo json_encode($result);
        die();
    }
	
	function test() {
		//$get_inventory = $this->m_inventories->get_item('K00012');
		//echo json_encode($get_inventory);
		
		$detail = $this->m_production->get_detail_item('HO-IST/1114DP/001');
		echo json_encode($detail);
	} 
	
	 function item_kategori(){
        $data = $this->load->m_production->get_kategori();
        echo json_encode($data);

//        echo $this->db->last_query(); die();
    }
	
	function search_prod(){
		echo json_encode($this->m_production->search_prod());
    }
	
	public function get_prod_number(){
		$prod_date  = $this->input->post('prod_af_date') == '' ? date('d-m-Y') : $this->input->post('prod_af_date');
		
		$prod_no = $this->m_production->create_prod_number($prod_date);
        
		$result['status']   = true;
        $result['number']   = $prod_no;
		
        echo json_encode($result);
	}
}