<?php
class OrdersController extends AppController {

	var $name = 'Orders';
	var $uses = array('Order');
	var $helpers = array('Html', 'Form', 'Time', 'Text', 'Number', 'Js' => array('Jquery'));
	var $paginate = array('limit' => 10, 'order' => array('Order.order_code DESC'));
    var $components = array('RequestHandler','Email');
	
	
	function beforeFilter() {
		$this->customer_id = $this->Auth->user('customer_id');
		$this->group_id = $this->Auth->user('group_id');	
		$this->requester_id = $this->Auth->user('requester_id');
		$this->team_id = $this->Auth->user('team_id');
		parent::beforeFilter();
	}
		
	
	function index() {
		$this->layout = 'main_index';
		$this->redirectToNamed();		
		$conditions = array();
		
		$params = $this->params['named'];

		if (!empty($params['status_id'])) {
		  $conditions['Order.status_id ='] = $params['status_id'];
		}
		if (!empty($params['order_code'])) {
		  $conditions['Order.order_code ='] = $params['order_code'];
		}
		if (!empty($params['employee_first_name'])) {
		  $conditions['Employee.first_name LIKE'] = '%'.$params['employee_first_name'].'%';
		}	
		if (!empty($params['customer_internalcode'])) {
		  $conditions['Employee.customer_internalcode LIKE'] = $params['customer_internalcode'];
		}
		if (!empty($params['employee_last_name'])) {
		  $conditions['Employee.last_name LIKE'] = '%'.$params['employee_last_name'].'%';
		}	
		if (!empty($params['day_f']) && !empty($params['month_f']) && !empty($params['year_f'])) {
		  $conditions['Order.status_date >='] = $params['year_f'].'-'.$params['month_f'].'-'.$params['day_f'];
		}
		if (!empty($params['day_t']) && !empty($params['month_t']) && !empty($params['year_t'])) {
		  $conditions['Order.status_date <='] = $params['year_t'].'-'.$params['month_t'].'-'.$params['day_t'];
		}		
		$urlArgs = array('url' => $params);

		if (empty($conditions)) { $conditions['Order.status_id ='] = 0;	}	
		# Superv - Case manager
		if ($this->group_id != 1)	{ $conditions['Order.customer_id ='] = $this->customer_id; }	

		// $conditions['Evaluation.last_test ='] = 1;	
		
		$this->paginate = array(
						'fields' => array('id','order_code','created','status_id'),			
						'conditions' => $conditions,
						'link' => array(
							'Evaluation' => array(	
								'Service' => array(
									'fields' => array('Service.id', 'Service.name')
													),
								'Requester' => array(
									'Team' => array(
										'fields' => array('Team.id', 'Team.name'),
										'conditions' => array('Team.id' => 'Requester.team_id')
													),
									'fields' => array('Requester.id', 'Requester.name')
											)
										),
							'Employee' => array(
								'fields' => array('Employee.id', 'Employee.name')),
							'StatusOrder' => array(
								'fields' => array('StatusOrder.id', 'StatusOrder.name_eng', 'StatusOrder.name_fre'))
							),
						'order' => 'Order.id DESC'
					);
		# Get the current language for status
		$currentLang = Configure::read('Config.language');
		$statuses = $this->Order->StatusOrder->forsearchListStatus(1,'name_'.$currentLang,'StatusOrder');		
		
		$orders = $this->paginate('Order');
		$this->set(compact('orders', 'statuses', 'urlArgs'));
	}	
	
	function view($id = null) {
		$this->layout = 'main_view';
		$this->idEmptyRedirect($id, 'index');

		# Get the Order view information - and all the Evaluation-Tests
		# Order info - header
		$infoOrder = $this->Order->infoOrder($id);
		# Evaluation info - details
		$infoOrdereval = $this->Order->Evaluation->infoOrdereval($id);
		
		$this->set(compact('infoOrdereval','infoOrder'));
	}	
	
	function cancel() {		
		$this->redirect('/evaluations'); 
	}		
	
