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

class M_sales_receipt extends CI_Model {
    public $table           = "at_salesreceipt";
    public $detail          = "at_srecdetail";
    public $journal         = "at_srecjournal";
    public $branch          = "am_branch";
    public $customer        = "am_customer";
    public $employee        = "am_employee";
    public $shipment        = "am_shipment";
    public $termspayment    = "am_termspayment";
	public $sorddetaildp    = "at_sorddetaildp";
	public $receipt    		= "at_invoicereceipt";
	public $comp_gl         = "at_compaccountgl";
	
    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'] : '';
		$cmb_CustomerCode	= isset($param['cmb_CustomerCode']) ? $param['cmb_CustomerCode'] : '';
		/*============================================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_salesreceipt.TransStatus,	at_salesreceipt.SRecNumber, at_salesreceipt.SRecDate, at_salesreceipt.SRecDesc, at_salesreceipt.ReceiptStatus,am_employee.EmployeeName as CreatedBy,
		at_salesreceipt.CustomerCode, at_salesreceipt.SRecTotalAmount, at_salesreceipt.SRecAmountCurr,
		at_salesreceipt.BranchCode, am_customer.CustomerName, am_branch.BranchName");
        $this->db->from('at_salesreceipt');
        $this->db->join('am_customer', 'am_customer.CustomerCode = at_salesreceipt.CustomerCode', 'inner');
        $this->db->join('am_branch', 'am_branch.BranchCode = at_salesreceipt.BranchCode', 'inner');
		$this->db->join('am_employee', 'am_employee.EmployeeCode = at_salesreceipt.CreatedBy', 'inner');

        /*===================================find by number dan desc=========================================================*/
		if($Number != ""){$this->db->like('at_salesreceipt.SRecNumber', $Number);}
		if($Desc != ""){$this->db->like('at_salesreceipt.SRecDesc', $Desc);}
		if($cmb_CustomerCode != ""){$this->db->where('am_customer.CustomerCode', $cmb_CustomerCode);}
		/*=============================================end===================================================================*/
		
		/*===================================find by branch code=========================================================*/
		/*
			get data dari  combobox find di view
		*/
        if($BranchCode != ""){
			$this->db->where('at_salesreceipt.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_salesreceipt.BranchCode', $sess_branch);
			//-----------------------end-------------------------------------------------//
		}
		/*=======================================================end========================================================*/
		
		/*=====================================================find by date==================================================*/
		if((($DateFrom != '') && ($DateTo != ''))){
            if($DateFrom <= $DateTo){
				$this->db->where('at_salesreceipt.SRecDate >=', date("Y-m-d", strtotime($DateFrom)));
            	$this->db->where('at_salesreceipt.SRecDate <=', date("Y-m-d", strtotime($DateTo)));
			}
        }
		/*======================================================end===========================================================*/
		
		/*=====================================================find by status==================================================*/
		if($TransStatus!=''){ 
			$this->db->where_in('at_salesreceipt.TransStatus',$TransStatus); 
		}
		else{
			/*
				trans status 0,1 adalah aktif
			*/
			$this->db->where_in('at_salesreceipt.TransStatus',array(0,1,4,5,6,7)); 
		}
		/*=======================================================end========================================================*/
		
