<?php
/*	
 *	Author 	: Ladur
 *	Tanggal : 01-10-2014	
 *	Revisi 	: Fachri (Rombak Insert dan update)
 */
 
class M_production extends CI_Model {    
    // deklarasi nama table
    public $table = "at_production";
    public $detail = "at_proddetail";
    public $journal = "at_prodjournal";
	
    function get_all(){
		/*=========================lemparan parah dari custom.js untuk searching_data_transaksi=====================*/
		$param = $this->input->post('param');
		/*====================================end===================================================================*/
		
		/*=================================post dari find di kiri====================================================*/
		$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============================================================*/
		
		/*======================================scrol view 1-150=======================================*/
		$page		= ($this->input->post('page')) ? intval($this->input->post('page')) : 1;
		$rows		= ($this->input->post('rows')) ? intval($this->input->post('rows')) : 150;
		
		$beginning 	= ($page - 1) * $rows;
		$end 		= $page * $rows;
		/*==============================================================================================*/
		
		/*==========================================by session=======================================================*/
		$sess_company		= $this->session->userdata('company');
        $sess_branch		= $this->session->userdata('branch');
        $sess_branch_status	= $this->session->userdata('branch_status');
		/*===========================================================================================================*/
		
        $this->db->select("at_production.TransStatus, at_production.ProdNumber, at_production.ProdDesc, at_production.ProdDate, am_branch.BranchName");
        $this->db->from($this->table);
        $this->db->join('am_branch', 'am_branch.BranchCode = at_production.BranchCode', 'inner');
        
        
		/*===================================find by number dan desc=========================================================*/
		if($Number != ""){$this->db->like('at_production.ProdNumber', $Number);}
		if($Desc != ""){$this->db->like('at_production.ProdDesc', $Desc);}
		/*=============================================end===================================================================*/
		
		/*===================================find by branch code=========================================================*/
		/*
			get data dari  combobox find di view
		*/
        if($BranchCode != ""){
			$this->db->where('at_production.BranchCode', $BranchCode);
		}
		else{
			/*
				inisialisasi untuk loading pertama page branch info 
			*/
			//----------------kondisi by company-------------------------------------//
			/*
				branch status 0 = HO
				branch status 1 = depo/branch
				jangan lupa sesion data di atas untuk setiap kondisi
				jangan lupa tambahin case when trans status
			*/
			$this->db->where('at_production.BranchCode', $sess_branch);
			//-----------------------end-------------------------------------------------//
		}
		/*=======================================================end========================================================*/
		
		/*=====================================================find by date==================================================*/
		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===========================================================*/
		
		/*=====================================================find by status==================================================*/
		if($TransStatus!=''){ 
			$this->db->where_in('at_production.TransStatus',$TransStatus); 
		}
		else{
			/*
				trans status 0,1 adalah aktif
			*/
			$this->db->where_in('at_production.TransStatus',array(2,6)); 
		}
		/*=======================================================end========================================================*/
		
		/*==============================================sort tabel asc==========================================================*/
		$this->db->order_by($this->table.'.TransStatus', 'ASC');
		$this->db->order_by($this->table.'.ProdNumber', 'ASC');
		/*===============================end=================================================================================*/
		$query  = $this->db->limit($end, $beginning);
		$query = $this->db->get();
		return $query->result();
    }
	
	function get_detail($id){
        $query = $this->db->get_where($this->table, array('ProdNumber' => $id));
		if($query->num_rows()>0){
			return $query->row();
		}
		else{
			return false;
		}      
    }	
	
	function get_detail_item($ProdNumber, $branch_code){
		$this->db->_protect_identifiers = FALSE;
	    $this->db->select('at_proddetail.ProdDetailID, at_proddetail.ProdNumber, at_proddetail.ItemCode, at_proddetail.ItemQty, at_proddetail.ItemUnit, at_proddetail.ItemDesc, at_production.BranchCode, "0" as Modus_Type');
		$this->db->join('at_production', 'at_production.ProdNumber = at_proddetail.ProdNumber', 'inner');
		//$this->db->join('at_inventories', 'at_inventories.ItemCode = at_proddetail.ItemCode', 'inner');
		$this->db->where('at_proddetail.ProdNumber', $ProdNumber);
		$this->db->where('at_production.BranchCode', $branch_code);
		$query = $this->db->get('at_proddetail');
		$this->db->_protect_identifiers = TRUE;
        return $query->result();
    }
	
