<?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_supplier_invoice a')
						->join('_ref_currency b', 'b.fldid = a.currencyID', 'left outer')
						->where(array('a.companyID'=> element('compID',	$this->session->userdata('logged_in')),
									'a.invoiceDate >='=> $dateFrom,
									'a.invoiceDate <='=> $dateTo,
								))
						->order_by('a.invoiceDate', '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_supplier_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_supplier_invoice',$data);
		$invID = $this->db->insert_id();	
		
		//Cloning detail row
		if($invID){
			$query = $this->db->query('select * from comp_supplier_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_supplier_invoice_detail',$data);
			}
		}
		
		//Cloning charge row
		if($invID){
			$query = $this->db->query('select * from comp_supplier_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_supplier_invoice_charges',$data);
			}
		}
	}
	
	//Update invoice information
	public function updateInvoice($data){
		$query = $this->db->where('ID',$data["ID"])->update('comp_supplier_invoice',$data);
		
		if($this->db->affected_rows() >= 1){
			return true;
		}else{
			return false;
		}
	}
	
}