	function add() {
		# First time the page is loaded - right after an Employee has been selected
		if (isset($this->params['named']['emp_id']) && empty($this->data)) {
			$idEmp = $this->params['named']['emp_id'];
		}		
		
		if (!empty($this->data)) {		
			$this->Order->create();			
			$this->Order->begin();  // Start of transaction 
			if ($this->Order->save($this->data)) {
				# attach the recent Order ID 
				$this->__attachOrderIdToEvaluation($this->Order->id); 			
					# save Evaluation	
					if ($this->Order->Evaluation->save($this->data['Evaluation'])) {					
						$this->Order->commit(); // Persist the data 
						if ($this->data['Evaluation']['communication_id'] == 1) {
							$this->__sendOrderQuest($this->data['Employee']['name'], $this->data['Customer']['name'], $this->data['Order']['employee_id'], $this->data['Employee']['email'], $this->data['Employee']['langue']);
							
							//$this->__sendOrderQuest($this->data['Employee']['name'], $this->data['Customer']['name'], $this->data['Order']['employee_id'], 'patient.testmetrix@gmail.com', $this->data['Employee']['langue']);
						}					
						$this->flashSuccess(__('La orden fué creada.', true), '/evaluations/index/order_code:'.$this->data['Order']['order_code']);					
						exit;
					} else {				
						$this->Order->rollback();
						$this->flashWarning(__('La orden no fué creada. Intente de nuevo.', true));
					}			
			} else {
				$this->Order->rollback();
				$this->flashWarning(__('La orden no fué creada. Intente de nuevo.', true));
			}			
			
		} else {
			### set up default Item ###			
			# Get the Employee-Customer information
			$infoEmp = $this->Order->Employee->infoEmp($idEmp);
		
			$this->data['Employee']['date_birth'] = $infoEmp['Employee']['date_birth'];
			$this->data['Employee']['gender'] = $infoEmp['Employee']['gender'];
			$this->data['Employee']['langue'] = $infoEmp['Employee']['langue'];
			$this->data['Employee']['name'] = $infoEmp['Employee']['first_name'].' '.$infoEmp['Employee']['last_name'];

			if($infoEmp['Employee']['address'] == '') { 
				$this->data['Employee']['full_address'] = __('Dirección no incluída.', true);
				$this->data['City']['name'] = __('Ciudad no incluída', true);
				$this->data['Province']['name'] = __('Estado no incluído', true);
			} else {
				$this->data['Employee']['full_address'] = $infoEmp['Employee']['address'].' '.$infoEmp['Employee']['code_postal'];
				$this->data['City']['name'] = $infoEmp['City']['name'];
				$this->data['Province']['name'] = $infoEmp['Province']['name'];
			}
			
			if($infoEmp['Employee']['email'] == "") { 
				$this->data['Employee']['nameemail'] = __('Email no incluído', true);
			} else {
				$this->data['Employee']['nameemail'] = $infoEmp['Employee']['email'];		
			}
			$this->data['Employee']['email'] = $infoEmp['Employee']['email'];
									
			##### get and set the last Order-Code from Orders table - 20000
			$lastOrder = $this->Order->lastOrder();
			if(empty($lastOrder[0]['order_code'])) { 
				# 1st Order 20000
				$this->data['Order']['order_code'] = 20000;
			} else {
				$this->data['Order']['order_code'] = $lastOrder[0]['order_code'] + 1;
			}
			
			# New Order and New-First Evaluation-Test
			$this->data['Evaluation']['last_id'] = 0;		//initial test, not older test
			
			###ORIGINAL LINE AS FOLLOWS: $tokenhash = Security::hash($this->data['Employee']['name'].'1', null, true);
			###MODIFIED ON FEBRUARY 6, 2017 WHERE THE NEW ORDERS CREATED FOR FOLLOW UP DID NOT CREATE A NEW TOKENHASH AND THE MESSAGE
			###"The Test Id was completed already or it is not longer valid"###REMOVE THE "1" FROM EXPRESSION###
			
			###Edited the next line on August 20-2017 to prevent tokenhash duplication on new orders after 3rrd reminder cancellation###
			$tokenhash = Security::hash($this->data['Employee']['name'].$this->data['Order']['order_code'], null, true);
			$this->data['Evaluation']['tokenhash'] = $tokenhash;	
			
			$this->data['Order']['customer_id'] = $infoEmp['Customer']['id'];
			$this->data['Order']['employee_id'] = $idEmp;
			$this->data['Order']['createdby'] = $this->Session->read('Auth.User.username');
			$this->data['Evaluation']['createdby'] = $this->Session->read('Auth.User.username');			
		}		
		
		# When an Employee has been selected from employees/index, the listbox will be updated with the Employee's customer_id 
		if (isset($this->data['Order']['customer_id'])) {	
			$customers = $this->Order->Customer->find('list', array('conditions' => array('Customer.id' => $this->data['Order']['customer_id'], 'Customer.active' => 1)));
			$this->data['Customer']['name'] = $customers[$this->data['Order']['customer_id']];
			$teams = $this->Order->Customer->Team->teamsCustomer($this->data['Order']['customer_id']);
			$services = $this->Order->Evaluation->Service->servicesCustomer($this->data['Order']['customer_id'],0);
			$provinces = $this->Order->Employee->Province->find('list', array('fields' => array('id', 'name'),'order' => 'name ASC'));
		}
		
		# When the form is reloaded and a Team has been selected, the listbox will be updated with the Requester's team_id	
		if ($this->group_id == 1) {	
			# Admin
			if (isset($this->data['Order']['team_id'])) {	
				$requesters = $this->Order->Customer->Team->Requester->listCaseMngSupervTeam($this->data['Order']['team_id']);
			} else {
				$requesters = array();
			}
		} else {
			# Superv - Case manager
			$requesters = $this->Order->Customer->Team->Requester->listRequestSupervPlus($this->requester_id);
			$this->data['Evaluation']['requester_id'] = $this->requester_id;
			$this->data['Order']['team_id'] = $this->team_id;
		}		
		
		# Get the current language for status
		$currentLang = Configure::read('Config.language');
		$communications = $this->Order->Evaluation->Communication->find('list', array('fields' => array('id', 'name_'.$currentLang),'order' => 'id ASC'));		
		$this->set(compact('provinces', 'teams', 'requesters', 'customers', 'services', 'communications','lastOrder','infoEmp'));			
	}	

	
	function edit($id = null) {	
		if (!empty($this->data)) {
			$this->Order->begin();  // Start of transaction
			if ($this->Order->save($this->data)) {
				$this->Order->commit();
				$this->flashSuccess(__('La orden fué actualizada.', true), 'index');
				exit;
			} else {
				$this->Order->rollback();
				$this->flashWarning(__('La orden no fué actualizada. Intente de nuevo.', true));
			}
		} else {
			# Get the Order view information
			$infoOrder = $this->Order->infoOrder($id);		
			
			# set up default values for form
			$this->data['Order']['customer_id'] = $infoOrder['Customer']['id'];
			$this->data['Customer']['name'] = $infoOrder['Customer']['name'];
			
			$this->data['Order']['status_id'] = $infoOrder['StatusOrder']['id'];
			
			$this->data['Order']['employee_id'] = $infoOrder['Employee']['id'];
			$this->data['Employee']['name'] = $infoOrder['Employee']['first_name']." ".$infoOrder['Employee']['last_name'];	
			
			$this->data['Order']['id'] = $id;
			$this->data['Order']['order_code'] = $infoOrder['Order']['order_code'];
			$this->data['Order']['modifiedby'] = $this->Session->read('Auth.User.username');

		}
		
		# Get the current language for status
		$currentLang = Configure::read('Config.language');
		
		# Admin
		if ($this->group_id == 1) {										
			$statuses = $this->Order->StatusOrder->listStatusName(1,1,'name_'.$currentLang,'StatusOrder');
		} elseif ($this->group_id == 2 || $this->group_id == 3)  {			
		# Superv - Case manager
			$statuses = $this->Order->StatusOrder->listStatusName(1,2,'name_'.$currentLang,'StatusOrder');
		}		

		if (isset($this->data['Order']['customer_id'])){	
			$employees = $this->Order->Employee->find('list', array('fields' => array('id', 'name'),'order' => 'name ASC', 
													'conditions' => array('Employee.customer_id' => $this->data['Order']['customer_id'])));
		}						
		$this->set(compact('infoOrder', 'statuses','employees'));		
		if (empty($this->data)) {
			$this->data = $this->Order->read(null, $id);
		}
	}	
	