	function create_preq_number(){
	    //$company_code=$this->session->userdata('company');
		$branch_code=$this->session->userdata('branch');
	   	$month=date('m');
		$year=date('y');
	    $preq_number=$branch_code."/".$month.$year."DP/";
		$this->db->like('ProdNumber',$preq_number);
		$num=$this->db->get($this->table)->num_rows()+1;
		$long=strlen($num);
		if($long==1){
		   $number='00'.$num;
		}
		elseif($long==2){
		   $number='0'.$num;
		}
		else{
			$number=$num;
		}
		
		return  $preq_number.$number;
	}
	
	function create_prod_number($date){
	    //$company_code=$this->session->userdata('company');
		$branch_code=$this->session->userdata('branch');
	   	if($date != ''){
            $month  = date('m', strtotime($date));
            $year   = date('y', strtotime($date));
        }
        else{
            $month  = date('m');
            $year   = date('y');
        }
		
	    $preq_number=$branch_code."/".$month.$year."DP/";
		$this->db->like('ProdNumber',$preq_number);
		$num=$this->db->get($this->table)->num_rows()+1;
		$long=strlen($num);
		if($long==1){
		   $number='00'.$num;
		}
		elseif($long==2){
		   $number='0'.$num;
		}
		else{
			$number=$num;
		}
		
		return  $preq_number.$number;
	}
	
	function delete_detail_grid_2($id){
		$this->db->where('ProdNumber',$id);
  		$this->db->delete($this->detail); 
	}
	
	function delete_detail_grid($id){
		$this->db->where('ProdDetailID',$id);
  		$this->db->delete($this->detail); 
	}
	
	function delete_journal($id){
		$this->db->where('ProdNumber',$id);
  		$this->db->delete($this->journal); 
	}
	
	function delete_detail($data) {
		$this->db->delete($this->detail, $data);	
	}
	
	function insert($data) {
		$this->db->insert($this->table, $data);	
	}
	
	function insert_detail($data_detail) {		
		$this->db->insert($this->detail, $data_detail);
	}
	
	function insert_inventori($data_detail) {		
		$this->db->insert('at_inventories', $data_detail);	
	}
	
	function update($data,$id) {
		 $this->db->update($this->table, $data, array('ProdNumber' => $id));
	}
	
	function update_detail($data, $id) {
		 $this->db->update($this->detail, $data, array('ProdDetailID' => $id));	
	}
	
	function set_trans_status($id, $status) {
		$this->db->set('TransStatus', $status);
		$this->db->where('ProdNumber', $id);
		$this->db->update($this->table);
	}
	
	function get_transstatus($id) {
        $this->db->select('TransStatus');
		$this->db->from($this->table);
		$this->db->where('ProdNumber', $id); 
		$query = $this->db->get();    
        
		if ($query->num_rows() > 0) {
			foreach ($query->result() as $row) {
				$TransStatus = $row->TransStatus;
			}    

			return $TransStatus;
		}
		else {
			return FALSE;
		}	
    }
	
	function get_date_by_id($id) {
        $this->db->select('ProdDate');
		$this->db->from($this->table);
		$this->db->where('ProdNumber', $id); 
		$query = $this->db->get();    
        
		if ($query->num_rows() > 0) {
			foreach ($query->result() as $row) {
				$ProdDate = $row->ProdDate;
			}    

			return $ProdDate;
		}
		else {
			return FALSE;
		}	
    }
	
	function get_inventoris($kode_item,$branch){
	    $this->db->_protect_identifiers = FALSE;
	    $this->db->select('at_inventories.ItemQty, at_inventories.ItemAverage, at_inventories.ItemValue, at_inventories.ItemCode');
		$this->db->where('at_inventories.ItemCode', $kode_item);
		$this->db->where('at_inventories.BranchCode', $branch);
		$query = $this->db->get('at_inventories');
		$this->db->_protect_identifiers = TRUE;
        return $query->result();
    }
	
