<?php
class M_fixed_asset_selling extends CI_Model {
    
	// deklarasi nama table
	public $table				= "at_fixed_asset_selling";
	public $journal				= "at_fsjournal";
	public $branch				= "am_branch";
	public $detail				= "at_fsdetail";
	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 $inventory 			= "at_inventories";
	public $depreciatemethod    = 'am_depreciatemethod';
	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_selling.BranchCode as Branch_Code, am_accountgl.AccountName, at_fixed_asset_selling.FSNumber, am_employee.EmployeeName as CreatedBy,
			at_fixed_asset_selling.FSDate, at_fixed_asset_selling.FSDesc, am_branch.BranchName, 
			at_fixed_asset_selling.TotalAmount, at_fixed_asset_selling.TransStatus'
		);
		$this->db->from($this->table);
		$this->db->join('am_branch','am_branch.BranchCode = at_fixed_asset_selling.BranchCode');
		$this->db->join('am_employee','am_employee.EmployeeCode = at_fixed_asset_selling.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.'.FSNumber', $Number);}
		if($Desc != ""){$this->db->like($this->table.'.FSDesc', $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.'.FSDate >=', date("Y-m-d", strtotime($DateFrom)));
            	$this->db->where($this->table.'.FSDate <=', 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.'.FSNumber', '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_fs_number) {
        $query = $this->db->get_where($this->table, array('FSNumber' => $new_fs_number), 1, 0);
		
        if ($query->num_rows() > 0) {
            return TRUE;
        }
        else {
            return FALSE;
        }	
    }
	
	function create_fs_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');
        }
		
        $fs_number	= $branch ."/". $month . $year ."FS/";
		
        $this->db->_protect_identifiers = false;
        $this->db->select('(CASE 
                              WHEN MAX(CONVERT(SUBSTR(FSNumber, -3),signed)) IS NULL then 1
                              ELSE MAX(CONVERT(SUBSTR(FSNumber, -3),signed)) + 1 END) as New_Number');
        $this->db->like('FSNumber', $fs_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_fs_number = $fs_number . $number;

        while($this->check_code_exist($new_fs_number)){
            $num++;
            $long = strlen($num);
    
            if($long == 1){
                $number = '00' . $num;
            }
            elseif($long == 2){
                $number = '0' . $num;
            }
            else{
                $number = $num;
            }
            
            $new_fs_number = $fs_number . $number;		
        }
        
        return  $new_fs_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,$FSNumber){
		$this->db->update($this->table,$data_group,array('FSNumber' => $FSNumber));
	}

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

	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->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 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 m_get_selling_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('Revenue','Other Revenue'));
		$this->db->where('ag.AccountChild !=', 0);
		$this->db->where('ac.TransStatus =', 2);

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

	function m_get_bank_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('sub.AccountTypeName', array('Bank'));
		$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_selling($fd_number, $BranchCode){
		$this->db->select($this->table.'.BranchCode,FSDate,FSNumber,GLAccount,FSDesc,TotalAmount,AssetPrice,Rate,SLAccount,CurrencyCode,at_fixed_asset_selling.TransStatus,at_fixed_asset_selling.CreatedBy,em.DepartmentCode');
		$this->db->from($this->table);
		$this->db->join($this->employee.' as em','em.EmployeeCode=at_fixed_asset_selling.CreatedBy','inner');
		$this->db->where('FSNumber',$fd_number);
		$this->db->where($this->table.'.BranchCode',$BranchCode);

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

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

	function get_fixed_asset_detail($branch,$FSNumber){
		//$this->db->select('dt.FSAmount as AccumAmount,id.ItemAverage,id.ItemCategoryID,id.AssetCode,id.ItemCode,id.ItemDesc as Description,dt.ItemQty as Qty,id.ReceiptNumber,dt.FixedAssetType');
		$this->db->select('dt.FSAmount as AccumAmount,id.ItemAverage,id.ItemCategoryID,id.AssetCode,id.ItemCode,id.ItemDesc as Description,(1) as Qty,id.ReceiptNumber,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.FSNumber',$FSNumber);
		$this->db->where('id.BranchCode',$branch);

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

		return $query;
	}

	function get_detail_journal($FSNumber){
		$this->db->select('gr.FSNumber,gr.FSDate,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('FSNumber',$FSNumber);

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

		return $query;
	}

	function get_list_journal($branch,$FSNumber){
		$this->db->select('jr.FSNumber,jr.AssetCode,jr.FSAccountNumber,ag.AccountName,jr.FSSaldoDebet,jr.FSSaldoCredit,jr.AmountCurrency');
		$this->db->from($this->journal.' as jr');
		$this->db->join($this->comp_gl.' as ac','ac.AccountNumber=jr.FSAccountNumber','inner');
		$this->db->join($this->acc_gl.' as ag','ag.AccountNumber=ac.AccountNumber','inner');
		$this->db->where('jr.FSNumber',$FSNumber);
		$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_selling($data_suspend,$FSNumber){
		$this->db->update($this->table,$data_suspend,array('FSNumber'=>$FSNumber));
	}

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

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

		$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($FSNumber,$data_fixed_asset){
    	$this->db->update($this->table,$data_fixed_asset,array("FSNumber" => $FSNumber));
    }

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

	function get_detail_print($FSNumber){
		$this->db->select('cp.CompanyName,gr.BranchCode,br.BranchName,br.BranchAddress,gr.FSNumber,gr.FSDate,gr.TotalAmount,gr.FSDesc,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.FSNumber', $FSNumber);
   
        $query = $this->db->get();
    
        if($query->num_rows()>0){
            return $query->row();
        }
        else {
            return false;
        }     
	}

	function get_detail_item_print($FSNumber){
		$this->db->select('dt.AssetCode,dt.ReceiptNumber,dt.ItemCode,it.ItemDesc,dt.FSAmount,gr.AssetPrice,ag.AccountName,');
		$this->db->from($this->detail.' as dt');
		$this->db->join($this->table.' as gr','gr.FSNumber=dt.FSNumber','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.FSNumber', $FSNumber);
		
        $query = $this->db->get()->result_array();
    
       return $query;
	}

	function get_fixed_asset_account($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()->result_array();

        if(count($query)>0){
            return $query;
        }
        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 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 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_selling.BranchCode as Branch_Code, am_accountgl.AccountName, at_fixed_asset_selling.FSNumber, am_employee.EmployeeName as CreatedBy,
			at_fixed_asset_selling.FSDate, at_fixed_asset_selling.FSDesc, am_branch.BranchName, 
			at_fixed_asset_selling.TotalAmount,                       
                          (case 
                            when at_fixed_asset_selling.TransStatus = 1 then 'On Progress'
                            when at_fixed_asset_selling.TransStatus = 2 then 'Finished'
                            when at_fixed_asset_selling.TransStatus = 3 then 'Suspend'
                            when at_fixed_asset_selling.TransStatus = 4 then 'Need App. Mgr.'
                            when at_fixed_asset_selling.TransStatus = 5 then 'Need App. Dir.'
                            when at_fixed_asset_selling.TransStatus = 6 then 'Need App. Dir. & Mgr.'
                            when at_fixed_asset_selling.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_selling.BranchCode');
        $this->db->join('am_employee', 'am_employee.EmployeeCode = at_fixed_asset_selling.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 . '.FSNumber', $Number);
        }
        if ($Desc != "") {
            $this->db->like($this->table . '.FSDesc', $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 . '.FSDate >=', date("Y-m-d", strtotime($DateFrom)));
                $this->db->where($this->table . '.FSDate <=', 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 . '.FSNumber', '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.FSDate,cb.FSNumber,
			cb.FSDesc,cb.TotalAmount,gl.AccountName as GL_Account,sl.AccountName as Sell_Account');
		$this->db->from($this->table.' as cb');
		$this->db->join($this->acc_gl.' as gl','gl.AccountNumber=cb.GLAccount','inner');
		$this->db->join($this->acc_gl.' as sl','sl.AccountNumber=cb.SLAccount','inner');
		$this->db->where('cb.BranchCode', $sess_branch);
		
		$query = $this->db->get();
		return $query->result();
	}
	
    //============= DHIDHIK, 21 Maret 2016 ===================================//        
    function datasend_fixedasset_selling_insert($dataSend){         
        $this->db->trans_start();  
        
        $this->insert_group($dataSend['insert_group']);
        
        foreach($dataSend['insert_detail']['detail_data'] as $key){
            $this->insert_detail($key);
        }
        
        //====== insert journal ======================================//
        foreach($dataSend['insert_journal']['journal_data_gl'] as $key){
            $this->insert_journal($key);
        }
        foreach($dataSend['insert_journal']['journal_data_acc'] as $key){
            $this->insert_journal($key);
        }
        foreach($dataSend['insert_journal']['journal_data_inv'] as $key){
            $this->insert_journal($key);
        }
        foreach($dataSend['insert_journal']['journal_data_selling'] as $key){
            $this->insert_journal($key);
        }
        foreach($dataSend['insert_journal']['journal_data_revenue'] as $key){
            $this->insert_journal($key);
        }
        //====== End insert journal ==================================//
        
        $this->update_soldstatus($dataSend['update_inv_details']['Arrassetcode'],$dataSend['update_inv_details']['data_invent']);
        
        $this->db->trans_complete();
        if($this->db->trans_status() == FALSE){
            $result  = false;
        }else{
            $result = true;
        }
        return $result;
    }   

    function datasend_fixedasset_selling_update($dataSend){         
        $this->db->trans_start();  
        
        $this->update_group($dataSend['update_group'],$dataSend['FSNumber']);
        
        $this->m_delete_journal($dataSend['FSNumber']);
        
        //====== insert journal ======================================//
        foreach($dataSend['insert_journal']['journal_data_gl'] as $key){
            $this->insert_journal($key);
        }
        foreach($dataSend['insert_journal']['journal_data_acc'] as $key){
            $this->insert_journal($key);
        }
        foreach($dataSend['insert_journal']['journal_data_inv'] as $key){
            $this->insert_journal($key);
        }
        foreach($dataSend['insert_journal']['journal_data_selling'] as $key){
            $this->insert_journal($key);
        }
        foreach($dataSend['insert_journal']['journal_data_revenue'] as $key){
            $this->insert_journal($key);
        }
        //====== End insert journal ==================================//
        
        $this->db->trans_complete();
        if($this->db->trans_status() == FALSE){
            $result  = false;
        }else{
            $result = true;
        }
        return $result;
    } 

    function datasend_fixedasset_selling_app_dir($dataSend){         
        $this->db->trans_start();
        
        // $this->m_delete_journal($dataSend['FSNumber']);

        //====== End insert journal ==================================//
        $this->m_delete_journal($dataSend['FSNumber']);

        //====== insert journal ======================================//
        foreach($dataSend['insert_journal']['journal_data_gl'] as $key){
            $this->insert_journal($key);
        }
        foreach($dataSend['insert_journal']['journal_data_acc'] as $key){
            $this->insert_journal($key);
        }
        foreach($dataSend['insert_journal']['journal_data_inv'] as $key){
            $this->insert_journal($key);
        }
        foreach($dataSend['insert_journal']['journal_data_selling'] as $key){
            $this->insert_journal($key);
        }
        foreach($dataSend['insert_journal']['journal_data_revenue'] as $key){
            $this->insert_journal($key);
        }

        $this->approval_fixed_asset_selling($dataSend['data_approval'],$dataSend['FSNumber']);
        $this->update_soldstatus($dataSend['arr_asset_code'],$dataSend['data_invent']);
        $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_fixedasset_selling_suspend($dataSend){         
        $this->db->trans_start();
        
        $this->suspend_fixed_asset_selling($dataSend['data_suspend'],$dataSend['FSNumber']);
        $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_fixedasset_selling_reverse($dataSend){         
        $this->db->trans_start();
        
        $this->update_to_reverse_fixed_asset($dataSend['FSNumber'],$dataSend['data_reverse']);//update fixed asset/ reverse
        $this->delete_reconcile($dataSend['FSNumber']);//delete reconcile
        $this->update_soldstatus($dataSend['arr_asset_code'],$dataSend['data_invent']);
         $this->update_inventory($dataSend['arr_item_code'],$dataSend['arr_item_average'],'reverse');
       
        $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;
       }
    }
    //============= End DHIDHIK, 21 Maret 2016 ===============================//
}