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

class M_sales_return extends CI_Model {

	public $table = "at_salesreturn";
	public $detail = "at_sretdetail";
	public $journal = "at_sretjournal";
	
	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_salesreturn.TransStatus, at_salesreturn.SRetNumber, at_salesreturn.SRetdate, at_salesreturn.SRetDesc, at_salesreturn.SInvNumber, am_employee.EmployeeName, at_salesreturn.CreatedBy,
		at_salesreturn.CustomerCode, at_salesreturn.BranchCode, am_customer.CustomerName, am_branch.BranchName");
		$this->db->from('at_salesreturn');
		$this->db->join('am_customer', 'am_customer.CustomerCode = at_salesreturn.CustomerCode', 'inner');
		$this->db->join('am_employee', 'am_employee.EmployeeCode = at_salesreturn.SalesmanCode', 'left');
		$this->db->join('am_branch', 'am_branch.BranchCode = at_salesreturn.BranchCode', 'inner');
		
		$this->db->where('at_salesreturn.BranchCode',$this->session->userdata('branch'));
		
		/*===================================find by number dan desc=========================================================*/
		if($Number != ""){$this->db->like('at_salesreturn.SRetNumber', $Number);}
		if($Desc != ""){$this->db->like('at_salesreturn.SRetDesc', $Desc);}
		/*=============================================end===================================================================*/
		
		/*===================================find by branch code=========================================================*/
		/*
			get data dari  combobox find di view
		*/
        if($BranchCode != ""){
			$this->db->where('at_salesreturn.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_salesreturn.BranchCode', $sess_branch);
			//-----------------------end-------------------------------------------------//
		}
		/*=======================================================end========================================================*/
		
		/*=====================================================find by date==================================================*/
		if((($DateFrom != '') && ($DateTo != ''))){
            if($DateFrom <= $DateTo){
				$this->db->where('at_salesreturn.SRetdate >=', date("Y-m-d", strtotime($DateFrom)));
            	$this->db->where('at_salesreturn.SRetdate <=', date("Y-m-d", strtotime($DateTo)));
			}
        }
		/*======================================================end===========================================================*/
		