	function insert_journal_debet($data_journal_debit) {		
		$this->db->insert($this->journal, $data_journal_debit);	
		if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            return 0;
        }
        else {
            //$this->db->trans_commit();
            return 1;
        }	
	}
	
	function insert_journal_credit($data_journal_credit) {		
		$this->db->insert($this->journal, $data_journal_credit);
		if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            return 0;
        }
        else {
            //$this->db->trans_commit();
            return 1;
        }		
	}
	
	function update_inventories($update_invetoris, $id_invent, $branch_inven) {
		
		 $this->db->update('at_inventories', $update_invetoris, array('ItemCode' => $id_invent, 'BranchCode' => $branch_inven));
		 
		 if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            return 0;
        }
        else {
            //$this->db->trans_commit();
            return 1;
        }		
	}
	
	function get_journal_by_number($Number){
	    $this->db->_protect_identifiers = FALSE;
	    $this->db->select("at_prodjournal.*,am_accountgl.AccountNumber,am_accountgl.AccountName");
		$this->db->join("am_accountgl","am_accountgl.AccountNumber=at_prodjournal.ProdAccountNumber","INNER");
        $this->db->order_by('at_prodjournal.ProdSaldoDebet','DESC');
		$query = $this->db->get_where($this->journal, array('ProdNumber' => $Number));
		$this->db->_protect_identifiers = TRUE;
        return $query->result();
    }
	
	function get_app_level1($id) {
        $this->db->select('AppLevel1Status');
		$this->db->from($this->table);
		$this->db->where('ProdNumber', $id); 
		$query = $this->db->get();    
        
		if ($query->num_rows() > 0) {
			foreach ($query->result() as $row) {
				$AppLevel1Status = $row->AppLevel1Status;
			}    

			return $AppLevel1Status;
		}
		else {
			return 0;
		}	
    }
	
	function get_app_level2($id) {
        $this->db->select('AppLevel2Status');
		$this->db->from($this->table);
		$this->db->where('ProdNumber', $id); 
		$query = $this->db->get();    
        
		if ($query->num_rows() > 0) {
			foreach ($query->result() as $row) {
				$AppLevel2Status = $row->AppLevel2Status;
			}    

			return $AppLevel2Status;
		}
		else {
			return 0;
		}	
    }
	
	function search_item(){
        $this->db->_protect_identifiers = true;
        $ItemCategoryID         = isset($_POST['item_categori'])? mysql_real_escape_string($_POST['item_categori']) : '';
        $ItemCode		= isset($_POST['item_code'])? mysql_real_escape_string($_POST['item_code']) : '';
        $ItemDesc		= isset($_POST['item_desc'])? mysql_real_escape_string($_POST['item_desc']) : '';
		
        $this->db->select("it.*, ItemPPhType as ItemPPh22Status, '0' ItemPPh23Status, '0' as ItemAdvNetDueIn, 
                           ic.ItemCategoryName as ItemCategoryCode, ic.AssetStatus as ItemStatus");
        $this->db->from($this->item . ' it');
        $this->db->join($this->itemcategory . ' ic', 'ic.ItemCategoryID = it.ItemCategoryID', 'INNER');

        if($ItemCategoryID != ''){
            $this->db->where('it.ItemCategoryID', $ItemCategoryID);
        }

        if($ItemCode != ''){
            $this->db->like('it.ItemCode', $ItemCode);
        }

        if($ItemDesc != ''){
            $this->db->like('it.ItemDesc', $ItemDesc);
        }

        $this->db->where_in('it.TransStatus', array(0, 1));
        $this->db->order_by('it.ItemCode', 'ASC');
        $this->db->_protect_identifiers = false;

        return $this->db->get()->result();
    }
	
	function search_prod(){
		$this->db->_protect_identifiers = true;
        $item_catcode	= isset($_POST['item_categori'])? mysql_real_escape_string($_POST['item_categori']) : '';
        $item_code	= isset($_POST['item_code'])? mysql_real_escape_string($_POST['item_code']) : '';
        $item_desc	= isset($_POST['item_desc'])? mysql_real_escape_string($_POST['item_desc']) : '';
        $sess_branch    = $this->session->userdata('branch');
        
        $this->db->select('am_item.ItemCode, am_item.ItemDesc');
        $this->db->from('am_item');
		$this->db->join('am_itemcategory', 'am_itemcategory.ItemCategoryID = am_item.ItemCategoryID', 'INNER');
        
		if($item_catcode != ''){
            $this->db->where('am_item.ItemCategoryID', $item_catcode);
        }

        if($item_code != ''){
            $this->db->like('am_item.ItemCode', $item_code);
        }

        if($item_desc != ''){
            $this->db->like('am_item.ItemDesc', $item_desc);
        }
		$this->db->where('am_itemcategory.AssetStatus !=', 1);
		$this->db->where('am_item.TransStatus', 1);
		
		//$item = array($item_code);
        $this->db->order_by('am_item.ItemCode', 'ASC');
		$this->db->_protect_identifiers = false;
		
        return $this->db->get()->result();
    }
	
	function get_kategori(){
        $this->db->select('am_itemcategory.*');
        $this->db->from('am_itemcategory');
	  	$this->db->where_in('am_itemcategory.TransStatus', array(0,1));
		$this->db->where('am_itemcategory.AssetStatus !=', 1);
        $query = $this->db->get();
        
        return $query->result();
    }
	
	function get_inventori_by_item($id, $branch) {     
        $query = $this->db->get_where('at_inventories', array('ItemCode' => $id, 'BranchCode' => $branch));
        
        if ($query->num_rows() > 0) {
            return $query->row();
        }
        else {
            return false;
        }	
    }
	
	/*function get_inventori_by_item($item_code, $branch){
        $this->db->select('at_inventories.*');
        $this->db->from('am_item');
		
		$this->db->join('at_inventories', 'at_inventories.ItemCode = am_item.ItemCode', 'inner');
	  	$this->db->where('at_inventories.ItemCode', $item_code);
		$this->db->where('at_inventories.BranchCode', $branch);
        $query = $this->db->get();
        
        return $query->result();
    }*/

    function insert_transsaction($trans_data){

		$this->db->trans_start();

		/*================= insert group transaction ==============================*/
		$this->insert($trans_data['insert_group']['data']);

		for($x=0;$x<count($trans_data['insert_detail']['data']);$x++){
			$this->insert_detail($trans_data['insert_detail']['data'][$x]);
		}

		for($x=0;$x<count($trans_data['insert_journal']['data']);$x++){
			$this->insert_journal_debet($trans_data['insert_journal']['data'][$x]);
		}

		$this->db->trans_complete();

		if ($this->db->trans_status() === FALSE) {
			return false;
		}else{
			return true;
		}	
	}

	function update_transsaction($trans_data){

		$this->db->trans_start();

		$this->update($trans_data['update_group']['data'],$trans_data['update_group']['TransNumber']);

		$this->delete_journal($trans_data['delete_journal']['TransNumber']);

		$this->delete_detail_grid_2($trans_data['delete_detail']['TransNumber']);

		for($x=0;$x<count($trans_data['insert_detail']['data']);$x++){
			$this->insert_detail($trans_data['insert_detail']['data'][$x]);
		}

		for($x=0;$x<count($trans_data['insert_journal']['data']);$x++){
			$this->insert_journal_debet($trans_data['insert_journal']['data'][$x]);
		}

		$this->db->trans_complete();

		if ($this->db->trans_status() === FALSE) {
			return false;
		}else{
			return true;
		}
	}

	function approve_transsaction($trans_data){

		$this->db->trans_start();

		$this->update_status($trans_data['update_status']['data'],$trans_data['update_status']['TransNumber']);

		for($x=0;$x<count($trans_data['update_inventories']['data']);$x++){
			$this->update_inventories($trans_data['update_inventories']['data'][$x],$trans_data['update_inventories']['ItemCode'][$x],$trans_data['update_inventories']['branch'][$x]);
		}

		$this->db->trans_complete();

		if($this->db->trans_status() === false) {
			return false;
		}else{
			return true;
		}
	}

	function suspend_transsaction($trans_data){

		$this->db->trans_start();

		$this->suspend($trans_data['suspend_data']['data'], $trans_data['suspend_data']['TransNumber']);

		for($x=0;$x<count($trans_data['update_inventories']['data']);$x++){
			$this->update_inventories($trans_data['update_inventories']['data'][$x],$trans_data['update_inventories']['ItemCode'][$x],$trans_data['update_inventories']['branch'][$x]);
		}

		$this->db->trans_complete();

		if ($this->db->trans_status() === FALSE) {
			return false;
		}
		else{
			return true;
		}
	}

	function reverse_transsaction($trans_data){

		$this->db->trans_start();

		$this->update_to_reverse_payment($trans_data['reverse_data']['TransNumber'],$trans_data['reverse_data']['data']);
		$this->delete_reconcile($trans_data['delete_reconcile']['TransNumber']);

		$this->db->trans_complete();

		if ($this->db->trans_status() === FALSE) {
			return false;
		}
		else{
			return true;
		}
	}
}