	## Private methods ##
	# Attaches Order.id to $this->data['Evaluation']
	function __attachOrderIdToEvaluation($id) {
	    $this->data['Evaluation']['order_id'] = $id;	 
	}	
	
	function __sendOrderQuest($nameEmp, $nameCust, $idEmp, $emailEmp, $lang_id){
		$finalMsg ='';
		//$emailEmp = 'patient.testmetrix@gmail.com';
		
		$this->loadModel('DocLabel');
		$labelsEmailClaim = $this->DocLabel->labelsEmail(1, 1, $lang_id);
		
		$labelsEmailClaimJGH = $this->DocLabel->labelsEmail(11, 1, $lang_id);	
		
		$labelsEmailClaimAMI = $this->DocLabel->labelsEmail(12, 1, $lang_id);	
		
		
		//ends here######################################################################
		if ($lang_id == 1)   {
		# Ingles
			$field_langue = 'name_eng';
		} elseif ($lang_id == 0)  {
		# French
			$field_langue = 'name_fre';
		}
		
		$this->Email->delivery = 'smtp';
		$this->Email->smtpOptions = array(
/*			'host' => 'mail.emtrixtest.ca.e-testmetrix.ca',
			'username' => 'mytestmail+emtrixtest.ca.e-testmetrix.ca', 
			'password' => '-2013testmtl' */
			'host' => 'mail.e-testmetrix.ca',
			'username' => 'admin.service+e-testmetrix.ca',
			'password' => '20metrix11-'
		);
		
		$this->Email->sendAs = 'both';
		//$this->Email->charset = 'iso-8859-15'; 
		
		$passw = '00c383efdccfff3c654bf5f91b4a12bd5ee2fe56';
		$tokeval = $this->data['Evaluation']['tokenhash'];							
		
		// WPS Initial MESSAGE
			if  ($nameCust == 'WPS Experts Inc.')
			{ 
				$this->Email->subject = $labelsEmailClaimJGH[0]['DocLabel'][$field_langue];
				$finalMsg .= $labelsEmailClaimJGH[1]['DocLabel'][$field_langue].'<br/><br/>';
				$finalMsg .= $labelsEmailClaimJGH[2]['DocLabel'][$field_langue].'<br/><br/>'; 
				$finalMsg .= $labelsEmailClaimJGH[3]['DocLabel'][$field_langue].'<br/><br/>';
				$finalMsg .= $labelsEmailClaimJGH[4]['DocLabel'][$field_langue].'<br/><br/>';
				$finalMsg .= $labelsEmailClaimJGH[5]['DocLabel'][$field_langue].'<br/><br/>';
				$finalMsg .= '<a href ='.'https://e-testmetrix.ca/pages/validate_emailaccess/wtf:'.$tokeval.'/udans:'.$passw.'/f08n:'.$idEmp.'>'.$labelsEmailClaimJGH[6]['DocLabel'][$field_langue].'</a><br/><br/>';
				$finalMsg .= $labelsEmailClaimJGH[7]['DocLabel'][$field_langue].'<br/><br/>';
				$finalMsg .= 'Testmetrix Admin Service<br/><br/><br/>';
				if($lang_id == 1) {
				    $finalMsg .= '<font size="-1"><i>(If the link does not open on your browser, 
                                    please right click the link and choose from the menu the following options according to your web browser: 
                                    Edge "Copy link". Mozilla Firefox: "Copy Link Location". 
                                    Chrome: "Copy link address". Open a new tab or window on your browser, right click on the address bar and press "paste and go"). </i><br/><br/><br/>';
				} else {
				    $finalMsg .= '<font size="-1"><i>(Si su link no se abre, copie y pegue directamente en el navegador.)</i><br/><br/><br/>';
				}		
				//$finalMsg .= '<font size="-2"><i><b>'.$labelsEmailClaimJGH[8]['DocLabel'][$field_langue].'<br/>';
				//$finalMsg .= '<a href ='.'https://e-testmetrix.ca/pages/refuse_emailaccess/ouqstapw:'.$tokeval.'/udans:'.$passw.'/f08n:'.$idEmp.'>'.$labelsEmailClaimJGH[9]['DocLabel'][$field_langue].'</b></i><br/><br/></font>';			
			}		
		// Allan Memorial Institute Initial MESSAGE
			elseif  ($nameCust == 'Dr. Howard Margolese')
			{ 
				$this->Email->subject = $labelsEmailClaimAMI[0]['DocLabel'][$field_langue];
				$finalMsg .= $labelsEmailClaimAMI[1]['DocLabel'][$field_langue].'<br/><br/>';
				$finalMsg .= $labelsEmailClaimAMI[2]['DocLabel'][$field_langue].'<br/><br/>'; 
				$finalMsg .= $labelsEmailClaimAMI[3]['DocLabel'][$field_langue].'<br/><br/>';
				$finalMsg .= $labelsEmailClaimAMI[4]['DocLabel'][$field_langue].'<br/><br/>';
				$finalMsg .= $labelsEmailClaimAMI[5]['DocLabel'][$field_langue].'<br/><br/>';
				$finalMsg .= '<a href ='.'https://e-testmetrix.ca/pages/validate_emailaccess/wtf:'.$tokeval.'/udans:'.$passw.'/f08n:'.$idEmp.'>'.$labelsEmailClaimAMI[6]['DocLabel'][$field_langue].'</a><br/><br/>';
				$finalMsg .= $labelsEmailClaimAMI[7]['DocLabel'][$field_langue].'<br/><br/>';
				$finalMsg .= 'Testmetrix Admin Service<br/><br/><br/>';
				if($lang_id == 1) {
				    $finalMsg .= '<font size="-1"><i>(If the link does not open on your browser, 
                                    please right click the link and choose from the menu the following options according to your web browser: 
                                    Edge "Copy link". Mozilla Firefox: "Copy Link Location". 
                                    Chrome: "Copy link address". Open a new tab or window on your browser, right click on the address bar and press "paste and go"). </i><br/><br/><br/>';
				} else {
				    $finalMsg .= '<font size="-1"><i>(Si su link no se abre, copie y pegue directamente en el navegador.)</i><br/><br/><br/>';
				}		
				//$finalMsg .= '<font size="-2"><i><b>'.$labelsEmailClaimJGH[8]['DocLabel'][$field_langue].'<br/>';
				//$finalMsg .= '<a href ='.'https://e-testmetrix.ca/pages/refuse_emailaccess/ouqstapw:'.$tokeval.'/udans:'.$passw.'/f08n:'.$idEmp.'>'.$labelsEmailClaimJGH[9]['DocLabel'][$field_langue].'</b></i><br/><br/></font>';			
			}					
			
			// TELUS Health initial MESSAGE
			else 
			{ 
				$this->Email->subject = $labelsEmailClaim[0]['DocLabel'][$field_langue];
				$finalMsg .= $labelsEmailClaim[1]['DocLabel'][$field_langue].'<br/><br/>';
				$finalMsg .= $labelsEmailClaim[2]['DocLabel'][$field_langue].' '.$labelsEmailClaim[3]['DocLabel'][$field_langue].'<br/><br/>';
				$finalMsg .= $labelsEmailClaim[4]['DocLabel'][$field_langue].'<br/><br/>'.$labelsEmailClaim[5]['DocLabel'][$field_langue].' '.$labelsEmailClaim[6]['DocLabel'][$field_langue].'<br/><br/>';
				$finalMsg .= $labelsEmailClaim[7]['DocLabel'][$field_langue].'<br/><br/>';
				$finalMsg .= '<a href ='.'https://e-testmetrix.ca/pages/validate_emailaccess/wtf:'.$tokeval.'/udans:'.$passw.'/f08n:'.$idEmp.'>'.$labelsEmailClaim[8]['DocLabel'][$field_langue].'</a><br/><br/>';
				// $finalMsg .= '<font size="-1"><i>If the link does not open on your browser, please right click the link and choose from the menu the following options according to your web browser: Internet Explorer: "Copy shortcut". Edge "Copy link". Mozilla Firefox: "Copy Link Location". Chrome: "Copy link address". Open a new tab or window on your browser, right click on the address bar and press "paste and go".</i><br/><br/><br/>';	
				$finalMsg .= '<font size="3">'.$labelsEmailClaim[9]['DocLabel'][$field_langue].'<br/><br/>';
				$finalMsg .= 'Testmetrix Admin Service<br/><br/><br/>';
				if($lang_id == 1) {
				    $finalMsg .= '<font size="-1"><i>(If the link does not open on your browser, 
                                    please right click the link and choose from the menu the following options according to your web browser: 
                                    Edge "Copy link". Mozilla Firefox: "Copy Link Location". 
                                    Chrome: "Copy link address". Open a new tab or window on your browser, right click on the address bar and press "paste and go"). </i><br/><br/><br/>';
				} else {
				    $finalMsg .= '<font size="-1"><i>(Si su link no se abre, copie y pegue directamente en el navegador.)</i><br/><br/><br/>';
				}		
				//$finalMsg .= '<font size="-2"><i><b>'.$labelsEmailClaim[10]['DocLabel'][$field_langue].'<br/>';
				//$finalMsg .= '<a href ='.'https://e-testmetrix.ca/pages/refuse_emailaccess/ouqstapw:'.$tokeval.'/udans:'.$passw.'/f08n:'.$idEmp.'>'.$labelsEmailClaim[11]['DocLabel'][$field_langue].'</b></i><br/><br/></font>';	
				
				
			}	
							
		//REPLACE STRINGS FOR CUSTOMIZED MESSAGES WITH INSERTED FIELDS
		$finalMsg = str_replace('#', '<b>'.$nameCust.'</b>', $finalMsg);
		$finalMsg = str_replace('?', '<b>'.$nameEmp.'</b>', $finalMsg);

		$finalMsg = wordwrap($finalMsg, 65, "\r\n");

		
		$this->Email->from = 'Testmetrix Admin Service <admin.service@e-testmetrix.ca>';
		$this->Email->template = 'initial_test';
		//$this->set('labelsEmailClaim', $labelsEmailClaim);
		//$this->set(compact('labelsEmailClaim', 'field_langue', 'hreLink', 'finalMsg'));
		$this->set('finalMsg', $finalMsg);
		$this->Email->to = $nameEmp.'<'.$emailEmp.'>';
		###ADDED A BLIND CARBON COPY OF EACH ORDER EMAIL###
		###CREATED FEBRUARY 10, 2017###
		$this->Email->bcc = array('admin.service@e-testmetrix.ca','admin@e-testmetrix.ca');
		//$this->Email->send($finalMsg);
		$this->Email->send();		
	}				

	public function get_requesters_ajax() {
	//   Configure::write('debug', 0);
	  if($this->RequestHandler->isAjax()) {
		$this->set('requesters', $this->Order->Customer->Team->Requester->find('list',
							   array('conditions' =>
										   array('Requester.team_id' => $this->params['url']['idteam']),
									'fields' => array('id', 'name'),
									'group' => null
									 )));
	  }
	}
	
}
?>