		/*=====================================================find by status==================================================*/
		if($TransStatus!=''){ 
			$this->db->where_in('at_salesreturn.TransStatus',$TransStatus); 
		}
		else{
			/*
				trans status 0,1 adalah aktif
			*/
			$this->db->where_in('at_salesreturn.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.'.SRetNumber', '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'] : '';
		/*============================================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_salesreturn.TransStatus, at_salesreturn.SRetNumber, at_salesreturn.SRetdate, at_salesreturn.SRetDesc, at_salesreturn.SInvNumber, am_employee.EmployeeName, at_salesreturn.CreatedBy,
		at_salesreturn.CustomerCode, at_salesreturn.BranchCode, am_customer.CustomerName, 
		(case 
                                when at_salesreturn.TransStatus = 0 then 'Waiting' 
                                when at_salesreturn.TransStatus = 1 then 'On Progress' 
                                when at_salesreturn.TransStatus = 2 then 'Active' 
                                when at_salesreturn.TransStatus = 3 then 'Suspended' 
                                when at_salesreturn.TransStatus = 4 then 'Need Mgr. App.' 
                                when at_salesreturn.TransStatus = 5 then 'Need Dir. App.' 
                                when at_salesreturn.TransStatus = 6 then 'Need Dir & Mgr App.' end) as Status,
		am_branch.BranchName");
		$this->db->from('at_salesreturn');
		$this->db->join('am_customer', 'am_customer.CustomerCode = at_salesreturn.CustomerCode', 'inner');
		$this->db->join('am_employee', 'am_employee.EmployeeCode = at_salesreturn.SalesmanCode', 'left');
		$this->db->join('am_branch', 'am_branch.BranchCode = at_salesreturn.BranchCode', 'inner');
		
		$this->db->where('at_salesreturn.BranchCode',$this->session->userdata('branch'));
		
		/*===================================find by number dan desc=========================================================*/
		if($Number != ""){$this->db->like('at_salesreturn.SRetNumber', $Number);}
		if($Desc != ""){$this->db->like('at_salesreturn.SRetDesc', $Desc);}
		/*=============================================end===================================================================*/
		
		/*===================================find by branch code=========================================================*/
		/*
			get data dari  combobox find di view
		*/
        if($BranchCode != ""){
			$this->db->where('at_salesreturn.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_salesreturn.BranchCode', $sess_branch);
			//-----------------------end-------------------------------------------------//
		}
		/*=======================================================end========================================================*/
		
		/*=====================================================find by date==================================================*/
		if((($DateFrom != '') && ($DateTo != ''))){
            if($DateFrom <= $DateTo){
				$this->db->where('at_salesreturn.SRetdate >=', date("Y-m-d", strtotime($DateFrom)));
            	$this->db->where('at_salesreturn.SRetdate <=', date("Y-m-d", strtotime($DateTo)));
			}
        }
		/*======================================================end===========================================================*/
		
		/*=====================================================find by status==================================================*/
		if($TransStatus!=''){ 
			$this->db->where_in('at_salesreturn.TransStatus',$TransStatus); 
		}
		else{
			/*
				trans status 0,1 adalah aktif
			*/
			$this->db->where_in('at_salesreturn.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.'.SRetNumber', 'ASC');
		/*===============================end=================================================================================*/
		$query  = $this->db->limit($end, $beginning);
		$query = $this->db->get();
		return $query->result();
    }
	
	function get_detail($id){    
		$this->db->_protect_identifiers = FALSE;
	    $this->db->select('
			at_salesreturn.SRetdate, at_salesreturn.SRetNumber, at_salesreturn.SRetDesc, at_salesreturn.SInvNumber, 
			at_salesreturn.SRetSubTotal, at_salesreturn.SRetDiscPcnt, at_salesreturn.SRetDiscount, at_salesreturn.SRetTotalAmount,  
			at_salesreturn.BranchCode, at_salesreturn.CustomerCode, at_salesreturn.SRetPPNOut, at_salesreturn.SRetPPNPcnt, at_salesreturn.SRetTaxesStatus,at_salesreturn.SInvDate,
			at_salesreturn.SRetInTaxStatus, at_salesreturn.CurrencyRate, at_salesreturn.FiscalRate, 
			at_salesreturn.AppLevel1Status, at_salesreturn.AppLevel1Code, at_salesreturn.AppLevel1Date, at_salesreturn.TransStatus,
			at_salesinvoice.SInvTaxesStatus, at_salesinvoice.SInvInTaxStatus, at_salesreturn.BillingAddress, at_salesreturn.ShippingAddress, at_salesinvoice.CurrencyCode,
			am_branch.BranchName, am_customer.CustomerName, at_salesinvoice.AppLevel1Status,at_salesreturn.CreatedBy
		');
        $this->db->join('at_salesinvoice', 'at_salesinvoice.SInvNumber = at_salesreturn.SInvNumber', 'inner');
		//$this->db->join('am_employee', 'am_employee.EmployeeCode = at_salesreturn.SalesmanCode', 'inner');
		$this->db->join('am_customer', 'am_customer.CustomerCode = at_salesreturn.CustomerCode', 'inner');
		$this->db->join('am_branch', 'am_branch.BranchCode = at_salesreturn.BranchCode', 'inner');
		$this->db->where('at_salesreturn.SRetNumber', $id);
		$query = $this->db->get($this->table);
		$this->db->_protect_identifiers = TRUE;
        return $query->row();
    }

    function get_detail_print($id){    
		$this->db->_protect_identifiers = FALSE;
	    $this->db->select('
			at_salesreturn.SRetdate, at_salesreturn.SRetNumber, at_salesreturn.SRetDesc, at_salesreturn.SInvNumber, 
			at_salesreturn.SRetSubTotal, at_salesreturn.SRetDiscPcnt, at_salesreturn.SRetDiscount, at_salesreturn.SRetTotalAmount,  
			at_salesreturn.BranchCode, at_salesreturn.CustomerCode, at_salesreturn.SRetPPNOut, at_salesreturn.SRetPPNPcnt, at_salesreturn.SRetTaxesStatus,at_salesreturn.SInvDate,
			at_salesreturn.SRetInTaxStatus, at_salesreturn.CurrencyRate, at_salesreturn.FiscalRate, 
			at_salesreturn.AppLevel1Status, at_salesreturn.AppLevel1Code, at_salesreturn.AppLevel1Date, at_salesreturn.TransStatus,
			at_salesinvoice.SInvTaxesStatus, at_salesinvoice.SInvInTaxStatus, at_salesinvoice.BillingAddress, at_salesinvoice.ShippingAddress, at_salesinvoice.CurrencyCode,
			am_branch.BranchName, am_customer.CustomerName, am_customer.CustomerAddress, am_customer.PhoneNumber, at_salesinvoice.AppLevel1Status, prepared.EmployeeName as nm_prepared, mng.EmployeeName as nm_manager
		');
        $this->db->join('at_salesinvoice', 'at_salesinvoice.SInvNumber = at_salesreturn.SInvNumber', 'inner');
		//$this->db->join('am_employee', 'am_employee.EmployeeCode = at_salesreturn.SalesmanCode', 'inner');
		$this->db->join('am_customer', 'am_customer.CustomerCode = at_salesreturn.CustomerCode', 'inner');
		$this->db->join('am_branch', 'am_branch.BranchCode = at_salesreturn.BranchCode', 'inner');
		$this->db->join('am_employee as prepared', 'prepared.EmployeeCode = at_salesreturn.CreatedBy', 'LEFT');
		$this->db->join('am_employee as mng', 'mng.EmployeeCode = at_salesreturn.AppLevel1Code', 'LEFT');
		$this->db->where('at_salesreturn.SRetNumber', $id);
		$query = $this->db->get($this->table);
		$this->db->_protect_identifiers = TRUE;
        return $query->row();
    }

    function get_detail_item_print($SRetNumber){
	    $this->db->_protect_identifiers = FALSE;
	    $this->db->select('
			at_sretdetail.ItemDesc, at_sretdetail.ItemCategoryID, at_sretdetail.SRetDate, at_sretdetail.ItemCategoryCode, at_sretdetail.ItemTotalAmount, at_sretdetail.AmountTax as ItemTax, at_sretdetail.ItemPriceCogs, at_sretdetail.ItemAmountCogs, 
			at_sretdetail.SRetDetailID, at_sretdetail.SRetNumber, at_sretdetail.ItemCode, at_sretdetail.ItemQty, at_sretdetail.ItemUnit, at_sretdetail.InvoiceQty as max_item_finis, at_sretdetail.ItemQtyRet,at_sinvdetail.ItemType as ItemStatus,
			at_sretdetail.ItemPrice, at_sretdetail.ItemAmount, at_sretdetail.SalesmanCode, (at_sinvdetail.ItemQty - at_sinvdetail.QtyReturn) as max_item, at_sinvdetail.QtyBookReturn as ItemQtyBookRet, am_employee.EmployeeName as SalesmanName, at_sretdetail.SInvDetailID
		');
        
		$this->db->where('at_sretdetail.SRetNumber', $SRetNumber);
		$this->db->join('am_employee', 'am_employee.EmployeeCode = at_sretdetail.SalesmanCode', 'inner');
		$this->db->join('at_sinvdetail', 'at_sinvdetail.SInvDetailID = at_sretdetail.SInvDetailID', 'inner');
		
		$query = $this->db->get('at_sretdetail');
		$this->db->_protect_identifiers = TRUE;
        return $query->result_array();
    }
	
	function get_detail_item($SRetNumber){
	    $this->db->_protect_identifiers = FALSE;
	    $this->db->select('
			at_sretdetail.ItemDesc, at_sretdetail.ItemCategoryID, at_sretdetail.SRetDate, at_sretdetail.ItemCategoryCode, at_sretdetail.ItemTotalAmount, at_sretdetail.AmountTax as ItemTax, at_sretdetail.ItemPriceCogs, at_sretdetail.ItemAmountCogs,at_sretdetail.ItemTotalAmount as Total_Amount_Hide, at_sretdetail.ItemAmount as Item_Amount_Hide, 
			at_sretdetail.SRetDetailID, at_sretdetail.SRetNumber, at_sretdetail.ItemCode, at_sretdetail.ItemQty, at_sretdetail.ItemUnit, at_sretdetail.InvoiceQty as max_item_finis, at_sretdetail.ItemQtyRet,at_sretdetail.ItemDiscPcnt,at_sretdetail.ItemType,at_sretdetail.ItemType as ItemStatus,
			at_sretdetail.ItemPrice, at_sretdetail.ItemAmount, at_sretdetail.SalesmanCode, at_sretdetail.InvoiceQty as max_item, at_sinvdetail.QtyBookReturn as ItemQtyBookRet, am_employee.EmployeeName as SalesmanName, at_sretdetail.SInvDetailID, at_sinvdetail.ItemQty as max_item_copy, at_sretdetail.ItemDiscPcnt
		');
        
		$this->db->where('at_sretdetail.SRetNumber', $SRetNumber);
		$this->db->join('am_employee', 'am_employee.EmployeeCode = at_sretdetail.SalesmanCode', 'inner');
		$this->db->join('at_sinvdetail', 'at_sinvdetail.SInvDetailID = at_sretdetail.SInvDetailID', 'inner');
		
		$query = $this->db->get('at_sretdetail');
		$this->db->_protect_identifiers = TRUE;
        return $query->result();
    }
	
	function get_detail_si($id){
	    $this->db->_protect_identifiers = FALSE;
	    $this->db->select('
			at_sinvdetail.QtyReturn, at_sinvdetail.ItemQty, at_sinvdetail.QtyBookReturn
		');
        
		$this->db->where('at_sinvdetail.SInvDetailID', $id);
		$query = $this->db->get('at_sinvdetail');
		$this->db->_protect_identifiers = TRUE;
        return $query->row();
    }
	
	function insert_transaction_all($trans_data){
		$this->db->trans_start();
		$this->insert($trans_data['insert_group']['data']);
		
		for($x=0;$x<count($trans_data['insert_detail']['data']);$x++){
			$this->insert_detail($trans_data['insert_detail']['data'][$x]);
		}
		
		$this->m_sales_invoice->update($trans_data['update_invoice_group']['data'],$trans_data['update_invoice_group']['SInvNumber']);
		
		/*
			Insert Journal
		*/
		if(!empty($trans_data['insert_journal']['data'])){
			for($x=0;$x<count($trans_data['insert_journal']['data']);$x++){
				$this->insert_journal($trans_data['insert_journal']['data'][$x]);
			}
		}
		
		if(!empty($trans_data['update_journal']['data'])){
			for($x=0;$x<count($trans_data['update_journal']['data']);$x++){
				$this->update_journal($trans_data['update_journal']['data'][$x],$trans_data['update_journal']['SRetJournalID'][$x]);
			}
		}
		
		if(!empty($trans_data['insert_journal_noloop']['data'])){
			$this->insert_journal($trans_data['insert_journal_noloop']['data']);
		}
		/*================ENd===============*/
		$this->db->trans_complete();
		if ($this->db->trans_status() === FALSE){
			return 0;
		}
		else{
			return 1;
		}
	}
	
	function update_transaction_all($trans_data){
		$this->db->trans_start();
		$this->update($trans_data['update_group']['data'],$trans_data['update_group']['SRetNumber']);
		
		for($x=0;$x<count($trans_data['update_detail']['data']);$x++){
			$this->update_detail($trans_data['update_detail']['data'][$x],$trans_data['update_detail']['SRetDetailID'][$x]);
		}
		$this->delete_journal($trans_data['delete_journal']['SRetNumber']);
		/*
			Delete grid
		*/
		if($trans_data['delete_detail']['total']>0){
			for($x=0;$x<count($trans_data['delete_detail']['SRetDetailID']);$x++){
				$this->delete_detail_by_sretdetail_id($trans_data['delete_detail']['SRetDetailID'][$x]);
			}
			
			for($x=0;$x<count($trans_data['update_detail_invoice']['data']);$x++){
				$this->m_sales_invoice->update_detail($trans_data['update_detail_invoice']['data'][$x],$trans_data['update_detail_invoice']['SInvDetailID'][$x]);
			}
		}
		/*===========================END================================*/
		
		/*
			Insert Journal
		*/
		if(!empty($trans_data['insert_journal']['data'])){
			for($x=0;$x<count($trans_data['insert_journal']['data']);$x++){
				$this->insert_journal($trans_data['insert_journal']['data'][$x]);
			}
		}
		
		
		if(!empty($trans_data['update_journal']['data'])){
			for($x=0;$x<count($trans_data['update_journal']['data']);$x++){
				$this->update_journal($trans_data['update_journal']['data'][$x],$trans_data['update_journal']['SRetJournalID'][$x]);
			}
		}
		
		if(!empty($trans_data['insert_journal_noloop']['data'])){
			$this->insert_journal($trans_data['insert_journal_noloop']['data']);
		}
		/*================ENd===============*/
		
		$this->db->trans_complete();
		if ($this->db->trans_status() === FALSE){
			return 0;
		}
		else{
			return 1;
		}
	}
	
	function reverse_trasaction($transaction_data) {
        $this->db->trans_start();
        if (!empty($transaction_data['update_inventory']['data'])) {
            for ($x = 0; $x < count($transaction_data['update_inventory']['data']); $x++) {
                $this->m_inventories->update($transaction_data['update_inventory']['data'][$x], $transaction_data['update_inventory']['ItemCode'][$x]);
            }
        }
		
		for ($x = 0; $x < count($transaction_data['update_qty_invoice']['data']); $x++) {
			$this->m_sales_invoice->update_detail_for_return($transaction_data['update_qty_invoice']['data'][$x], $transaction_data['update_qty_invoice']['SInvDetailID'][$x]);
		}
		
		$this->delete_sordetaildp($transaction_data['delete_sordetaildp']['SOrdNumber']);
		$this->update($transaction_data['update_sret']['data'], $transaction_data['update_sret']['SRetNumber']);
		$this->m_sales_invoice->update($transaction_data['update_invoice']['data'], $transaction_data['update_invoice']['SInvNumber']);
			
        $this->db->trans_complete();
        if ($this->db->trans_status() === FALSE) {
            return 0;
        } else {
            return 1;
        }
    }
	
	function insert($data) {
		$this->db->insert($this->table, $data);	
	}
	
	function update($data, $id) {
		$this->db->update($this->table, $data, array('SRetNumber' => $id));
	}
	
	function update_detail($data, $id) {
		$this->db->update($this->detail, $data, array('SRetDetailID' => $id));
	}
	
	function delete_journal($id) {
        $this->db->delete($this->journal, array('SRetNumber' => $id));
    }
	
	function delete_detail_by_sretdetail_id($SRetDetailID) {
        $this->db->delete($this->detail, array('SRetDetailID' => $SRetDetailID));
    }
	
	function delete_sordetaildp($SOrdNumber) {
        $this->db->delete('at_sorddetaildp', array('SOrdNumber' => $SOrdNumber));
    }
	
	function insert_detail($data_detail) {		
		$this->db->insert($this->detail, $data_detail);
	}
	
	function insert_journal($data_journal) {		
		$this->db->insert($this->journal, $data_journal);
	}
	
	function update_journal($data, $id) {
		$this->db->update($this->journal, $data, array('SRetJournalID' => $id));
	}
	
	/*======================penomeran transaksi new=======================================================*/
	function check_code_exist($new_sret_number) {
        $query = $this->db->get_where($this->table, array('SRetNumber' => $new_sret_number), 1, 0);
		
        if ($query->num_rows() > 0) {
            return TRUE;
        }
        else {
            return FALSE;
        }	
    }
	
	function create_sret_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');
        }
		
        $sret_number	= $branch ."/". $month . $year ."SU/";
		
        $this->db->_protect_identifiers = false;
        $this->db->select('(CASE 
                              WHEN MAX(CONVERT(SUBSTR(SRetNumber, -3),signed)) IS NULL then 1
                              ELSE MAX(CONVERT(SUBSTR(SRetNumber, -3),signed)) + 1 END) as New_Number');
        $this->db->like('SRetNumber', $sret_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_sret_number = $sret_number . $number;

        while($this->check_code_exist($new_sret_number)){
            $num++;
            $long = strlen($num);
    
            if($long == 1){
                $number = '00' . $num;
            }
            elseif($long == 2){
                $number = '0' . $num;
            }
            else{
                $number = $num;
            }
            
            $new_sret_number = $sret_number . $number;		
        }
        
        return  $new_sret_number;
    }
	/*==============================================================end=================================*/
	
	function set_trans_status($id, $status) {
		$this->db->set('TransStatus', $status);
		$this->db->where('SRetNumber', $id);
		$this->db->update($this->table);
	}
	
	function get_transstatus($id) {
        $this->db->select('TransStatus');
		$this->db->from($this->table);
		$this->db->where('SRetNumber', $id); 
		$query = $this->db->get();    
        
		if ($query->num_rows() > 0) {
			foreach ($query->result() as $row) {
				$TransStatus = $row->TransStatus;
			}    

			return $TransStatus;
		}
		else {
			return FALSE;
		}	
    }
	
	function get_dept_name($id) {
        $this->db->select('DepartmentName');
		$this->db->from('am_department');
		$this->db->where('DepartmentCode', $id); 
		$query = $this->db->get();    
        
		if ($query->num_rows() > 0) {
			foreach ($query->result() as $row) {
				$DepartmentName = $row->DepartmentName;
			}    

			return $DepartmentName;
		}
		else {
			return FALSE;
		}	
    }
	
	function get_at_sales_inv_qty($id) {
        $this->db->select('ItemQty, SInvDetailID, QtyReturn, QtyBookReturn');
        $this->db->from('at_sinvdetail');
       $this->db->where('SInvDetailID', $id); 
        $query = $this->db->get();    
        
        if ($query->num_rows() > 0) {
            return $query->row();
        }
        else {
            return false;
        }	
    }
	
	function get_detail_invoice($Sord_number){
        $this->db->_protect_identifiers = false;
        $this->db->select("srd.SInvNumber as Invoice_Number, sr.SRecNumber as SRecNumber");
        $this->db->from('at_salesreceipt as sr');
        $this->db->join('at_srecdetail as srd', 'srd.SRecNumber = sr.SRecNumber', 'LEFT');
        $this->db->where('srd.SOrdNumber', $Sord_number);
        $this->db->group_by('Invoice_Number');
        $this->db->order_by('SInvNumber', 'ASC');
        $query = $this->db->get();
        $this->db->_protect_identifiers = false;
        
        if ($query->num_rows() > 0) {
            return $query->row();
        }
        else {
            return false;
        }	
    }
		
	function get_journal_by_number($Number){
	    $this->db->_protect_identifiers = FALSE;
	    $this->db->select("at_sretjournal.*,am_accountgl.AccountNumber,am_accountgl.AccountName");
		$this->db->join("am_accountgl","am_accountgl.AccountNumber=at_sretjournal.SRetAccountNumber","INNER");
        $this->db->order_by('at_sretjournal.ReturnStatus','DESC');
		$query = $this->db->get_where($this->journal, array('SRetNumber' => $Number));
		$this->db->_protect_identifiers = TRUE;
        return $query->result();
    }
	
	function get_journal_return_empty($akun, $id, $invoice_number=''){
		$this->db->_protect_identifiers = FALSE;
	    $this->db->select("SRetAccountNumber, SRetSaldoDebet, SRetSaldoCredit, AmountCurrency, SRetJournalID");
		$this->db->from($this->journal);
		$this->db->where('SRetAccountNumber', $akun); 
		$this->db->where('SRetNumber', $id); 
		if($invoice_number != ''){
			$this->db->where('SInvNumber', $invoice_number); 
		}
		
		$query = $this->db->get();
		$this->db->_protect_identifiers = TRUE;
		return $query->row();
    }
	
	function get_sales_return($SInvNumber) {
        $this->db->select('SInvNumber');
        $this->db->from('at_salesreturn');
       	$this->db->where('SInvNumber', $SInvNumber); 
		$this->db->where_in('TransStatus', array(3,8,9)); 
		
        $query = $this->db->get();    
        
        if ($query->num_rows() > 0) {
            return $query->row();
        }
        else {
            return false;
        }	
    }
}

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