<?php
class Invoice extends AppModel {
	var $name = 'Invoice';
	var $displayField = 'id';
	
	
	
	//The Associations below have been created with all possible keys, those that are not needed can be removed

	var $belongsTo = array(
		'Customer' => array(
			'className' => 'Customer',
			'foreignKey' => 'customer_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		),
		'Status' => array(
			'className' => 'Status',
			'foreignKey' => 'status_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		),
		'Team' => array(
			'className' => 'Team',
			'foreignKey' => 'team_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		),
		'Requester' => array(
			'className' => 'Requester',
			'foreignKey' => 'requester_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		)		
	);
	
	var $hasMany = array(
		'Evaluation' => array(
			'className' => 'Evaluation',
			'foreignKey' => 'invoice_id',
			'dependent' => false,
			'conditions' => '',
			'fields' => '',
			'order' => '',
			'limit' => '',
			'offset' => '',
			'exclusive' => '',
			'finderQuery' => '',
			'counterQuery' => ''
		),
		'InvoiceItem' => array(
			'className' => 'InvoiceItem',
			'foreignKey' => 'invoice_id',
			'dependent' => false,
			'conditions' => '',
			'fields' => '',
			'order' => '',
			'limit' => '',
			'offset' => '',
			'exclusive' => '',
			'finderQuery' => '',
			'counterQuery' => ''
		)		
	);
	
	###################################################
	### returns the last Invoice Number
	###################################################
	function lastInvoice()
	{
		return $this->find('first', array('fields' => 'Invoice.invoice_code','order' => 'Invoice.created DESC'));
	}		

	###########################################################################
	# Validate if there is already a Invoice Score
	###########################################################################
	function countInvoice($month_invoice, $year_invoice, $customer_id, $team_id, $requester_id)
	{
		if (empty($requester_id)) {
			return $this->find('count', array('conditions' => array('Invoice.customer_id' => $customer_id, 'Invoice.team_id' => $team_id,
											'Invoice.invoiced_year' => $year_invoice,
											'Invoice.invoiced_month' => $month_invoice)));		
		} else {
			return $this->find('count', array('conditions' => array('Invoice.customer_id' => $customer_id, 'Invoice.team_id' => $team_id,
											'Invoice.requester_id' => $requester_id,
											'Invoice.invoiced_year' => $year_invoice,
											'Invoice.invoiced_month' => $month_invoice)));		
		}
	}
	 	 
	###################################################
	# returns the Invoice information
	###################################################
	function infoCustomerInvoice($inv_id)
	{
		return $this->find('first', array(
				'link' => array(
					'Customer' => array(
							'City'  => array(
									'conditions' => 'Customer.city_id  = City.id'),
							'Province' => array(
									'conditions' => 'Customer.province_id  = Province.id')
								),
					'Team',			
					'Status',
					'InvoiceItem'
				),
				'fields' => array('Invoice.id','Invoice.invoice_code','Invoice.status_id', 'Invoice.created', 'Invoice.modified', 'Invoice.invoiced_month',
								'Invoice.invoiced_year', 'Invoice.invoice_type', 
								'Invoice.tax_fed_rate', 'Invoice.tax_fed_desc', 'Invoice.tax_prov_rate', 'Invoice.tax_prov_desc',
								'Customer.id','Customer.name','Customer.contact_fname','Customer.contact_lname', 
								'Status.name_eng', 'Team.name',
								 'SUM(InvoiceItem.amount) AS sumNoTax'
								),			
				'conditions' =>  array('Invoice.id' => $inv_id),
				// 'group' => array('Invoice.id')
			));			
	}
		 
	###########################################################################
	# Prepare - select the data that is going to be Invoiced
	###########################################################################		 
	function getInvoiceDataToSave($customer_id, $team_id, $requester_id, $type, $month_test, $year_test)
	{
		$testsFees = array();
		
		# By Customer
		if ($type == 1) {
			$orderTestToInvoices = $this->Evaluation->Order->infoEvalByCust($customer_id, $month_test, $year_test);
		} elseif ($type == 2) {
		# By Company / Team
			$orderTestToInvoices = $this->Evaluation->Order->infoEvalByCustTeam($team_id, $month_test, $year_test);
		} elseif ($type == 3) {
		# By Company / Team / Requester
			$orderTestToInvoices = $this->Evaluation->Order->infoEvalByCustTeamReq($requester_id, $month_test, $year_test);
		}		
		//echo pr($orderTestToInvoices);
		# Number of Orders
		$countOrders = count($orderTestToInvoices);
		//echo ' countOrders '.$countOrders;
		//echo pr($orderTestToInvoices);
				
		foreach ($orderTestToInvoices as $orderTest) 
		{
			# Test/Evaluations by Order
			$countTests = count($orderTest['Evaluation']);
			//echo 'countorderTest[Evaluation] '.$countTests;
			//echo pr($orderTest);
			//echo '$team_id :'.$team_id;
			
			for ($i=0; $i < $countTests; $i++)
			{
				if (empty($team_id))
				{				
					$commun = $orderTest['Evaluation'][$i]['communication_id'];
					$service = $orderTest['Evaluation'][$i]['service_id'];
					$status = $orderTest['Evaluation'][$i]['status_id'];
					
					if ($orderTest['Evaluation'][$i]['test_serie'] == 1) 
					{
						$ttest = 0;
					}
					else
					{
						$ttest = 1;
					}
					
					$getFeeValue = $this->Evaluation->Service->Fee->getFeeValue($ttest, $commun, $service, $status);
					//echo pr($getFeeValue);
					$testsFees = array_merge($testsFees, array(
												array('test_id' => $orderTest['Evaluation'][$i]['id'], 												
													'fee_value' => $getFeeValue['Fee']['fee_value'],
													'status_id' => $orderTest['Evaluation'][$i]['status_id']
													)
														)
											);				
				}
				else
				{
					if($type == 2 || $type == 3) {
						$countReq = 0;
						$countTestEv = 0;					
							
						$countReq =  count($orderTest['Evaluation'][$i]['Requester']);
						//echo '$countReq '.$countReq;
						if ($countReq != 0)
						{
							//echo pr($orderTestReq);
							$commun = $orderTest['Evaluation'][$i]['communication_id'];
							$service = $orderTest['Evaluation'][$i]['service_id'];
							$status = $orderTest['Evaluation'][$i]['status_id'];
							
							if ($orderTest['Evaluation'][$i]['test_serie'] == 1) 
							{
								$ttest = 0;
							}
							else
							{
								$ttest = 1;
							}
							
							$getFeeValue = $this->Evaluation->Service->Fee->getFeeValue($ttest, $commun, $service, $status);
							//echo pr($getFeeValue);
							$testsFees = array_merge($testsFees, array(
														array('test_id' => $orderTest['Evaluation'][$i]['id'], 												
															'fee_value' => $getFeeValue['Fee']['fee_value'],
															'status_id' => $orderTest['Evaluation'][$i]['status_id']
															)
																)
													);								
						}					
					} //elseif($type == 3) {
					
					//}
				}
			}										
		}
		return $testsFees;	
	}

	###################################################################################
	# Returns the Customer address by cutomer_id provided
	# Called from View Invoice Report
	###################################################################################
	/*
	function infoCustomerInvoice($invoice_id)
	{
		return $this->find('first', array(
				'link' => array(
					'Customer' => array(
							'City'  => array(
									'conditions' => 'Customer.city_id  = City.id'),
							'Province' => array(
									'conditions' => 'Customer.province_id  = Province.id')
								)					
						),
				'fields' => array(
							'Customer.id','Customer.abbrv','Customer.name','Customer.address','Customer.code_postal',
							'Province.name','City.name'
							),			
				'conditions' =>  array('Invoice.id' => $invoice_id)
			));			
	}*/	

	################################################################################
	#                                  Before Save                                 #
	################################################################################		
	function beforeSave($opt=[]) 
	{
	### set todays date to 'status_date'
	$today = date('Y-m-d', time());		
	//echo $today;
	### When an Insert Table is made
		if(empty($this->id))		 
		{
	
		}
		else
	### When an Update is made
		{
	
		}			  
//		$this->data['Order']['status_date'] = $today;		
//		echo pr($this->data);
		return true;
	}	

	################################################################################
	#                                  After Save                                  #
	################################################################################		
	function afterSave($created) 
	{
	//$today = date('Y-m-d');	
	### When an Insert is made
		if($created)
		{
			## Update Evaluations with the Invoice id
			//$updateValTest = array_values($this->data['Evaluation']);		
			$result1 = $this->Evaluation->updateAll(
						array(
								'Evaluation.invoice_id' => $this->id
							),
						array('Evaluation.id' => $this->data['Eval']
							)
						);
			
		    if (!$result1)
			{
				return false;
			}
		}
		else
		{
	
			
		}
		return true;		
	}	
}
?>