		/*==============================================sort tabel asc==========================================================*/
		$this->db->order_by($this->table.'.TransStatus', 'ASC');
		$this->db->order_by($this->table.'.SRecNumber', 'ASC');
		/*===============================end=================================================================================*/
		$query  = $this->db->limit($end, $beginning);
		$query = $this->db->get();
		return $query->result();
    }
	
	function get_all_print($param){
		/*=========================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'] : '';
		$cmb_CustomerCode	= isset($param['cmb_CustomerCode']) ? $param['cmb_CustomerCode'] : '';
		/*============================================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_salesreceipt.TransStatus,	at_salesreceipt.SRecNumber, at_salesreceipt.SRecDate, at_salesreceipt.SRecDesc, at_salesreceipt.ReceiptStatus,am_employee.EmployeeName as CreatedBy,
		at_salesreceipt.CustomerCode, at_salesreceipt.SRecTotalAmount, at_salesreceipt.SRecAmountCurr,
		(case 
                                when at_salesreceipt.TransStatus = 0 then 'Waiting' 
                                when at_salesreceipt.TransStatus = 1 then 'On Progress' 
                                when at_salesreceipt.TransStatus = 2 then 'Active' 
                                when at_salesreceipt.TransStatus = 3 then 'Suspended' 
                                when at_salesreceipt.TransStatus = 4 then 'Need Mgr. App.' 
                                when at_salesreceipt.TransStatus = 5 then 'Need Dir. App.' 
                                when at_salesreceipt.TransStatus = 6 then 'Need Dir & Mgr App.' end) as Status,
								
								
		at_salesreceipt.BranchCode, am_customer.CustomerName, am_branch.BranchName");
        $this->db->from('at_salesreceipt');
        $this->db->join('am_customer', 'am_customer.CustomerCode = at_salesreceipt.CustomerCode', 'inner');
        $this->db->join('am_branch', 'am_branch.BranchCode = at_salesreceipt.BranchCode', 'inner');
		$this->db->join('am_employee', 'am_employee.EmployeeCode = at_salesreceipt.CreatedBy', 'inner');

        /*===================================find by number dan desc=========================================================*/
		if($Number != ""){$this->db->like('at_salesreceipt.SRecNumber', $Number);}
		if($Desc != ""){$this->db->like('at_salesreceipt.SRecDesc', $Desc);}
		if($cmb_CustomerCode != ""){$this->db->where('am_customer.CustomerCode', $cmb_CustomerCode);}
		/*=============================================end===================================================================*/
		
		/*===================================find by branch code=========================================================*/
		/*
			get data dari  combobox find di view
		*/
        if($BranchCode != ""){
			$this->db->where('at_salesreceipt.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_salesreceipt.BranchCode', $sess_branch);
			//-----------------------end-------------------------------------------------//
		}
		/*=======================================================end========================================================*/
		
		/*=====================================================find by date==================================================*/
		if((($DateFrom != '') && ($DateTo != ''))){
            if($DateFrom <= $DateTo){
				$this->db->where('at_salesreceipt.SRecDate >=', date("Y-m-d", strtotime($DateFrom)));
            	$this->db->where('at_salesreceipt.SRecDate <=', date("Y-m-d", strtotime($DateTo)));
			}
        }
		/*======================================================end===========================================================*/
		
		/*=====================================================find by status==================================================*/
		if($TransStatus!=''){ 
			$this->db->where_in('at_salesreceipt.TransStatus',$TransStatus); 
		}
		else{
			/*
				trans status 0,1 adalah aktif
			*/
			$this->db->where_in('at_salesreceipt.TransStatus',array(0,1,4,5,6,7)); 
		}
		/*=======================================================end========================================================*/
		
		/*==============================================sort tabel asc==========================================================*/
		$this->db->order_by($this->table.'.TransStatus', 'ASC');
		$this->db->order_by($this->table.'.SRecNumber', 'ASC');
		/*===============================end=================================================================================*/
		$query  = $this->db->limit($end, $beginning);
		$query = $this->db->get();
		return $query->result();
    }
	
    function get_detail($id){
        $this->db->select($this->table.".*,".$this->branch.".BranchName, ".$this->customer.".CustomerName, cg.GLSaldoBSheet as BankBalance,cp.CompanyName,
							".$this->customer.".CustomerAddress, ".$this->customer.".CurrencyCode as CurrCustomer, ".$this->customer.".SaldoDPPartial,
                          ".$this->customer.".SaldoDPBalance, am_accountgl.AccountName");
        $this->db->join($this->branch,$this->branch.".BranchCode=".$this->table.".BranchCode","INNER");
        $this->db->join($this->customer,$this->customer.".CustomerCode=".$this->table.".CustomerCode","INNER");
        $this->db->join("am_accountgl","am_accountgl.AccountNumber=".$this->table.".BankReceipt","INNER");
		$this->db->join($this->comp_gl . ' as cg', 'cg.AccountNumber = at_salesreceipt.BankReceipt', 'INNER');
		$this->db->join('am_company as cp', 'cp.CompanyCode = am_branch.CompanyCode', 'INNER');
		
        $query = $this->db->get_where($this->table, array('SRecNumber' => $id));
	
        if($query->num_rows()>0){
            return $query->row();
        }
        else{
            return false;
        }      
    }

    function get_detail_print($id){
        $this->db->select($this->table.".*,".$this->branch.".BranchName, ".$this->customer.".CustomerName, ".$this->customer.".CustomerAddress, ".$this->customer.".PhoneNumber,".$this->customer.".CurrencyCode as CurrCustomer, ".$this->customer.".SaldoDPPartial,
                          ".$this->customer.".SaldoDPBalance, am_accountgl.AccountName, prepared.EmployeeName as nm_prepared, mng.EmployeeName as nm_manager");
        $this->db->join($this->branch,$this->branch.".BranchCode=".$this->table.".BranchCode","INNER");
        $this->db->join($this->customer,$this->customer.".CustomerCode=".$this->table.".CustomerCode","INNER");
        $this->db->join("am_accountgl","am_accountgl.AccountNumber=".$this->table.".BankReceipt","INNER");
        $this->db->join("am_employee as prepared","prepared.EmployeeCode=".$this->table.".CreatedBy","LEFT");
        $this->db->join("am_employee as mng","mng.EmployeeCode=".$this->table.".AppLevel1Code","LEFT");
        $query = $this->db->get_where($this->table, array('SRecNumber' => $id));
    
        if($query->num_rows()>0){
            return $query->row();
        }
        else{
            return false;
        }      
    }

    //Daswan get detail invoice to print
    function get_detail_invoice_print($Number){
        $this->db->select("(case when at_srecdetail.SRecPaidStatus = 1 then 'Yes' else 'No' end) as Paid,
                           (case when at_srecdetail.SRecInvoiceType = 0 then 'SI' when at_srecdetail.SRecInvoiceType = 1 then 'SO' when at_srecdetail.SRecInvoiceType = 2 then 'PPN' else '-' end) as InvoiceType,
                            at_srecdetail.SRecDetailID, at_salesreceipt.SRecNumber, at_srecdetail.SInvNumber as InvoiceNumber, at_srecdetail.FiscalStatus, 
                            at_srecdetail.SInvDate as InvoiceDate, at_srecdetail.SInvAmount as InvoiceAmount, at_srecdetail.SRecAmount as PaymentAmountCopy, at_srecdetail.SInvAmountTemp as InvoiceAmountCopy,
                            at_srecdetail.SRecOwing as InvoiceOwing, at_srecdetail.SRecOwing as OwingHidden, at_srecdetail.SRecDiscDate as ReceiptDiscDate, at_srecdetail.SRecRounded as BebanPembulatan, 
                            at_srecdetail.SRecDiscount as ReceiptDiscount, at_srecdetail.SRecDPUsed as ReceiptTotalDP, 
                            at_srecdetail.SRecAmount as PaymentAmount, at_srecdetail.SRecAmount as DataAmount, am_itemCategory.ItemCategoryID, am_itemCategory.ItemCategoryName, at_srecdetail.DPStatus, at_srecdetail.ItemCategoryCode, at_srecdetail.CategoryName,
                            at_srecdetail.SInvFiscalRate as InvoiceFiscalRate, at_srecdetail.SInvCurrRate as InvoiceCurrRate, at_srecdetail.SRecCurrency as PaymentCurrency,
                           (case when at_srecdetail.SRecInvoiceType = 0 then at_srecdetail.SRecDPUsed else at_srecdetail.SRecAmount end) as ReceiveTotalDP");
        $this->db->from($this->table);
        $this->db->join($this->detail, 'at_salesreceipt.SRecNumber = at_srecdetail.SRecNumber', 'INNER');
        $this->db->join('am_itemCategory', 'am_itemCategory.ItemCategoryID = at_srecdetail.ItemCategoryID', 'INNER');
        $this->db->where('at_salesreceipt.SRecNumber', $Number);
        $query = $this->db->get();
        
        return $query->result_array();
    }
	
    function get_detail_item($id) {
        $query = $this->db->get_where($this->detail, array('SRecNumber' => $id));
        return $query->result();
    }
	
	function get_detail_invoice($srec_number){
        $this->db->_protect_identifiers = false;
        $this->db->select("(case when srd.SRecPaidStatus = 1 then 'Yes' else 'No' end) as Paid,
                           (case when srd.SRecInvoiceType = 0 then 'SI' else 'SO' end) as Invoice_Type,
                            srd.SRecDetailID, srd.SInvFiscalRate as InvoiceFiscalRate, srd.InvoicePaymentID, sr.SRecNumber as PaymentNumber, srd.SInvNumber as Invoice_Number, srd.SOrdNumber as Select_DP,
                            srd.SInvDate as Invoice_Date, sum(srd.SInvAmount) as Invoice_Amount, sum(SRecOwing) as Invoice_Owing, sum(srd.SInvAmountTemp) as InvoiceAmountCopy,sum(srd.SInvAmountTemp) as InvoiceOwingHidden, 
							sum(SRecOwing) as InvoiceOwingHiddenNew,
                            srd.SRecDiscDate as Payment_DiscDate, sum(srd.SRecDiscount) as Receipt_Discount, sum(srd.SRecDPUsed) as Receipt_DP, sum(srd.SRecRounded) as Load_Rounding, srd.SRecInvoiceType,srd.SRecDate,srd.SRecTime,
                            sum(srd.SRecAmount) as Receipt_Amount, sum(srd.SRecCurrency) as Receipt_Currency, 
                            srd.SInvCurrRate as InvoiceCurrRate, srd.ItemCategoryID, 0 as UnPaid,
                           (case when SRecInvoiceType = 0 then 'Invoice' else 'Down Payment' end) as PaymentType,
                           (case when srd.SRecInvoiceType = 1 then sum(srd.SRecAmount) else sum(srd.SRecDPUsed) end) as Old_Payment_DP,
                           (case when FiscalStatus = 0 then 'Invoice' 
                                 when FiscalStatus = 1 then 'PPn Fiscal'
                                 else 'Down Payment' end) as ItemCategoryCode");
        $this->db->from($this->table . ' as sr');
        $this->db->join($this->detail . ' as srd', 'srd.SRecNumber = sr.SRecNumber', 'LEFT');
        $this->db->where('sr.SRecNumber', $srec_number);
        $this->db->group_by('Invoice_Number');
        $this->db->order_by('SInvNumber', 'ASC');
        $query = $this->db->get();
        $this->db->_protect_identifiers = false;
        
        return $query->result();
    }
    
	function check_code_exist($sr_number) {
        $query = $this->db->get_where($this->table, array('SRecNumber' => $sr_number), 1, 0);
		
        if ($query->num_rows() > 0) {
            return TRUE;
        }
        else {
            return FALSE;
        }	
    }
    
    function create_sr_number($date = '',$BankCode){
        $branch = $this->session->userdata('branch');
		
        if($date != ''){
            $month  = date('m', strtotime($date));
            $year   = date('y', strtotime($date));
        }
        else{
            $month  = date('m');
            $year   = date('y');
        }
		
		$sr_number  = $branch."/".$month.$year."SR/".$BankCode."/";
        //$sr_number	= $branch ."/". $month . $year ."SR/";
		
        $this->db->_protect_identifiers = false;
        $this->db->select('(CASE 
                              WHEN MAX(CONVERT(SUBSTR(SRecNumber, -3),signed)) IS NULL then 1
                              ELSE MAX(CONVERT(SUBSTR(SRecNumber, -3),signed)) + 1 END) as New_Number');
        $this->db->like('SRecNumber', $sr_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_sr_number = $sr_number . $number;

        while($this->check_code_exist($new_sr_number)){
            $num++;
            $long = strlen($num);
    
            if($long == 1){
                $number = '00' . $num;
            }
            elseif($long == 2){
                $number = '0' . $num;
            }
            else{
                $number = $num;
            }
            
            $new_sr_number = $sr_number . $number;		
        }
        
        return  $new_sr_number;
    }
	  
    //I am not sure with this procedure for creatr Auto Number CRV
//    function create_preq_number(){
//        $branch_code=$this->session->userdata('branch');
//        $month=date('m');
//        $year=date('y');
//
//        $preq_number    = $branch_code."/".$month.$year."SR/";
//        $this->db->like('SRecNumber',$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_preq_number_awal(){
//        $branch_code    = $this->session->userdata('branch');
//        $month          = date('m');
//        $year           = date('y');
//
//        $preq_number = $branch_code."/".$month.$year."SR";
//        $this->db->like('SRecNumber',$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;
//    }
//	
//    function create_preq_number_akhir(){
//        $branch_code=$this->session->userdata('branch');
//        $month=date('m');
//        $year=date('y');
//        
//        $preq_number=$branch_code."/".$month.$year."SR/";
//        $this->db->like('SRecNumber',$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  $number;
//    }

    function get_bank_account(){
		$CurrencyCode = $this->input->get('CurrencyCode');
		
        $this->db->select('at_compaccountgl.AccountNumber,am_accountgl.AccountName,am_bank.BankOutCode,am_bank.BankInCode, 
			am_currency.CurrencyCode,am_currency.CurrencyName,am_currency.CurrencyRate, at_compaccountgl.GLSaldoBSheet as BankBalance');
        
		$this->db->from('at_compaccountgl');
        $this->db->join('am_accountgl','at_compaccountgl.AccountNumber=am_accountgl.AccountNumber','INNER');
        $this->db->join('am_bank','am_bank.BankID=am_accountgl.BankID','INNER');
        $this->db->join('am_currency','am_accountgl.CurrencyCode=am_currency.CurrencyCode','INNER');
        
		$this->db->where('at_compaccountgl.CompanyCode',$this->session->userdata('company'));
		$this->db->where('am_bank.CompanyCode',$this->session->userdata('company'));
        $this->db->where('at_compaccountgl.BranchCode', $this->session->userdata('branch'));
        $this->db->where('at_compaccountgl.GLSaldoYears', date('Y'));
        $this->db->where('am_accountgl.AccountSubTypeID',7);
        $this->db->where('am_accountgl.AccountChild',1);
        $this->db->where('at_compaccountgl.TransStatus',2);
		$this->db->where('am_currency.CompanyCode',$this->session->userdata('company'));
		
		if($CurrencyCode != 'IDR'){
            $this->db->where_in('am_accountgl.CurrencyCode', array('IDR', $CurrencyCode));            
        }

        return $this->db->get()->result();
    }
    
	/*function get_detail_trans($id_sales_recipt){
        $this->db->select('sr.*');
        $this->db->from($this->table . ' as sr');
        
        $this->db->where('sr.SRecNumber', $id_sales_recipt);
        $query = $this->db->get();
        
        if($query->num_rows()>0){
            return $query->row();
        }
        else{
            return false;
        }
    }*/
	
	/*function get_detail_item($id_sales_recipt){
        $this->db->_protect_identifiers = FALSE;
        $this->db->select("srd.*");
        $this->db->from($this->table . ' as sr');
        $this->db->join($this->detail . ' as srd', "srd.SRecNumber = sr.SRecNumber", "INNER");
        
        $this->db->where('sr.SRecNumber', $id_sales_recipt);
        $this->db->order_by('srd.SRecDetailID', 'ASC');
        $query = $this->db->get();
        $this->db->_protect_identifiers = TRUE;
        
        return $query->result();
    }*/
	
	function reverse_trasaction($transaction_data){
		$this->db->trans_start();
        if (!empty($transaction_data['update_customer']['data'])) {
            for ($x = 0; $x < count($transaction_data['update_customer']['data']); $x++) {
                $this->m_customer->update($transaction_data['update_customer']['data'][$x],$transaction_data['update_customer']['CustomerCode'][$x]);
            }
        }
		
		if (!empty($transaction_data['update_dp']['data'])) {
            for ($x = 0; $x < count($transaction_data['update_dp']['data']); $x++) {
				 $Customercode 		= $transaction_data['update_dp']['CustomerCode'][$x];
				 $SOrdDetailDPID 	= $transaction_data['update_dp']['SOrdDetailDPID'][$x];
				 $Select_DP 		= $transaction_data['update_dp']['Select_DP'][$x];
				 
                 $this->update_so_detail_dp_by_customer($transaction_data['update_dp']['data'][$x], $Customercode, $SOrdDetailDPID, $Select_DP);
            }
        }
		
		if (!empty($transaction_data['update_so_dp']['data'])) {
            for ($x = 0; $x < count($transaction_data['update_so_dp']['data']); $x++) {
				 $SOrdNumber 		= $transaction_data['update_so_dp']['SOrdNumber'][$x];
				 
                 $this->update_so_detail_dp_by_invoice($transaction_data['update_so_dp']['data'][$x], $SOrdNumber);
            }
        }
		
		if (!empty($transaction_data['update_so']['data'])) {
            for ($x = 0; $x < count($transaction_data['update_so']['data']); $x++) {
				 $SOrdNumber 		= $transaction_data['update_so']['SOrdNumber'][$x];
                 $this->m_sales_order->update($transaction_data['update_so']['data'][$x], $SOrdNumber);
            }
        }
		
		if (!empty($transaction_data['update_pi']['data'])) {
            for ($x = 0; $x < count($transaction_data['update_pi']['data']); $x++) {
                $this->m_sales_invoice->update($transaction_data['update_pi']['data'][$x], $transaction_data['update_pi']['InvoiceNumber'][$x]);
            }
        }
		
		if (!empty($transaction_data['update_ireceipts']['data'])) {
            for ($x = 0; $x < count($transaction_data['update_ireceipts']['data']); $x++) {
                $this->update_invoicerecip($transaction_data['update_ireceipts']['data'][$x], $transaction_data['update_ireceipts']['InvoicePaymentID'][$x]);
            }
        }
		
		$this->update($transaction_data['update_receipts']['data'], $transaction_data['update_receipts']['SRecNumber']);
		
		if (!empty($transaction_data['delete_dp']['SRecNumber'])) {
            for ($x = 0; $x < count($transaction_data['delete_dp']['SRecNumber']); $x++) {
            	$this->delete_dp($transaction_data['delete_dp']['SRecNumber'][$x]);
			}
        }
		
        $this->db->trans_complete();
        if ($this->db->trans_status() === FALSE) {
            return 0;
        } else {
            return 1;
        }
	}
	
	function insert_so_detail_dp($data) {
        $this->db->insert($this->sorddetaildp, $data);
    }
	
    function insert($data) {
        $this->db->insert($this->table, $data);
    }
	
    function insert_detail($data_detail) {		
        $this->db->insert($this->detail, $data_detail);
    }
	
    function update($data, $id) {
        $this->db->update($this->table, $data, array('SrecNumber' => $id));
    }

    function update_detail($data, $id) {
        $this->db->update($this->detail, $data, array('SRecDetailID' => $id));	
    }
	
	function update_invoicerecip($data, $id) {
        $this->db->update('at_invoicereceipt', $data, array('InvoicePaymentID' => $id));
    }
	
	function update_so_detail_dp($data, $id) {
        $this->db->update('at_sorddetaildp', $data, array('SOrdNumber' => $id));
    }
	
	function update_so_detail_dp_by_invoice($data, $id) {
        $this->db->update('at_sorddetaildp', $data, array('SOrdNumber' => $id));	
    }
	
	function update_journal($data, $id, $akun_number, $invoice_number) {
        $this->db->update($this->journal, $data, array('SRecNumber' => $id, 'SRecAccountNumber' =>$akun_number, 'SInvNumber'=>$invoice_number));
    }
    
	function update_so_detail_dp_pay_before($data, $id, $pord_number, $SOrdDetailDPID) {
        $this->db->update('at_sorddetaildp', $data, array('CustomerCode' => $id, 'SOrdNumber' => $pord_number, 'SOrdDetailDPID' => $SOrdDetailDPID));	
    }
	
	function update_so_detail_dp_by_customer($data, $id, $id_detail, $sord_number) {
        $this->db->update('at_sorddetaildp', $data, array('CustomerCode' => $id, 'SOrdDetailDPID' => $id_detail, 'SOrdNumber' => $sord_number));	
    }
	
	function update_so_detail_dp_for_sr($data, $id, $SOrdDetailDPID) {
        $this->db->update('at_sorddetaildp', $data, array('CustomerCode' => $id, 'SOrdDetailDPID' => $SOrdDetailDPID));	
    }
	
	function update_sr_detail_dp_rec_before($data, $id, $sord_number, $SOrdDetailDPID) {
        $this->db->update('at_sorddetaildp', $data, array('CustomerCode' => $id, 'SOrdNumber' => $sord_number, 'SOrdDetailDPID' => $SOrdDetailDPID));	
    }
	
    function insert_journal($data) {		
        $this->db->insert($this->journal, $data);
    }

    function delete_journal($id){
        $this->db->delete($this->journal, array('SRecNumber' => $id));
    }
	
	function delete_detail($sinv_number){
		$this->db->delete($this->detail, array('SInvNumber' => $sinv_number));
    }
    
	function delete_dp($id){
		$this->db->delete($this->sorddetaildp, array('SRecNumber' => $id));
    }
	
    function get_invoice_payment_by_id($id) {
        $this->db->select('SInvNumber, SInvPaymentAmnt, SRecTotalDiscount, SRecUsedDP');
        $this->db->from($this->detail);
        $this->db->where('SRecNumber', $id); 
        $query = $this->db->get();    

        return $query->result();
        
		// if ($query->num_rows() > 0) {
			// foreach ($query->result() as $row) {
				// $SInvPaymentAmnt = $row->SInvPaymentAmnt;
			// }    

			// return $SInvPaymentAmnt;
		// }
		// else {
			// return FALSE;
		// }	
    }
	
    function get_rec_no_by_invoice($invoice) {
        $this->db->select('SrecNumber');
        $this->db->from($this->detail);
        $this->db->where('SInvNumber', $invoice); 
        $query = $this->db->get();    

        if ($query->num_rows() > 0) {
            foreach ($query->result() as $row) {
                $SrecNumber = $row->SrecNumber;
            }    
            
            return $SrecNumber;
        }
        else {
            return FALSE;
        }	
    }
	
    function get_invoice_date_by_id($id) {
        $this->db->select('SInvDate');
        $this->db->from($this->detail);
        $this->db->where('SRecNumber', $id);
        $query = $this->db->get();    
        
        if ($query->num_rows() > 0) {
            foreach ($query->result() as $row) {
                $SInvDate = $row->SInvDate;
            }    

            return $SInvDate;
        }
        else {
            return FALSE;
        }	
    }
	
    function get_journal_by_number($Number){
        $this->db->_protect_identifiers = FALSE;
        $this->db->select("at_srecjournal.SInvNumber,at_srecjournal.SRecSaldoCredit,at_srecjournal.AmountCurrency,at_srecjournal.SRecSaldoDebet,
							am_accountgl.AccountNumber,am_accountgl.AccountName");
        $this->db->join("am_accountgl","am_accountgl.AccountNumber=at_srecjournal.SRecAccountNumber","INNER");
        //$this->db->order_by('at_srecjournal.SRecAccountNumber','ASC');
		
        $query = $this->db->get_where($this->journal, array('SRecNumber' => $Number));
        $this->db->_protect_identifiers = TRUE;
        
        return $query->result();
    }
	
    function get_type($id) {
        $this->db->select('SInvType');
        $this->db->from($this->detail);
        $this->db->where('SrecNumber', $id); 
        $query = $this->db->get();    

        if ($query->num_rows() > 0) {
            foreach ($query->result() as $row) {
                $SInvType = $row->SInvType;
            }    

            return $SInvType;
        }
        else {
            return FALSE;
        }	
    }
	
    function get_by_si($si) {
        $this->db->select("at_salesreceipt.SRecNumber");
        $this->db->join('at_srecdetail','at_srecdetail.SRecNumber = at_salesreceipt.SRecNumber', 'inner');
        $this->db->where('at_srecdetail.SInvNumber', $si);
        $this->db->where('at_salesreceipt.AppLevel1Status !=', 'NULL');
        $data = $this->db->get($this->table);
        
        return $data->result();
    }
	
    function set_trans_status($id, $status) {
        $this->db->set('TransStatus', $status);
        $this->db->where('SRecNumber', $id);
        $this->db->update($this->table);
    }
	
    function check_approval($id) {
        $this->db->select('AppLevel1Status');
        $this->db->from($this->table);
        $this->db->where('SrecNumber', $id); 
        $query = $this->db->get();    

        if ($query->num_rows() > 0) {
            foreach ($query->result() as $row) {
                $AppLevel1Status = $row->AppLevel1Status;
            }    

            return $AppLevel1Status;
        }
        else {
            return 0;
        }	
    }
	
	function check_approval_status($SRecNumber){
		$query = $this->db->get_where($this->table, array('SRecNumber' => $SRecNumber, 'AppLevel1Status' => 1, 'AppLevel2Status' => 1), 1, 0);
		
		if ($query->num_rows() > 0) {
			return TRUE;
		}else {
			return FALSE;
		}
	}

//    function check_approval_status($srecnumber) {
//        $this->db->select('*');
//        $this->db->from($this->table);
//        $this->db->where('SRecNumber', $srecnumber);
//        $this->db->where('ApprovalLevel1Status', 1);
//        $query = $this->db->get();
//        
//        if($query->num_rows()>0){
//            return $query->row();
//        }
//        else{
//            return false;
//        }
//    }
    
    function get_customer_dp($id){
        $this->db->select('CustomerCode, CustSaldoDP');
        $this->db->where('CustomerCode', $id);
        $query = $this->db->get('am_customer');

        return $query->result;
    }
	
    function get_receipt_downpayment($id){
        $this->db->select('at_srecdetail.SInvAmount, at_srecdetail.SInvOwing, at_srecdetail.SInvPaymentAmnt, at_srecdetail.SInvPaidStatus, 
                           at_srecdetail.SInvDate, at_srecdetail.SrecNumber, at_srecdetail.SInvNumber,at_salesreceipt.SRecDesc');
        $this->db->join('at_salesreceipt', 'at_salesreceipt.SrecNumber = at_srecdetail.SrecNumber', 'inner');
        $this->db->where('at_srecdetail.SInvNumber', $id);
        $query = $this->db->get('at_srecdetail');
        $this->db->_protect_identifiers = TRUE;

        return $query->result();      
    }
	
	function get_dp_account($id) {
        $this->db->select('AccountNumber');
		$this->db->from('sys_salesaccount');
		$this->db->where('AccountCode', 'AdvanceSales'); 
		$query = $this->db->get();    
        
		if ($query->num_rows() > 0) {
			foreach ($query->result() as $row) {
				$AccountNumber = $row->AccountNumber;
			}    

			return $AccountNumber;
		}
		else {
			return FALSE;
		}	
    }
	
    function get_diskon_account($id) {
        $this->db->select('AccountNumber');
        $this->db->from('sys_salesaccount');
        $this->db->where('AccountCode', 'ReceiveDiscount'); 
        $query = $this->db->get();    

        if ($query->num_rows() > 0) {
            foreach ($query->result() as $row) {
                $AccountNumber = $row->AccountNumber;
            }    

            return $AccountNumber;
        }
        else {
            return FALSE;
        }	
    }

    function get_invoice_date($customer_code){
        $this->db->select('SRecDate, NetDueIn');
        $this->db->join('at_srecdetail', 'at_srecdetail.SrecNumber = at_salesreceipt.SrecNumber');
        $this->db->join('at_salesinvoice', 'at_salesinvoice.SInvNumber = at_srecdetail.SInvNumber');
        $this->db->join('am_termspayment', 'am_termspayment.TermsPaymentID = at_salesinvoice.TermsPaymentID');
        $this->db->where('at_salesinvoice.BranchCode', $this->session->userdata('branch'));
        $this->db->where('at_salesinvoice.CustomerCode', $customer_code);
        $this->db->order_by('SRecDate', 'DESC');
        $this->db->limit('1');
        $query = $this->db->get($this->table);
        
        return $query->result();
    }
    
     function get_invoice_date_by_so($customer_code){
        $this->db->select('SRecDate, SOrdDate, NetDueIn');
        $this->db->join('at_srecdetail', 'at_srecdetail.SrecNumber = at_salesreceipt.SrecNumber', 'INNER');
        $this->db->join('at_salesorder', 'at_salesorder.SOrdNumber = at_srecdetail.SInvNumber', 'LEFT');
        $this->db->join('am_termspayment', 'am_termspayment.TermsPaymentID = at_salesorder.TermsPaymentID', 'LEFT');
        $this->db->where('at_salesorder.BranchCode', $this->session->userdata('branch'));
        $this->db->where('at_salesorder.CustomerCode', $customer_code);
        $this->db->order_by('SRecDate', 'DESC');
        $this->db->limit('1');
        $query = $this->db->get($this->table);
        
        return $query->result();
    }
    
	function get_invoice_recip($invoice_number, $invoice_type, $ppn_fiscal){
        $this->db->select('InvoiceNumber,InvoicePaymentID,ItemCategoryID,ItemCategoryCode,ItemCategoryRatio
							InvoiceAmount,InvoiceType');
        $this->db->from('at_invoicereceipt');
        $this->db->where('InvoiceNumber', $invoice_number);
        $this->db->where('InvoiceType', $invoice_type);
        $this->db->where('PPnFiscalStatus', $ppn_fiscal);
        $this->db->order_by('InvoicePaymentID', 'ASC');
        $query = $this->db->get();
        
        return $query->result();
    }
	
	/*function get_invoice_recip_no_fiscal($invoice_number, $invoice_type){
        $this->db->select('*');
        $this->db->from('at_invoicereceipt');
        $this->db->where('InvoiceNumber', $invoice_number);
        $this->db->where('InvoiceType', $invoice_type);
       // $this->db->where('PPnFiscalStatus', $ppn_fiscal);
        $this->db->order_by('InvoicePaymentID', 'ASC');
        $query = $this->db->get();
        
        return $query->result();
    }*/
	
	/*function get_invoice_recip_grouping($invoice_number, $invoice_type, $ppn_fiscal){
		$this->db->select('SUM(InvoiceOwing-SRecAmntBooked+JVoucherBalance) AS TotalOwing');
        $this->db->from('at_invoicereceipt');
        $this->db->where('InvoiceNumber', $invoice_number);
        $this->db->where('InvoiceType', $invoice_type);
        $this->db->where('PPnFiscalStatus', $ppn_fiscal);
        $this->db->order_by('InvoicePaymentID', 'ASC');
        $query = $this->db->get();
        
		if($query->num_rows() > 0) {
            return $query->result();
        }    
        else {
            return false;
        }
    }*/
	
    //Return Wrong Data
//    function get_date_invoice($invoice) {
//        $this->db->select('SInvDate');
//        $this->db->from($this->detail);
//        $this->db->where('SInvNumber', $invoice); 
//        $this->db->order_by($this->detail.'.SInvDate','DESC');
//        $query = $this->db->get();    
//
//        if ($query->num_rows() > 0) {
//            foreach ($query->result() as $row) {
//                $SInvDate = $row->SInvDate;
//            }    
//
//            return $SInvDate;
//        }
//        else {
//            return FALSE;
//        }	
//    }
	
	function get_saldo_detail_dp($id, $SOrdNumber, $status_transaction) {
        $this->db->select('SOrdTotalDP, Owing, PaymentAmount, CustomerCode, SaldoDPBalance, CurrencyRate, DPUsedBook, IsEdit, SOrdDetailDPID, DPUsed, SOrdStatus, JVoucherBalance');
        $this->db->from('at_sorddetaildp');
        $this->db->where('CustomerCode', $id); 
		if($status_transaction == 1){
			$this->db->where('SOrdNumber', $SOrdNumber);
		}
		
        $query = $this->db->get();    

        return $query->result();
    }
	
	function get_saldo_detail_dp_sales_journal($id) {
        $this->db->select('SOrdTotalDP, Owing, PaymentAmount, CustomerCode, SaldoDPBalance, CurrencyRate, DPUsedBook, IsEdit, SOrdDetailDPID, DPUsed, SOrdStatus, JVoucherBalance');
        $this->db->from('at_sorddetaildp');
        $this->db->where('SOrdNumber', $id);
		
        $query = $this->db->get();    

        return $query->result();
    }
	
	function get_saldo_detail_dp_approve_by_inv($id) {
        $this->db->select('SOrdTotalDP, Owing, PaymentAmount, CustomerCode, SaldoDPBalance, CurrencyRate, DPUsedBook, IsEdit, SOrdDetailDPID, DPUsed');
        $this->db->from('at_sorddetaildp');
        $this->db->where('SOrdNumber', $id);
		$this->db->where('(DPUsed - SaldoDPBalance) != ', 0);
        $query = $this->db->get();    

        return $query->result();
    }
	
	function get_saldo_detail_dp_approve($id) {
        $this->db->select('SOrdTotalDP, Owing, PaymentAmount, CustomerCode, SaldoDPBalance, CurrencyRate, DPUsedBook, IsEdit, SOrdDetailDPID, DPUsed');
        $this->db->from('at_sorddetaildp');
        $this->db->where('CustomerCode', $id);
		$this->db->where('(DPUsed - SaldoDPBalance) != ', 0);
        $query = $this->db->get();    

        return $query->result();
    }
	
    function get_dept($code) {
        $this->db->select('DepartmentName');
        $this->db->from('am_department');
        $this->db->where('DepartmentCode', $code); 
        $query = $this->db->get();    

        if ($query->num_rows() > 0) {
            foreach ($query->result() as $row) {
                $DepartmentName = $row->DepartmentName;
            }    

            return $DepartmentName;
        }
        else {
            return FALSE;
        }	
    }
	
	/*function get_sordetail_new($id) {
        $this->db->select('SOrdStatus, SOrdDetailDPID');
        $this->db->from('at_sorddetaildp');
        $this->db->where('CustomerCode', $id);
		//$this->db->where('SOrdStatus !=', 1);
        $query = $this->db->get();    

        return $query->row();
    }*/
	
	function get_journal_recip_empty($akun, $id, $invoice_number){
		$this->db->_protect_identifiers = FALSE;
	    $this->db->select("at_srecjournal.SRecAccountNumber, at_srecjournal.SRecSaldoDebet, at_srecjournal.SRecSaldoCredit, at_srecjournal.AmountCurrency, at_srecjournal.SRecJournalID");
		$this->db->from($this->journal);
		$this->db->join('at_srecdetail', 'at_srecdetail.SRecNumber = at_srecjournal.SRecNumber', 'INNER');
		
		$this->db->where('at_srecjournal.SRecAccountNumber', $akun); 
		$this->db->where('at_srecjournal.SRecNumber', $id); 
		$this->db->where('at_srecjournal.SInvNumber', $invoice_number); 
		$query = $this->db->get();
		$this->db->_protect_identifiers = TRUE;
		return $query->row();
    }
	
	function get_customer_for_lock_status($customer_code) {
        $this->db->select('CustomerCode, CustomerName, LockStatus');
        $this->db->from('am_customer');
        $this->db->where('CustomerCode', $customer_code);
		$this->db->where('TransStatus', 1);
		
        $query = $this->db->get();    
		
		if ($query->num_rows() > 0) {
           return $query->row();
        }
        else {
            return FALSE;
        }
    } 
	
	function get_sales_receipt($SInvNumber) {
        $this->db->select('at_srecdetail.SInvNumber');
        $this->db->from('at_srecdetail');
		$this->db->join('at_salesreceipt', 'at_salesreceipt.SRecNumber = at_srecdetail.SRecNumber', 'INNER');
		
       	$this->db->where('at_srecdetail.SInvNumber', $SInvNumber); 
		$this->db->where_in('at_salesreceipt.TransStatus', array(3,8,9)); 
		
        $query = $this->db->get();    
        
        if ($query->num_rows() > 0) {
            return $query->result();
        }
        else {
            return false;
        }	
    }
	
	function get_sordetail_dp_balance($customer_code) {
		$this->db->_protect_identifiers = FALSE;
        $this->db->select("sum(SaldoDPBalance) as SaldoDPBalance, sum(SaldoDPBalance - DPUsed) as DownPayment");
        $this->db->from('at_sorddetaildp');
        $this->db->where('CustomerCode', $customer_code); 
		$this->db->where('StatusDPFor', 1);
		//$this->db->where('(SaldoDPBalance - DPUsed) >', 0);
        $query = $this->db->get();    
		$this->db->_protect_identifiers = TRUE;

        if($query->num_rows() > 0){
            return $query->row();
        }
        else{
            return false;
        }	
    } 
	
	function get_sordetail_dp_balance_invoice($customer_code) {
		$this->db->_protect_identifiers = FALSE;
        $this->db->select("sum(SaldoDPBalance - DPUsed) as DownPayment, sum(SaldoDPBalance) as DownPayment_Partial");
        $this->db->from('at_sorddetaildp');
        $this->db->where('CustomerCode', $customer_code); 
		$this->db->where('StatusDPFor', 0);
		$this->db->group_by('CustomerCode'); 
		
        $query = $this->db->get();    
		$this->db->_protect_identifiers = TRUE;

        if($query->num_rows() > 0){
            return $query->row();
        }
        else{
            return false;
        }	
    } 
	
	function get_saldo_detail_dp_new($id) {
		
		$this->db->_protect_identifiers = FALSE;
		$this->db->select("at_sorddetaildp.SOrdNumber, sum(at_sorddetaildp.SaldoDPBalance - at_sorddetaildp.DPUsed) as ReceiptAmount_SUM, at_sorddetaildp.SOrdDetailDPID,
							at_sorddetaildp.SaldoDPBalance - at_sorddetaildp.DPUsed as Payment_Used, at_sorddetaildp.CustomerCode, 'No' as Status");	
		//$this->db->join('at_ppaydetail', 'at_ppaydetail.POrdDetailDPID = at_sorddetaildp.POrdDetailDPID', 'LEFT');
			
        $this->db->from('at_sorddetaildp');
        $this->db->where('at_sorddetaildp.CustomerCode', $id); 
		$this->db->where('at_sorddetaildp.StatusDPFor', 1);
		$this->db->where_in('at_sorddetaildp.IsEdit', array(1,0));
		$this->db->where('(at_sorddetaildp.SaldoDPBalance - at_sorddetaildp.DPUsed) > ', 0);
		$this->db->group_by('at_sorddetaildp.SOrdNumber');
		
        $query = $this->db->get();    
		$this->db->_protect_identifiers = TRUE;
		
        return $query->result();
    }
	
	function get_receipt($invoice_number, $invoice_type, $ppn_fiscal){
        $this->db->select('InvoicePaymentID,ItemCategoryCode,ItemCategoryID,ItemType,ItemCategoryRatio,InvoiceOwing,InvoiceAmount,InvoiceCurrRate,InvoiceNumber');
        $this->db->from($this->receipt);
        $this->db->where('InvoiceNumber', $invoice_number);
        $this->db->where('InvoiceType', $invoice_type);
        $this->db->where('PPnFiscalStatus', $ppn_fiscal);
        $this->db->order_by('InvoicePaymentID', 'ASC');
        $query = $this->db->get();
        
        return $query->result();
    }
	
	function get_receipt_by_id($invoice_payment_id){
        $this->db->select('ItemCategoryRatio,ItemType,InvoiceNumber,InvoiceOwing,ReceiptDiscount,ReceiptDPUsed,ReceiptAmount,ReceiptTotal,ReceiptCurrency,ReceiptRounded');
        $this->db->from($this->receipt);
        $this->db->where('InvoicePaymentID', $invoice_payment_id);
        $query = $this->db->get();
        
        return $query->result();
    }
	
	function get_saldo_detail_dp_update($id) {
		$this->db->_protect_identifiers = FALSE;
		$this->db->select("at_sorddetaildp.SOrdNumber, at_sorddetaildp.SaldoDPBalance - at_sorddetaildp.DPUsed as PaymentAmount_SUM, at_sorddetaildp.SOrdDetailDPID,
							at_sorddetaildp.SaldoDPBalance - at_sorddetaildp.DPUsed as Payment_Used, at_sorddetaildp.CustomerCode, 'No' as Status");	
		//$this->db->join('at_ppaydetail', 'at_ppaydetail.POrdDetailDPID = at_sorddetaildp.POrdDetailDPID', 'LEFT');
			
        $this->db->from('at_sorddetaildp');
        $this->db->where('at_sorddetaildp.CustomerCode', $id); 
		$this->db->where('at_sorddetaildp.StatusDPFor', 1);
		$this->db->where("(((at_sorddetaildp.SaldoDPBalance - at_sorddetaildp.DPUsed) > 0) OR (at_sorddetaildp.IsEdit = 1))");
		
        $query = $this->db->get();    
		$this->db->_protect_identifiers = TRUE;
		
        return $query->result();
    } 
	
	
	function get_saldo_detail_dp_pop_up($id) {
		$this->db->_protect_identifiers = FALSE;
		$this->db->select("at_sorddetaildp.SOrdNumber, at_sorddetaildp.SaldoDPBalance - at_sorddetaildp.DPUsed as PaymentAmount_SUM, at_sorddetaildp.SOrdDetailDPID,
							at_sorddetaildp.SaldoDPBalance - at_sorddetaildp.DPUsed as Payment_Used, at_sorddetaildp.CustomerCode, 'No' as Status");	
		//$this->db->join('at_ppaydetail', 'at_ppaydetail.POrdDetailDPID = at_sorddetaildp.POrdDetailDPID', 'LEFT');
			
        $this->db->from('at_sorddetaildp');
        $this->db->where('at_sorddetaildp.CustomerCode', $id); 
		$this->db->where('at_sorddetaildp.StatusDPFor', 0);
		//$this->db->where('(at_sorddetaildp.SaldoDPBalance - at_sorddetaildp.DPUsed) > 0');
		$this->db->where('at_sorddetaildp.IsEdit', 0);
		//$this->db->group_by('at_sorddetaildp.POrdNumber');
		
        $query = $this->db->get();    
		$this->db->_protect_identifiers = TRUE;
		
        return $query->result();
    } 
	
	function get_saldo_detail($SOrdDetailDPID, $CustomerCode, $SRecNumber){
		$this->db->select("at_srecjournal.AmountCurrency, at_srecjournal.SRecSaldoDebet");
		$this->db->from('at_srecjournal');
		$this->db->join('at_salesreceipt', 'at_salesreceipt.SRecNumber = at_srecjournal.SRecNumber', 'INNER');
		
		$this->db->where('at_salesreceipt.CustomerCode', $CustomerCode); 
		$this->db->where('at_srecjournal.SOrdDetailDPID', $SOrdDetailDPID); 
		$this->db->where('at_salesreceipt.SRecNumber', $SRecNumber);
		$this->db->where('at_salesreceipt.TransStatus', 4); 
		//$this->db->where_in('at_srecjournal.SRecAccountNumber', array('2-2-01-001-00','2-2-01-002-00'));
		
		$query = $this->db->get();  
		if($query->num_rows() > 0){
            return $query->row();
        }
        else{
            return false;
        }	
	}
	
	function get_receipt_detail_dp_update($id, $akun_number) {
		$this->db->_protect_identifiers = FALSE;
		$this->db->select("at_sorddetaildp.SOrdStatus, at_sorddetaildp.JVoucherBalance, at_sorddetaildp.SOrdTotalDP, at_sorddetaildp.Owing, 
							at_sorddetaildp.PaymentAmount, at_sorddetaildp.CustomerCode, at_sorddetaildp.SaldoDPBalance, at_sorddetaildp.SOrdNumber, 
							at_sorddetaildp.CurrencyRate, at_sorddetaildp.DPUsedBook, at_sorddetaildp.IsEdit, at_sorddetaildp.SOrdDetailDPID, 
							at_sorddetaildp.DPUsed, at_srecjournal.AmountCurrency, at_srecjournal.SRecSaldoDebet");
		$this->db->join('at_salesreceipt', 'at_salesreceipt.SRecNumber = at_srecjournal.SRecNumber', 'INNER');
		$this->db->join('at_sorddetaildp', 'at_sorddetaildp.SOrdDetailDPID = at_srecjournal.SOrdDetailDPID', 'INNER');
		
        $this->db->from('at_srecjournal');
        $this->db->where('at_sorddetaildp.CustomerCode', $id); 
		
		$this->db->where('at_srecjournal.SRecAccountNumber', $akun_number); 
		$this->db->where_in('at_salesreceipt.TransStatus', array(4));
		
        $query = $this->db->get();    
		$this->db->_protect_identifiers = TRUE;
		
        return $query->result();
    } 
	
	function get_receipt_detail($sinv_number, $srec_number){
        $this->db->select('SRecDetailID,ItemCategoryID,ItemCategoryCode,ItemCategoryRatio,SInvCurrRate,InvoicePaymentID,SRecCurrency,SRecDiscDate,
							SRecDPUsed,SRecDiscount,SrecRounded,SRecAmount,SRecTotalAmnt');
        $this->db->from($this->detail);
        $this->db->where('SInvNumber', $sinv_number);
        $this->db->where('SRecNumber', $srec_number);
        $this->db->order_by('SRecDetailID', 'ASC');
        $query = $this->db->get();
        
        return $query->result();
    }
	
	function set_finish_invoice($id) {
        $this->db->select('sum(InvoiceOwing) as InvoiceOwing');
        $this->db->from($this->receipt);
        $this->db->where('InvoiceNumber', $id);
        $query = $this->db->get();

        if($query->num_rows() > 0){
			return $query->result();
        }
        else{
            return false;
        }		
    } 
	
	function get_detail_for_suspend($srec_number){
        $this->db->select("sr.*, ssd.SRecInvoiceType, ssd.SRecAmount, ssd.SRecDPUsed, ssd.SOrdNumber");
        $this->db->from($this->table . ' as sr');
        $this->db->join($this->detail . ' as ssd', 'ssd.SRecNumber = sr.SRecNumber', 'INNER');
        $this->db->where('sr.SRecNumber', $srec_number);        
        $query = $this->db->get();
        
        if($query->num_rows()>0){
            return $query->row();
        }
        else{
            return false;
        }      
    }
	
	function get_payment_detail_dp_suspend($id, $SOrdNumber, $akun_number) {
		$this->db->_protect_identifiers = FALSE;
		$this->db->select("at_sorddetaildp.SOrdStatus, at_sorddetaildp.JVoucherBalance, at_sorddetaildp.SOrdTotalDP, at_sorddetaildp.Owing, 
							at_sorddetaildp.PaymentAmount, at_sorddetaildp.CustomerCode, at_sorddetaildp.SaldoDPBalance, at_sorddetaildp.SOrdNumber, 
							at_sorddetaildp.CurrencyRate, at_sorddetaildp.DPUsedBook, at_sorddetaildp.IsEdit, at_sorddetaildp.SOrdDetailDPID, 
							at_sorddetaildp.DPUsed, at_srecjournal.AmountCurrency, at_srecjournal.SRecSaldoDebet");
		$this->db->join('at_salesreceipt', 'at_salesreceipt.SRecNumber = at_srecjournal.SRecNumber', 'INNER');
		$this->db->join('at_sorddetaildp', 'at_sorddetaildp.SOrdDetailDPID = at_srecjournal.SOrdDetailDPID', 'INNER');
		
        $this->db->from('at_srecjournal');
        $this->db->where('at_sorddetaildp.CustomerCode', $id); 
		
		$this->db->where('at_sorddetaildp.SOrdNumber', $SOrdNumber); 
		$this->db->where('at_srecjournal.SRecAccountNumber', $akun_number); 
		$this->db->where_in('at_salesreceipt.TransStatus', array(4));
		
        $query = $this->db->get();    
		$this->db->_protect_identifiers = TRUE;
		
        return $query->result();
    } 
	
	function get_sordetail_dp_invoice_or_return($customer_code, $SOrdNumber, $status_transaction) {
        $this->db->select('SOrdTotalDP, Owing, PaymentAmount, CustomerCode, SaldoDPBalance, CurrencyRate, DPUsedBook, IsEdit, SOrdDetailDPID, DPUsed, SOrdStatus, JVoucherBalance');
        $this->db->from('at_sorddetaildp');
        $this->db->where('CustomerCode', $customer_code); 
		$this->db->where('SOrdNumber', $SOrdNumber); 
		$this->db->where('StatusDPFor', $status_transaction); 
		$this->db->where('(SaldoDPBalance - DPUsedBook) >', 0);
		
        $query = $this->db->get();    

        return $query->result();
    }
	
	function get_sales_receipt_for_dp($SOrdNumber, $CustomerCode){
        $this->db->select('at_srecdetail.SInvNumber');
        $this->db->from('at_srecdetail');
		$this->db->join('at_salesreceipt', 'at_salesreceipt.SRecNumber = at_srecdetail.SRecNumber', 'INNER');
		
        $this->db->where('at_srecdetail.SInvNumber', $SOrdNumber);
        $this->db->where('at_salesreceipt.CustomerCode', $CustomerCode);
		$this->db->where_in('at_salesreceipt.TransStatus', array(4,5,6));
        $query = $this->db->get();
        
        if($query->num_rows() > 0){
            return true;
        }
        else{
            return false;
        }	
    }

	function get_sales_receipt_on_finshed($CustomerCode){
        $this->db->select('sum(at_srecdetail.SRecTotalAmnt) as SRecTotalAmnt, at_srecdetail.SRecNumber');
        $this->db->from('at_salesreceipt');
		$this->db->join('at_srecdetail', 'at_srecdetail.SRecNumber = at_salesreceipt.SRecNumber', 'INNER');
        $this->db->where('at_salesreceipt.CustomerCode', $CustomerCode);
		$this->db->where('at_srecdetail.ItemCategoryCode !=', 'PPn Fiscal');
		$this->db->where('at_srecdetail.SRecInvoiceType', 0);
		$this->db->where_in('at_salesreceipt.TransStatus', array(2));
		$this->db->group_by('at_salesreceipt.SrecNumber');
		
        $query = $this->db->get();
        
        if($query->num_rows() > 0){
            return $query->result();
        }
        else{
            return false;
        }	
    }
	
	function get_sales_receipt_on_finshed_fiscal_new($CustomerCode){
        $this->db->select('sum(at_srecdetail.SRecTotalAmnt / at_srecdetail.SInvFiscalRate) as SRecTotalAmnt, at_srecdetail.SRecNumber, at_srecdetail.SInvFiscalRate');
        $this->db->from('at_salesreceipt');
		$this->db->join('at_srecdetail', 'at_srecdetail.SRecNumber = at_salesreceipt.SRecNumber', 'INNER');
        $this->db->where('at_salesreceipt.CustomerCode', $CustomerCode);
		$this->db->where('at_srecdetail.ItemCategoryCode', 'PPn Fiscal');
		$this->db->where_in('at_salesreceipt.TransStatus', array(2));
		$this->db->group_by('at_salesreceipt.SrecNumber');
		
        $query = $this->db->get();
        
        if($query->num_rows() > 0){
            return $query->result();
        }
        else{
            return false;
        }	
    }
	
	function get_sordetail_dp($id,$SOrdNumber) {
		$this->db->_protect_identifiers = FALSE;
		$this->db->select("PaymentAmount");	
		//$this->db->join('at_ppaydetail', 'at_ppaydetail.POrdDetailDPID = at_sorddetaildp.POrdDetailDPID', 'LEFT');
			
        $this->db->from('at_sorddetaildp');
        $this->db->where('at_sorddetaildp.CustomerCode', $id);
		$this->db->where('at_sorddetaildp.SOrdNumber', $SOrdNumber); 
		$this->db->where('at_sorddetaildp.StatusDPFor', 0);
		
		$this->db->where('at_sorddetaildp.IsEdit', 0);
		//$this->db->group_by('at_sorddetaildp.POrdNumber');
		
        $query = $this->db->get();    
		$this->db->_protect_identifiers = TRUE;
		
        return $query->result();
    } 
	
	function get_sales_order_dp_detail($SInvNumber){
        $this->db->select('at_srecdetail.SRecDate,at_srecdetail.SRecTime,at_srecdetail.SrecNumber');
        $this->db->from('at_srecdetail');
		$this->db->join('at_salesreceipt', 'at_salesreceipt.SrecNumber = at_srecdetail.SrecNumber', 'INNER');
		
        $this->db->where('at_srecdetail.SInvNumber', $SInvNumber);
		$this->db->where('at_salesreceipt.TransStatus', 2);
		$this->db->group_by('at_srecdetail.SrecNumber');
		$this->db->order_by('at_srecdetail.SRecTime', 'ASC');
		
        $query = $this->db->get();
        
        if($query->num_rows() > 0){
            return $query->result();
        }
        else{
            return false;
        }	
    }
	
	function get_sales_receipt_dp_used($SOrdNumber){
        $this->db->select('at_srecdetail.SRecNumber');
        $this->db->from('at_srecdetail');
		$this->db->join('at_salesreceipt', 'at_salesreceipt.SrecNumber = at_srecdetail.SrecNumber', 'INNER');
        $this->db->where('at_srecdetail.SOrdNumber', $SOrdNumber);
		$this->db->where('at_salesreceipt.TransStatus !=', 3);
		$this->db->group_by('at_srecdetail.SInvNumber');
		$this->db->order_by('at_srecdetail.SInvNumber', 'ASC');
		
        $query = $this->db->get();
        
        if($query->num_rows() > 0){
            return $query->row();
        }
        else{
            return false;
        }	
    }
	
	function get_sales_dp_useddp($SOrdNumber){
        $this->db->select('at_salesdp.SDpayNumber');
        $this->db->from('at_salesdp');
		
        $this->db->where('at_salesdp.SOrdNumber', $SOrdNumber);
		$this->db->where('at_salesdp.TransStatus !=', 3);
		$this->db->order_by('at_salesdp.SOrdNumber', 'ASC');
		
        $query = $this->db->get();
        
        if($query->num_rows() > 0){
            return $query->row();
        }
        else{
            return false;
        }	
    }
}

/* End of file m_sales_receipt.php */
/* Location: ./application/models/m_sales_receipt.php */