<?php
class M_fixed_asset_dispose extends CI_Model {
    
	// deklarasi nama table
	public $table				= "at_fixed_asset_dispose";
	public $journal				= "at_fdjournal";
	public $branch				= "am_branch";
	public $detail				= "at_fddetail";
	public $inv_detail 			= 'at_inventdetail';
	public $item_category       = 'am_itemcategory';
    public $fixed_asset_type    = 'am_fixedassettype';
    public $comp_gl 			= "at_compaccountgl";
	public $acc_gl 				= "am_accountgl";
	public $sub_type  			= "am_accountsubtype";
	public $acc_type  			= "am_accounttype";
	public $period 				= "at_periodend";
	public $reconcile 			= "at_bankreconcille";
	public $employee 			= "am_employee";
	public $department 			= "am_department";
	public $item 				= "am_item";
	public $company 			= "am_company";
	public $jvdetail 			= "at_jvchdetail";
	public $inventory 			= "at_inventories";
	public $gnl_ledger          = 'at_journalvoucher';
    public $ledger_detail       = 'at_jvchdetail';
    public $ledger_journal      = "at_jvchjournal";
	
	//create nomor
	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_fixed_asset_dispose.BranchCode as Branch_Code, am_accountgl.AccountName, at_fixed_asset_dispose.FDNumber, am_employee.EmployeeName as CreatedBy,
			at_fixed_asset_dispose.FDDate, at_fixed_asset_dispose.FDDesc, am_branch.BranchName, 
			at_fixed_asset_dispose.TotalAmount, at_fixed_asset_dispose.TransStatus'
		);
		$this->db->from($this->table);
		$this->db->join('am_branch','am_branch.BranchCode = at_fixed_asset_dispose.BranchCode');
		$this->db->join('am_employee','am_employee.EmployeeCode = at_fixed_asset_dispose.CreatedBy', 'LEFT');
		$this->db->join('am_accountgl','am_accountgl.AccountNumber = '.$this->table.'.GLAccount');
		
		/*===================================find by number dan desc=========================================================*/
		if($Number != ""){$this->db->like($this->table.'.FDNumber', $Number);}
		if($Desc != ""){$this->db->like($this->table.'.FDDesc', $Desc);}
		/*=============================================end===================================================================*/
		
		/*===================================find by branch code=========================================================*/
		/*
			get data dari  combobox find di view
		*/
        if($BranchCode != ""){
			$this->db->where($this->table.'.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($this->table.'.BranchCode', $sess_branch);
			//-----------------------end-------------------------------------------------//
		}
		/*=======================================================end========================================================*/
		
		/*=====================================================find by date==================================================*/
		if((($DateFrom != '') && ($DateTo != ''))){
            if($DateFrom <= $DateTo){
				$this->db->where($this->table.'.FDDate >=', date("Y-m-d", strtotime($DateFrom)));
            	$this->db->where($this->table.'.FDDate <=', date("Y-m-d", strtotime($DateTo)));
			}
        }

		/*======================================================end===========================================================*/
		
		/*=====================================================find by status==================================================*/
		if($TransStatus!=''){ 
			$this->db->where_in($this->table.'.TransStatus',$TransStatus); 
		}
		else{
			/*
				trans status 0,1 adalah aktif
			*/
			$this->db->where_in($this->table.'.TransStatus',array(0,1,4,5,6,7,8)); 
		}
		/*=======================================================end========================================================*/
		
		/*==============================================sort tabel asc==========================================================*/
		$this->db->order_by($this->table.'.FDNumber', 'ASC');
		$this->db->order_by($this->table.'.TransStatus', 'DESC');
		/*===============================end=================================================================================*/
		$query  = $this->db->limit($end, $beginning);
		$query = $this->db->get();
		return $query->result();
    }

	
	/*======================penomeran transaksi new=======================================================*/
	function check_code_exist($new_fd_number) {
        $query = $this->db->get_where($this->table, array('FDNumber' => $new_fd_number), 1, 0);
		
        if ($query->num_rows() > 0) {
            return TRUE;
        }
        else {
            return FALSE;
        }	
    }
	
	function create_fd_number($date = ''){
        $branch = $this->session->userdata('branch');
		
        if($date != ''){
            $month  = date('m', strtotime($date));
            $year   = date('y', strtotime($date));
        }
        else{
            $month  = date('m');
            $year   = date('y');
        }
		
        $fd_number	= $branch ."/". $month . $year ."FD/";
		
        $this->db->_protect_identifiers = false;
        $this->db->select('(CASE 
                              WHEN MAX(CONVERT(SUBSTR(FDNumber, -3),signed)) IS NULL then 1
                              ELSE MAX(CONVERT(SUBSTR(FDNumber, -3),signed)) + 1 END) as New_Number');
        $this->db->like('FDNumber', $fd_number);
        $query = $this->db->get($this->table);
        $this->db->_protect_identifiers = true;
                
        $num    = $query->row()->New_Number;
        $long   = strlen($num);
        
        if($long == 1){
            $number = '00' . $num;
        }
        elseif($long == 2){
            $number = '0' . $num;
        }
        else{
            $number = $num;
        }

        $new_fd_number = $fd_number . $number;

        while($this->check_code_exist($new_fd_number)){
            $num++;
            $long = strlen($num);
    
            if($long == 1){
                $number = '00' . $num;
            }
            elseif($long == 2){
                $number = '0' . $num;
            }
            else{
                $number = $num;
            }
            
            $new_fd_number = $fd_number . $number;		
        }
        
        return  $new_fd_number;
    }
	/*==============================================================end=================================*/
	
	function insert_group($data_group){
		$this->db->insert($this->table, $data_group);
	}
	
	function insert_detail($detail_data){
		$this->db->insert($this->detail, $detail_data);
	}

	function insert_journal($journal_data){
		$this->db->insert($this->journal, $journal_data);
	}

	function update_soldstatus($ArrassetCode,$data_invent){
		$this->db->where_in('AssetCode',$ArrassetCode);
		$this->db->update($this->inv_detail,$data_invent);
	}

	function update_group($data_group,$FDNumber){
		$this->db->update($this->table,$data_group,array('FDNumber' => $FDNumber));
	}

	function m_delete_journal($FDNumber){
		$this->db->delete($this->journal,array('FDNumber'=>$FDNumber));
	}

	function get_item_detail($sess_branch, $item_code){
		$this->db->select('ItemCOde');
		$this->db->from('at_jcostdetail');
		$this->db->where('at_jcostdetail.ItemCode', $item_code);
		$query = $this->db->get();    
        
		if ($query->num_rows() > 0) {
			foreach ($query->result() as $row) {
				$ItemCOde = $row->ItemCOde;
			}    

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

			return $TransStatus;
		}
		else {
			return FALSE;
		}	
    }
	
	function set_trans_status($id, $status) {
		$this->db->set('TransStatus', $status);
		$this->db->where('JCostNumber', $id);
		$this->db->update($this->table);
	}
	
	function update_app($data,$id) {
		 $this->db->update($this->table, $data, array('JCostNumber' => $id));
	}

    // function get_fixed_asset($branch){
    // 	$this->db->_protect_identifiers = false;
    // 	$this->db->select('id.ReceiptNumber,id.ReceiptDate,id.ItemCode,id.ItemAverage,id.AssetCode,fat.FixedAssetType,id.ItemDesc,id.ItemQty,id.ItemCategoryID,sum(COALESCE(jv.JVchDebetSaldo,0)) as PaymentAmount');
    // 	$this->db->from($this->inv_detail . ' id');
    //     $this->db->join($this->item_category . ' ic', 'ic.ItemCategoryID = id.ItemCategoryID', 'INNER');
    //     $this->db->join($this->fixed_asset_type . ' fat', 'fat.FixedAssetType = ic.ItemCategoryName', 'INNER');
    //     $this->db->join($this->jvdetail . ' jv', 'jv.AssetCode = id.AssetCode', 'LEFT');
    //     $this->db->where('id.BranchCode', $branch);
    //     $this->db->where('id.SoldStatus',0);
    //     $this->db->where('id.ItemAverage != id.PaymentAmount');
    //     // $this->db->where('fat.TransStatus',1);
    //     $this->db->group_by('id.AssetCode');
    //     $this->db->order_by('id.ReceiptNumber', 'ASC');
    //     $query = $this->db->get();
        
    //     return $query->result_array();
    // }

    function get_fixed_asset($branch){
    	$this->db->select('id.ReceiptNumber,id.ReceiptDate,id.ItemCode,id.ItemAverage,id.PaymentAmount,id.AssetCode,fat.FixedAssetType,id.ItemDesc,id.ItemQty,id.ItemCategoryID');
    	$this->db->from($this->inv_detail . ' id');
        $this->db->join($this->item_category . ' ic', 'ic.ItemCategoryID = id.ItemCategoryID', 'INNER');
        $this->db->join($this->fixed_asset_type . ' fat', 'fat.FixedAssetType = ic.ItemCategoryName', 'INNER');
        $this->db->where('id.BranchCode', $branch);
        $this->db->where('id.SoldStatus',0);
        //$this->db->where('id.ItemAverage != id.PaymentAmount');
        // $this->db->where('fat.TransStatus',1);
        $this->db->order_by('id.ReceiptNumber', 'ASC');
        $query = $this->db->get();
        
        return $query->result();
    }

    function get_total_amount_period($branch,$AssetCode,$accum_account){
        //$this->db->select('sum(case when dt.JVchDebetSaldo=0 then dt.JVchCreditSaldo else dt.JVchDebetSaldo end) as amount_period');
        $this->db->select('sum(dt.JVchCreditSaldo) as amount_period');
        $this->db->from($this->ledger_detail.' as dt');   
        $this->db->join($this->gnl_ledger.' as gr','gr.JVchNumber=dt.JVchNumber','inner');
        $this->db->where('dt.AssetCode',$AssetCode);
        //$this->db->where('dt.JVchAccount',$accum_account);
        $this->db->where('gr.TransStatus',2);
        $this->db->where('gr.JVchType',0);
        $this->db->where('gr.BranchCode',$branch);

        $query = $this->db->get();

        if($query->num_rows()>0){
            $row = $query->row();

            return $row->amount_period;
        }else{
            return 0;
        }  
    }


    function get_fixed_asset_account($fixed_asset_type){
        $this->db->select('AccumAccountNumber');
        $this->db->from($this->fixed_asset_type);
        $this->db->where('FixedAssetType', $fixed_asset_type);
        $query = $this->db->get()->result_array();

        if(count($query)>0){
            return $query[0]['AccumAccountNumber'];
        }
        else{
            return FALSE;
        }
    }

    function get_fixed_asset_account_period($fixed_asset_type){
        $this->db->select('AccumAccountNumber, ExpenseAccountNumber');
        $this->db->from($this->fixed_asset_type);
        $this->db->where('FixedAssetType', $fixed_asset_type);
        $query = $this->db->get();

        if($query->num_rows > 0){
            return $query->row();
        }
        else{
            return FALSE;
        }
    }

    function m_get_gl_account($branch){
		$this->db->select('ag.AccountName,ag.AccountNumber,ag.CurrencyCode');
		$this->db->from($this->comp_gl.' as ac');
		$this->db->join($this->acc_gl.' as ag','ag.AccountNumber = ac.AccountNumber','INNER');
		$this->db->join($this->sub_type.' as sub','sub.AccountSubTypeID = ag.AccountSubTypeID', 'INNER');
		$this->db->join($this->acc_type.' as acc','acc.AccountTypeID = sub.AccountTypeID', 'INNER');
		$this->db->where('ac.BranchCode', $branch);
		$this->db->where('ac.GLSaldoYears', date('Y'));
		$this->db->where_in('acc.AccountTypeName', array('Expense','Other Expense'));
		$this->db->where('ag.AccountChild !=', 0);
		$this->db->where('ac.TransStatus =', 2);

		$query	= $this->db->get();
		return $query->result();
	}

	function get_account_advance($branch){
		$this->db->select('ag.AccountNumber');
		$this->db->from($this->comp_gl.' as ac');
		$this->db->join($this->acc_gl.' as ag','ag.AccountNumber = ac.AccountNumber','INNER');
		$this->db->where('ac.BranchCode', $branch);
		$this->db->where('ag.AccountName', 'Laba (Rugi) Penjualan Aktiva Tetap');
		$this->db->where('ac.GLSaldoYears', date('Y'));
		$this->db->where('ag.AccountChild !=', 0);
		$this->db->where('ac.TransStatus =', 2);

		$query	= $this->db->get()->result_array();

		if(count($query) > 0){
			return $query[0]['AccountNumber'];
		}else{
			return false;
		}
	}

	function get_edit_fixed_asset_dispose($fd_number, $BranchCode){
		$this->db->select($this->table.'.BranchCode,FDDate,FDNumber,GLAccount,FDDesc,TotalAmount,'.$this->table.'.TransStatus,'.$this->table.'.CreatedBy,em.DepartmentCode');
		$this->db->from($this->table);
		$this->db->join($this->employee.' as em','em.EmployeeCode=at_fixed_asset_dispose.CreatedBy','inner');
		$this->db->where('FDNumber',$fd_number);
		$this->db->where($this->table.'.BranchCode',$BranchCode);

		$query 	= $this->db->get();

		$row 	= $query->row();
		return $row;
	}

	function get_fixed_asset_detail($branch,$FDNumber){
		//$this->db->select('dt.FDAmount as AccumAmount,id.AssetCode,id.ItemAverage,id.ItemCode,id.ItemDesc as Description,id.ItemQty as Qty,id.ReceiptNumber,id.ItemCategoryID,dt.FixedAssetType');
		$this->db->select('dt.FDAmount as AccumAmount,id.AssetCode,id.ItemAverage,id.ItemCode,id.ItemDesc as Description,(1) as Qty,id.ReceiptNumber,id.ItemCategoryID,dt.FixedAssetType');
		$this->db->from($this->detail.' as dt');
		$this->db->join($this->inv_detail.' as id','id.AssetCode=dt.AssetCode','inner');
		$this->db->where('dt.FDNumber',$FDNumber);
		$this->db->where('id.BranchCode',$branch);

		$query = $this->db->get()->result_array();

		return $query;
	}

	function get_detail_journal($FDNumber){
		$this->db->select('gr.FDNumber,gr.FDDate,gr.BranchCode,br.BranchName');
		$this->db->from($this->table.' as gr');
		$this->db->join($this->branch.' as br','br.BranchCode=gr.BranchCode','inner');
		$this->db->where('FDNumber',$FDNumber);

		$query 	= $this->db->get()->result();

		return $query;
	}

	function get_list_journal($branch,$FDNumber){
		$this->db->select('jr.FDNumber,jr.AssetCode,jr.FDAccountNumber,ag.AccountName,jr.FDSaldoDebet,jr.FDSaldoCredit');
		$this->db->from($this->journal.' as jr');
		$this->db->join($this->comp_gl.' as ac','ac.AccountNumber=jr.FDAccountNumber','inner');
		$this->db->join($this->acc_gl.' as ag','ag.AccountNumber=ac.AccountNumber','inner');
		$this->db->where('jr.FDNumber',$FDNumber);
		$this->db->where('ac.BranchCode',$branch);
		$this->db->where('ac.GLSaldoYears',date('Y'));
		$this->db->where('ac.TransStatus',2);
		$this->db->order_by('jr.AssetCode','ASC');

		$query = $this->db->get()->result();

		return $query;
	}

	function suspend_fixed_asset_dispose($data_suspend,$FDNumber){
		$this->db->update($this->table,$data_suspend,array('FDNumber'=>$FDNumber));
	}

	function approval_fixed_asset_dispose($data_approval,$FDNumber){
		$this->db->update($this->table,$data_approval,array('FDNumber'=>$FDNumber));
	}

	function get_asset_code_fixed_asset($FDNumber){
		$this->db->select('AssetCode,ItemCode,ItemAverage');
		$this->db->from($this->detail);
		$this->db->where('FDNumber',$FDNumber);

		$query = $this->db->get()->result();

		$arr_asset_code 	= array();
		$arr_item_code 		= array();
		$arr_item_average 	= array();

		foreach($query as $row){
			array_push($arr_asset_code,$row->AssetCode);
			array_push($arr_item_code,$row->ItemCode);
			array_push($arr_item_average,$row->ItemAverage);
		}

		$return['arr_asset_code'] 		= $arr_asset_code;
		$return['arr_item_code']  		= $arr_item_code;
		$return['arr_item_average']  	= $arr_item_average;

		return $return;
	}

	function check_period_end($periodend){
		$this->db->select('PeriodEnd');
		$this->db->from($this->period);
		$this->db->where('PeriodEnd',$periodend);

		$query = $this->db->get()->result_array();

		if(count($query) > 0){
			return true;
		}else{
			return false;
		}
	}

	function update_to_reverse_fixed_asset($FDNumber,$data_fixed_asset){
    	$this->db->update($this->table,$data_fixed_asset,array("FDNumber" => $FDNumber));
    }

    function delete_reconcile($FDNumber){
		$this->db->where('TransNumber',$FDNumber);
		$this->db->delete($this->reconcile);
	}

	function get_detail_print($FDNumber){
		$this->db->select('cp.CompanyName,gr.BranchCode,br.BranchName,br.BranchAddress,gr.FDNumber,gr.FDDate,gr.TotalAmount,gr.FDDesc,gr.TransStatus, ap.EmployeeName as nm_direksi,pr.EmployeeName as nm_prepared');
		$this->db->from($this->table.' as gr');
        $this->db->join($this->branch.' as br','br.BranchCode=gr.BranchCode','INNER');
        $this->db->join($this->company.' as cp','cp.CompanyCode=br.CompanyCode','INNER');
        $this->db->join($this->employee.' as pr','pr.EmployeeCode=gr.CreatedBy','LEFT');
        $this->db->join($this->employee.' as ap','ap.EmployeeCode=gr.AppLevel2Code','LEFT');
        $this->db->where('gr.FDNumber', $FDNumber);
   
        $query = $this->db->get();
    
        if($query->num_rows()>0){
            return $query->row();
        }
        else {
            return false;
        }     
	}

	function get_detail_item_print($FDNumber){
		$this->db->select('dt.AssetCode,dt.ReceiptNumber,dt.ItemCode,it.ItemDesc,dt.FDAmount,ag.AccountName,');
		$this->db->from($this->detail.' as dt');
		$this->db->join($this->table.' as gr','gr.FDNumber=dt.FDNumber','inner');
		$this->db->join($this->item.' as it','it.ItemCode=dt.ItemCode','inner');
  		$this->db->join($this->acc_gl.' as ag','ag.AccountNumber=gr.GLAccount','INNER');
        $this->db->where('dt.FDNumber', $FDNumber);
		
        $query = $this->db->get()->result_array();
    
       return $query;
	}

	function update_inventory($arrItemCode,$arrItemAverage,$appreverse){

		$branch = $this->session->userdata('branch');

		for($x=0;$x<count($arrItemCode);$x++){

			$ItemCode 		= $arrItemCode[$x];
			$ItemAverage 	= $arrItemAverage[$x];
			$ItemCode_db 	= '';
			$ItemAverage_db = 0;
			$ItemValue_db 	= 0;
			$ItemQty_db 	= 0;

			$arrItemAverageDb = $this->get_item_average_by_itemcode($ItemCode,$branch);

			for($i=0;$i<count($arrItemAverageDb);$i++){
				if($ItemCode == $arrItemAverageDb[$i]['ItemCode']){
					$ItemCode_db 	= doubleval($arrItemAverageDb[$i]['ItemCode']);
					$ItemAverage_db = doubleval($arrItemAverageDb[$i]['ItemAverage']);
					$ItemValue_db 	= doubleval($arrItemAverageDb[$i]['ItemValue']);
					$ItemQty_db 	= doubleval($arrItemAverageDb[$i]['ItemQty']);
				}
			}

			if($appreverse == 'approve'){
				$itemQty_new 			= $ItemQty_db - 1;
				if($itemQty_new > 0){
					$ItemAverage_new 		= (($ItemQty_db * $ItemAverage_db) - (1 * $ItemAverage)) / ($ItemQty_db - 1);
				}else{
					$ItemAverage_new 		= (($ItemQty_db * $ItemAverage_db) - (1 * $ItemAverage));
				}
				
				$ItemValue_new 			= $ItemAverage_new * $itemQty_new;
			}else{
				$itemQty_new 			= $ItemQty_db + 1;
				$ItemAverage_new 		= (($ItemQty_db * $ItemAverage_db) + (1 * $ItemAverage)) / ($ItemQty_db + 1);
				$ItemValue_new 			= $ItemAverage_new * $itemQty_new;
			}
			

			$this->db->set('ItemQty',$itemQty_new, FALSE);
			$this->db->set('ItemAverage',$ItemAverage_new, FALSE);
			$this->db->set('ItemValue',$ItemValue_new, FALSE);
			$this->db->where('ItemCode', $ItemCode);
			$this->db->update($this->inventory);
		}
	}

	function get_item_average_by_itemcode($ItemCode,$branch){
    	$this->db->select('ItemQty,ItemAverage,ItemValue,ItemCode');
    	$this->db->from($this->inventory);
    	$this->db->where('ItemCode',$ItemCode);
    	$this->db->where('BranchCode',$branch);

    	$query = $this->db->get()->result_array();

    	return $query;
    }

	function m_delete_detail($AssetCode,$FDNumber){
		$this->db->where('AssetCode',$AssetCode);
		$this->db->where('FDNumber',$FDNumber);
		$this->db->delete($this->detail);
	}

	function get_company_by_branch($sess_branch){
		$this->db->select('CompanyName,BranchName');
		$this->db->from('am_company');
		$this->db->join('am_branch','am_branch.CompanyCode = am_company.CompanyCode','inner');
		// $this->db->join($this->table,$this->table.'.BranchCode = am_branch.BranchCode','inner');
		$this->db->where('am_branch.BranchCode', $sess_branch);
		$query = $this->db->get();
		return $query->row();
	}

    function get_all_to_print($data_filter) {
        /* =================================post dari find di kiri==================================================== */
        $BranchCode     = $data_filter['cmb_branch'];
        $Number         = $data_filter['txt_IDNumber'];
        $Desc           = $data_filter['txt_Description'];
        $DateFrom       = $data_filter['txt_DateFrom'];
        $DateTo         = $data_filter['txt_DateTo'];
        $TransStatus    = $data_filter['chk_TransStatus'];
        /* ============================================end============================================================ */

        /* ==========================================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_fixed_asset_dispose.BranchCode as Branch_Code, am_accountgl.AccountName, at_fixed_asset_dispose.FDNumber, am_employee.EmployeeName as CreatedBy,
			at_fixed_asset_dispose.FDDate, at_fixed_asset_dispose.FDDesc, am_branch.BranchName, 
			at_fixed_asset_dispose.TotalAmount,
                (case 
                when at_fixed_asset_dispose.TransStatus = 1 then 'On Progress'
                when at_fixed_asset_dispose.TransStatus = 2 then 'Finished'
                when at_fixed_asset_dispose.TransStatus = 3 then 'Suspend'
                when at_fixed_asset_dispose.TransStatus = 4 then 'Need App. Mgr.'
                when at_fixed_asset_dispose.TransStatus = 5 then 'Need App. Dir.'
                when at_fixed_asset_dispose.TransStatus = 6 then 'Need App. Dir. & Mgr.'
                when at_fixed_asset_dispose.TransStatus = 9 then 'Canceled by Dir.'
                else 'Unknown' end) as TransStatus"
        );
        $this->db->from($this->table);
        $this->db->join('am_branch', 'am_branch.BranchCode = at_fixed_asset_dispose.BranchCode');
        $this->db->join('am_employee', 'am_employee.EmployeeCode = at_fixed_asset_dispose.CreatedBy', 'LEFT');
        $this->db->join('am_accountgl', 'am_accountgl.AccountNumber = ' . $this->table . '.GLAccount');

        /* ===================================find by number dan desc========================================================= */
        if ($Number != "") {
            $this->db->like($this->table . '.FDNumber', $Number);
        }
        if ($Desc != "") {
            $this->db->like($this->table . '.FDDesc', $Desc);
        }
        /* =============================================end=================================================================== */

        /* ===================================find by branch code========================================================= */
        /*
          get data dari  combobox find di view
         */
        if ($BranchCode != "") {
            $this->db->where($this->table . '.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($this->table . '.BranchCode', $sess_branch);
            //-----------------------end-------------------------------------------------//
        }
        /* =======================================================end======================================================== */

        /* =====================================================find by date================================================== */
        if ((($DateFrom != '') && ($DateTo != ''))) {
            if ($DateFrom <= $DateTo) {
                $this->db->where($this->table . '.FDDate >=', date("Y-m-d", strtotime($DateFrom)));
                $this->db->where($this->table . '.FDDate <=', date("Y-m-d", strtotime($DateTo)));
            }
        }

        /* ======================================================end=========================================================== */

        /* =====================================================find by status================================================== */
        if (!empty($TransStatus)) {
            $this->db->where_in($this->table . '.TransStatus', $TransStatus);
        } else {
            /*
              trans status 0,1 adalah aktif
             */
            $this->db->where_in($this->table . '.TransStatus', array(0, 1, 4, 5, 6, 7, 8));
        }
        /* =======================================================end======================================================== */

        /* ==============================================sort tabel asc========================================================== */
        $this->db->order_by($this->table . '.FDNumber', 'ASC');
        $this->db->order_by($this->table . '.TransStatus', 'DESC');
        /* ===============================end================================================================================= */
        $query = $this->db->get();
        return $query->result();
    }
	function get_all_to_print_LAMA($sess_branch){
		$this->db->select('cb.FDDate,cb.FDNumber,
			cb.FDDesc,cb.TotalAmount,gl.AccountName as GL_Account');
		$this->db->from($this->table.' as cb');
		$this->db->join($this->acc_gl.' as gl','gl.AccountNumber=cb.GLAccount','inner');
		$this->db->where('cb.BranchCode', $sess_branch);
		
		$query = $this->db->get();
		return $query->result();
	}
        
    //=========== DHIDHIK, 23 MARET 2016 =====================================//
    function datasend_fixedassetdispose_insert($dataSend){         
        $this->db->trans_start();  
        
        $this->insert_group($dataSend['data_group']);//insert group        
        foreach($dataSend['data_detail'] as $key){//insert data detail
            $this->insert_detail($key); 
        }  
        
        //============== insert data journal =================================//
        foreach($dataSend['data_journal']['journal_data_gl'] as $key){ //insert journal_data_gl
            $this->insert_journal($key);
        }
        foreach($dataSend['data_journal']['journal_data_acc'] as $key){ //insert journal_data_acc
            $this->insert_journal($key);
        }
        foreach($dataSend['data_journal']['journal_data_inv'] as $key){ //insert journal_data_inv
            $this->insert_journal($key);
        }
        //============== End insert data journal =============================//
               
        $this->update_soldstatus($dataSend['data_invdetail']['Arrassetcode'],$dataSend['data_invdetail']['data_invent']);//update_inv_detail
        
        $this->db->trans_complete();
        if($this->db->trans_status() == FALSE){
            $result  = false;
        }else{
            $result = true;
        }
        return $result;
    }
    function datasend_fixed_asset_dispose_app_dir($dataSend){         
        $this->db->trans_start();  
        
        $this->approval_fixed_asset_dispose($dataSend['data_approval'],$dataSend['FDNumber']);  //update fixed asset group to approve
        $this->update_soldstatus($dataSend['arr_asset_code'],$dataSend['data_invent']);         //update soldstatus inv detail to sold
        $this->update_inventory($dataSend['arr_item_code'],$dataSend['arr_item_average'],'approve');
        
        $this->db->trans_complete();
        if($this->db->trans_status() == FALSE){
            $result  = false;
        }else{
            $result = true;
        }
        return $result;
    }
    function datasend_fixedassetdispose_update($dataSend){         
        $this->db->trans_start();  
        
        foreach($dataSend['group_update'] as $key){ //group_update
            $data_group = array(
                'BranchCode' 		=> $key['BranchCode'],
                'FDDate' 		=> $key['FDDate'],	
                'FDDesc' 		=> $key['FDDesc'],
                'GLAccount' 		=> $key['GLAccount'],
                'TotalAmount' 		=> $key['TotalAmount'],
                'TransStatus' 		=> $key['TransStatus'],
                'CreatedBy' 		=> $key['CreatedBy'],
                'CreatedAt' 		=> $key['CreatedAt'],
                'LastUser' 		=> $key['LastUser']
            );
            $this->update_group($data_group,$key['FDNumber']);
        }        
        $this->m_delete_journal($dataSend['FDNumber']);//delete journal
        foreach($dataSend['detail_delete'] as $key){ //detail_delete
            $this->m_delete_detail($key['ass_code'],$key['FDNumber']);
        }
        
        //============== insert data journal =================================//
        foreach($dataSend['journal_insert']['journal_data_gl'] as $key){ //insert journal_data_gl
            $this->insert_journal($key);
        }
        foreach($dataSend['journal_insert']['journal_data_acc'] as $key){ //insert journal_data_acc
            $this->insert_journal($key);
        }
        foreach($dataSend['journal_insert']['journal_data_inv'] as $key){ //insert journal_data_inv
            $this->insert_journal($key);
        }
        //============== End insert data journal =============================//
        
        $this->db->trans_complete();
        if($this->db->trans_status() == FALSE){
            $result  = false;
        }else{
            $result = true;
        }
        return $result;
    }
    function datasend_fixedassetdispose_suspend($dataSend){         
        $this->db->trans_start();  
        
        $this->suspend_fixed_asset_dispose($dataSend['data_suspend'],$dataSend['FDNumber']);//suspend 
        $this->update_soldstatus($dataSend['arr_asset_code'],$dataSend['data_invent']);
        
        $this->db->trans_complete();
        if($this->db->trans_status() == FALSE){
            $result  = false;
        }else{
            $result = true;
        }
        return $result;
    }
    function datasend_fixedassetdispose_reverse($dataSend){         
        $this->db->trans_start();  
        
        $this->update_to_reverse_fixed_asset($dataSend['FDNumber'],$dataSend['data_suspend']);//update fixed asset/ reverse
        $this->delete_reconcile($dataSend['FDNumber']);//get asset code from fixed asset dispose by FDNumber
        $this->update_soldstatus($dataSend['arr_asset_code'],$dataSend['data_invent']);
        $this->update_inventory($dataSend['arr_item_code'],$dataSend['arr_item_average'],'reverse');//update inventories qty + 1
        
        $this->db->trans_complete();
        if($this->db->trans_status() == FALSE){
            $result  = false;
        }else{
            $result = true;
        }
        return $result;
    }

    function get_item_average($AssetCode,$branch){
    	$this->db->select('id.ItemAverage');
    	$this->db->from($this->inv_detail . ' id');
        $this->db->join($this->item_category . ' ic', 'ic.ItemCategoryID = id.ItemCategoryID', 'INNER');
        $this->db->join($this->fixed_asset_type . ' fat', 'fat.FixedAssetType = ic.ItemCategoryName', 'INNER');
        $this->db->where('id.BranchCode', $branch);
        $this->db->where('id.ItemAverage != id.PaymentAmount');
        $this->db->where('id.AssetCode',$AssetCode);

        $this->db->order_by('id.ReceiptNumber', 'ASC');
        $query = $this->db->get();
        
       if($query->num_rows()>0){
       		$row = $query->row();
       		return $row->ItemAverage;
       }else{
       		return 0;
       }
    }

    function get_item_average_inventories($arr_item_code,$branch){
    	$this->db->select('ItemQty,ItemAverage,ItemValue,ItemCode');
    	$this->db->from($this->inventory);
    	$this->db->where_in('ItemCode',$arr_item_code);
    	$this->db->where('BranchCode',$branch);

    	$query = $this->db->get()->result_array();

    	return $query;
        
    //=========== END DHIDHIK, 23 MARET 2016 =================================//
    }
	
}