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

class invoiceClone extends CI_Model{
	
	public function invoiceList($dateFrom,$dateTo){
		$query = $this->db->select('a.*,a.updateAble as Yes,
								a.totalamount * exchangeRate as totalbaseamount,
								a.totalTaxAmount * exchangeRate as totalbasetaxamount,
								b.fldcurr_code,
							')
						->from('comp_sales_invoice a')
						->join('_ref_currency b', 'b.fldid = a.currencyID', 'left outer')
						->where(array('a.companyID'=> element('compID',	$this->session->userdata('logged_in')),
									'a.salesinvoiceDate >='=> $dateFrom,
									'a.salesinvoiceDate <='=> $dateTo,
								))
						->order_by('a.salesinvoiceDate', 'desc')
						->get();
		
		if($query->num_rows() >= 1){
			return $query->result();
		}else{
			return false;
		}
	}
	//Clone data of certain invoice
	public function cloneIt($id){
		//Cloning invoice row
		$query = $this->db->query('select * from comp_sales_invoice where ID='.$id);
		$data = $query->result();
		$data = json_decode(json_encode($data[0]), true);
		unset($data['ID']); $data['updateAble'] = 1;
		$this->db->insert('comp_sales_invoice',$data);
		$invID = $this->db->insert_id();	
		
		//Cloning detail row
		if($invID){
			$query = $this->db->query('select * from comp_sales_invoice_detail where invoiceID='.$id);
			$data = $query->result();
			$data = json_decode(json_encode($data), true);
			if(!empty($data)){
				foreach($data as &$v){unset($v['ID']); $v['invoiceID'] = $invID;}
				$this->db->insert_batch('comp_sales_invoice_detail',$data);
			}
		}
		
		//Cloning charge row
		if($invID){
			$query = $this->db->query('select * from comp_sales_invoice_charges where invoiceID='.$id);
			$data = $query->result();
			$data = json_decode(json_encode($data), true);
			if(!empty($data)){
				foreach($data as &$v){unset($v['ID']); $v['invoiceID'] = $invID;}
				$this->db->insert_batch('comp_sales_invoice_charges',$data);
			}
		}
	}
	//gather customer currencty and exchage rate
	public function getCustomerInfo($id){
		$query = $this->db->select('cur.fldid,cur.fldcurr_code')
						->from('customer c')
						->join('_ref_currency cur','cur.fldid=c.currencyID','left')
						->where(array('c.ID'=>$id))
						->get();
		if($query->num_rows() >= 1){
			return json_encode($query->result()); 
		}
	}
	
	//Update invoice information
	public function updateInvoice($data){
		$this->db->where('ID',$data["ID"])->update('comp_sales_invoice',$data);
	}
	
}
