<?php
class EvaluationsController extends AppController
{

	var $name = 'Evaluations';
	var $helpers = array('Html', 'Form', 'Time', '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');
		$this->Auth->allow('export_cancels_xls');
		parent::beforeFilter();
	}


	function index()
	{
		$this->layout = 'main_index';
		$this->redirectToNamed();
		$conditions = array();

		$params = $this->params['named'];

		if (!empty($params['order_id'])) {
			$conditions['Evaluation.order_id ='] = $params['order_id'];
		}
		if (!empty($params['status_id'])) {
			$conditions['Evaluation.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'] . '%';
		}

		#INSERTION HERE 
		if (!empty($params['team_id'])) {
			$conditions['Team.id ='] = $params['team_id'];
		}
		if (!empty($params['requester_id'])) {
			$conditions['Evaluation.requester_id ='] = $params['requester_id'];
		}
		if (!empty($params['customer_id'])) {
			$conditions['Order.customer_id ='] = $params['customer_id'];
		}
		// if (!empty($params['customer_id'])) { $conditions['Customer_id ='] = $params['customer_id']; }		


		if (!empty($params['day_f']) && !empty($params['month_f']) && !empty($params['year_f'])) {
			$conditions['Evaluation.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['Evaluation.status_date <='] = $params['year_t'] . '-' . $params['month_t'] . '-' . $params['day_t'];
		}
		$urlArgs = array('url' => $params);
		if (empty($conditions)) {
			$conditions['Evaluation.status_id ='] = 0;
		}

		# Superv - Case manager
		if ($this->group_id != 1) {
			$conditions['Order.customer_id ='] = $this->customer_id;
		}
		$this->paginate = array(
			'fields' => array('id', 'test_serie', 'created', 'status_date', 'order_id', 'last_test'),
			'conditions' => $conditions,
			'link' => array(
				'Order' => array(
					'Employee',
					'Customer' => array('fields' => array('Customer.id'))
				),
				'Requester' => array(
					'User' => array('fields' => array('User.id', 'User.username')),
					'Team' => array('fields' => array('Team.id', 'Team.name')),
					'fields' => array('Requester.id', 'Requester.name')
				),
				'Status' => array(
					'fields' => array('Status.id', 'Status.name_eng', 'Status.name_fre')
				)
			),
			'order' => 'Order.id DESC'
		);

		if ($this->group_id == 1) {
			$requesters = $this->Evaluation->Requester->find(
				'list',
				array(
					'conditions' =>  array('Requester.hide' => 0),
					'fields' => array('id', 'name'),
					'order' => 'name ASC'
				)
			);
			$teams = $this->Evaluation->Requester->Team->find(
				'list',
				array(
					'fields' => array('id', 'name'),
					'order' => 'name ASC'
				)
			);
			$customers = $this->Evaluation->Requester->Team->Customer->find(
				'list',
				array(
					'fields' => array('id', 'name'),
					'order' => 'name ASC'
				)
			);

			# Send teams and customers info to the Administrator's profile form exclusively
			$currentLang = Configure::read('Config.language');
			$statuses = $this->Evaluation->Status->forsearchListStatus(2, 'name_' . $currentLang, 'Status');
			$evaluations = $this->paginate('Evaluation');
			$this->set(compact('evaluations', 'statuses', 'requesters', 'teams',  'customers', 'urlArgs'));
		} elseif ($this->group_id == 2) {
			$requesters = $this->Evaluation->Requester->listRequestSupervPlus($this->requester_id);
			if (empty($requesters)) {
				$requesters = $this->Evaluation->Requester->find('list', array(
					'conditions' => array('Requester.id' => $this->requester_id, 'Requester.hide' => 0),
					'fields' => array('id', 'name'),
					'order' => 'name ASC'
				));
			}
		} elseif ($this->group_id == 3) {
			$requesters = $this->Evaluation->Requester->find('list', array(
				'conditions' => array('Requester.id' => $this->requester_id, 'Requester.hide' => 0),
				'fields' => array('id', 'name'),
				'order' => 'name ASC'
			));
		}

		# Get the current language for status
		$currentLang = Configure::read('Config.language');
		$statuses = $this->Evaluation->Status->forsearchListStatus(2, 'name_' . $currentLang, 'Status');
		$evaluations = $this->paginate('Evaluation');
		$this->set(compact('evaluations', 'statuses', 'requesters', 'urlArgs'));
	}


	function view($id = null)
	{
		$this->idEmptyRedirect($id, 'index');
		# Get the Employee-Customer information
		$evaluation = $this->Evaluation->infoEvalorder($id);
		$this->set(compact('evaluation'));
	}


	function cancel()
	{
		if (isset($this->params['named']['ordercode'])) {
			$ordercode = $this->params['named']['ordercode'];
		}
		$this->redirect('/evaluations/index/order_code:' . $ordercode);
	}


	function add()
	{
		# First time the page is loaded - right after an Employee has been selected
		if (isset($this->params['named']['eval_id'])) {
			$idEval = $this->params['named']['eval_id'];
		}
		if (!empty($this->data)) {
			$this->Evaluation->create();
			# There is some Doctor information that need to be saved
			if ($this->Evaluation->save($this->data)) {
				if ($this->data['Evaluation']['communication_id'] == 1) {
					$this->__sendOrderQuest(99, $this->data['Evaluation']['tokenhash'], $this->data['Employee']['name'], $this->data['Customer']['name'], $this->data['Employee']['id'], $this->data['Employee']['email'], $this->data['Employee']['langue']);
					###EDITED HERE FEBRUARY 6 2017. REORGANIZED AND INSERTED MISSING INDEXES ON THE SENDORDERQUEST FUNCTION AFTER
					###IT CONFIRMED THE SENDING OF NEW EVALUATIONS TO CLIENTS BY EMAIL BUT DID NOT SEND IN THE BACKGROUND LANGUAGE VARIABLE WAS OFF INDEX line #573
					###ADDED MISSING TOKENHASH VARIABLE
					/*$this->__sendOrderQuest(99, $this->data['Employee']['name'], $this->data['Customer']['name'], $this->data['Employee']['id'], $this->data['Employee']['email'], $this->data['Employee']['langue']);*/
				}
				$this->flashSuccess(__('El test fué creado.', true), 'index/order_code:' . $this->data['Order']['order_code']);
			} else {
				$this->flashWarning(__('El test no fué creado. Corrija el error.', true));
			}
		} else {
			# Get the Order-Current Evaluation view information
			$infoEval = $this->Evaluation->infoEval($idEval);

			# set up default values for form
			$this->data['Order']['order_code'] = $infoEval['Order']['order_code'];
			$this->data['Employee']['name'] = $infoEval['Employee']['first_name'] . ' ' . $infoEval['Employee']['last_name'];
			$this->data['Customer']['id'] = $infoEval['Customer']['id'];
			$this->data['Customer']['name'] = $infoEval['Customer']['name'];
			$this->data['Employee']['id'] = $infoEval['Employee']['id'];
			$this->data['Employee']['langue'] = $infoEval['Employee']['langue'];

			/* Update the new Service
			---Feb. 2015: update from current service to new service. i.e. : dsp-77 initial(#20) to dsp-77 follow-up (#25)
			-- Go by service ID #-- Needs to be updated every time a pair of complementary services is created*/
			if ($infoEval['Service']['id'] == 1){
				$this->data['Evaluation']['service_id'] = 3;
			}elseif ($infoEval['Service']['id'] == 2){
				$this->data['Evaluation']['service_id'] = 4;
			}elseif ($infoEval['Service']['id'] == 5){
				$this->data['Evaluation']['service_id'] = 7;
			}elseif ($infoEval['Service']['id'] == 6){
				$this->data['Evaluation']['service_id'] = 8;
			}elseif ($infoEval['Service']['id'] == 9){
				$this->data['Evaluation']['service_id'] = 10;
			}elseif ($infoEval['Service']['id'] == 3){
				$this->data['Evaluation']['service_id'] = 3;
			}elseif ($infoEval['Service']['id'] == 4){
				$this->data['Evaluation']['service_id'] = 4;
			}elseif ($infoEval['Service']['id'] == 7){
				$this->data['Evaluation']['service_id'] = 7;
			}elseif ($infoEval['Service']['id'] == 8){
				$this->data['Evaluation']['service_id'] = 8;
			}elseif ($infoEval['Service']['id'] == 10){
				$this->data['Evaluation']['service_id'] = 10;
			}elseif ($infoEval['Service']['id'] == 11){
				$this->data['Evaluation']['service_id'] = 11;
			}elseif ($infoEval['Service']['id'] == 12){
				$this->data['Evaluation']['service_id'] = 12;
				//service #13
			}elseif ($infoEval['Service']['id'] == 13){
				$this->data['Evaluation']['service_id'] = 26;
			}elseif ($infoEval['Service']['id'] == 26){
				$this->data['Evaluation']['service_id'] = 26;
				//service #14
			}elseif ($infoEval['Service']['id'] == 14){
				$this->data['Evaluation']['service_id'] = 27;
			}elseif ($infoEval['Service']['id'] == 27){
				$this->data['Evaluation']['service_id'] = 27;
				//service #15
			}elseif ($infoEval['Service']['id'] == 15){
				$this->data['Evaluation']['service_id'] = 28;
			}elseif ($infoEval['Service']['id'] == 28){
				$this->data['Evaluation']['service_id'] = 28;
				//service #16
			}elseif ($infoEval['Service']['id'] == 16){
				$this->data['Evaluation']['service_id'] = 29;
			}elseif ($infoEval['Service']['id'] == 29){
				$this->data['Evaluation']['service_id'] = 29;
				//service #17
			}elseif ($infoEval['Service']['id'] == 17){
				$this->data['Evaluation']['service_id'] = 30;
			}elseif ($infoEval['Service']['id'] == 30){
				$this->data['Evaluation']['service_id'] = 30;
				//service #18
			}elseif ($infoEval['Service']['id'] == 18){
				$this->data['Evaluation']['service_id'] = 31;
			}elseif ($infoEval['Service']['id'] == 31){
				$this->data['Evaluation']['service_id'] = 31;
                //service #19
			}elseif ($infoEval['Service']['id'] == 19){
				$this->data['Evaluation']['service_id'] = 32;
			}elseif ($infoEval['Service']['id'] == 32){
				$this->data['Evaluation']['service_id'] = 32;
				//service #20
			}elseif ($infoEval['Service']['id'] == 20){
				$this->data['Evaluation']['service_id'] = 25;
			}elseif ($infoEval['Service']['id'] == 25){
				$this->data['Evaluation']['service_id'] = 25;
				//service #21
			}elseif ($infoEval['Service']['id'] == 21){
				$this->data['Evaluation']['service_id'] = 33;
			}elseif ($infoEval['Service']['id'] == 33){
				$this->data['Evaluation']['service_id'] = 33;
				//service #22
			}elseif ($infoEval['Service']['id'] == 22){
				$this->data['Evaluation']['service_id'] = 34;
			}elseif ($infoEval['Service']['id'] == 34){
				$this->data['Evaluation']['service_id'] = 34;
				//service #23
			}elseif ($infoEval['Service']['id'] == 23){
				$this->data['Evaluation']['service_id'] = 35;
			}elseif ($infoEval['Service']['id'] == 35){
				$this->data['Evaluation']['service_id'] = 35;
				//service #24
			}elseif ($infoEval['Service']['id'] == 24){
				$this->data['Evaluation']['service_id'] = 36;
			}elseif ($infoEval['Service']['id'] == 36){
				$this->data['Evaluation']['service_id'] = 36;
				//service #40
			}elseif ($infoEval['Service']['id'] == 40){
				$this->data['Evaluation']['service_id'] = 41;
			}elseif ($infoEval['Service']['id'] == 41){
				$this->data['Evaluation']['service_id'] = 41;
				//service #42-43
			}elseif ($infoEval['Service']['id'] == 42){
				$this->data['Evaluation']['service_id'] = 43;
			}elseif ($infoEval['Service']['id'] == 43){
				$this->data['Evaluation']['service_id'] = 43;
				//service #44-45
			}elseif ($infoEval['Service']['id'] == 44){
				$this->data['Evaluation']['service_id'] = 45;
			}elseif ($infoEval['Service']['id'] == 45){
				$this->data['Evaluation']['service_id'] = 45;
			}

			$serviceInfo = $this->Evaluation->Service->servicesInfo($this->data['Evaluation']['service_id']);
			$this->data['Service']['name'] = $serviceInfo['Service']['name'];

			# Info about the last_id - last Evaluation-Test
			$this->data['Evaluation']['order_id'] = $infoEval['Evaluation']['order_id'];
			$this->data['Evaluation']['last_id'] = $idEval;

			# Flag control for the last test
			$this->data['Evaluation']['last_test'] = 1;

			$this->data['Employee']['email'] = $infoEval['Employee']['email'];

			# Evaluate the Status of the current Test before to increment the Test test_serie
			# 7 Canceled by user / 14 Auto-canceled(2nd reminder) / 15 Canceled by admin / 16 Canceled by employee / 18 Auto-canceled(not received by mail)
			if (
				$infoEval['Status']['id'] == 7 || $infoEval['Status']['id'] == 14 || $infoEval['Status']['id'] == 15 ||
				$infoEval['Status']['id'] == 16 || $infoEval['Status']['id'] == 18
			) {
				$this->data['Evaluation']['new_test_serie'] = $infoEval['Evaluation']['test_serie'];
			} else {
				$this->data['Evaluation']['new_test_serie'] = $infoEval['Evaluation']['test_serie'] + 1;
			}

			$tokenhash = Security::hash($this->data['Employee']['name'] . $this->data['Evaluation']['new_test_serie'], null, true);
			$this->data['Evaluation']['tokenhash'] = $tokenhash;

			$this->data['Evaluation']['communication_id'] = $infoEval['Evaluation']['communication_id'];
			$this->data['Evaluation']['createdby'] = $this->Session->read('Auth.User.username');
		}
		$teams = $this->Evaluation->Requester->Team->teamsCustomer($this->data['Customer']['id']);

		# Admin
		if ($this->group_id == 1) {
			$requesters = array();
		} elseif ($this->group_id == 2 || $this->group_id == 3) {
			# Superv - Case manager
			$requesters = $this->Evaluation->Requester->listRequestSupervPlus($this->requester_id);
			$this->data['Evaluation']['requester_id'] = $this->requester_id;
			$this->data['Evaluation']['team_id'] = $this->team_id;
		}
		$currentLang = Configure::read('Config.language');
		$communications = $this->Evaluation->Communication->find('list', array('fields' => array('id', 'name_' . $currentLang), 'order' => 'id ASC'));
		$this->set(compact('requesters', 'communications', 'teams', 'infoEval', 'idEval'));
	}


	function edit($id = null)
	{
		$this->idEmptyRedirect($id, 'index');
		if (!empty($this->data)) {
			if ($this->Evaluation->save($this->data)) {
				# There is some Doctor information that need to be updated
				$this->flashSuccess(__('El test fué actualizado.', true), 'index/order_code:' . $this->data['Order']['order_code']);
			} else {
				$this->flashWarning(__('El test no fué actualizado. Corrija el error.', true));
			}
		} else {
			# Get the Order view information			
			$infoEval = $this->Evaluation->infoEval($id);

			# set up default values for form
			$this->data['Order']['order_code'] = $infoEval['Order']['order_code'];
			$this->data['Employee']['name'] = $infoEval['Employee']['first_name'] . ' ' . $infoEval['Employee']['last_name'];
			$this->data['Employee']['email'] = $infoEval['Employee']['email'];
			$this->data['Employee']['id'] = $infoEval['Employee']['id'];

			$this->data['Customer']['id'] = $infoEval['Customer']['id'];
			$this->data['Customer']['name'] = $infoEval['Customer']['name'];
			$this->data['Service']['name'] = $infoEval['Service']['name'];
			$this->data['Service']['id'] = $infoEval['Service']['id'];

			# Info about the current Evaluation
			$this->data['Evaluation']['id'] = $id;
			$this->data['Evaluation']['test_serie'] = $infoEval['Evaluation']['test_serie'];
			$this->data['Evaluation']['last_test'] = $infoEval['Evaluation']['last_test'];
			$this->data['Evaluation']['created'] = $infoEval['Evaluation']['created'];
			$this->data['Evaluation']['order_id'] = $infoEval['Evaluation']['order_id'];
			$this->data['Evaluation']['service_id'] = $infoEval['Evaluation']['service_id'];
			$this->data['Evaluation']['requester_id'] = $infoEval['Evaluation']['requester_id'];
			$this->data['Evaluation']['status_id'] = $infoEval['Evaluation']['status_id'];

			$this->data['Evaluation']['communication_id'] = $infoEval['Evaluation']['communication_id'];
			$this->data['Evaluation']['modifiedby'] = $this->Session->read('Auth.User.username');

			$this->data['Requester']['requester_id'] = $infoEval['Evaluation']['requester_id'];
			$this->data['Requester']['name'] = $infoEval['Requester']['last_name'] . ', ' . $infoEval['Requester']['first_name'];
			$this->data['Requester']['teamname'] = $infoEval['Team']['name'];
		}

		# Get the current language for status		
		$currentLang = Configure::read('Config.language');
		$communications = $this->Evaluation->Communication->find('list', array('fields' => array('id', 'name_' . $currentLang), 'order' => 'id ASC'));

		# Admin
		if ($this->group_id == 1) {
			$statuses = $this->Evaluation->Status->listStatusName(2, 1, 'name_' . $currentLang, 'Status');
		} elseif ($this->group_id == 2 || $this->group_id == 3) {
			# Superv - Case manager
			$statuses = $this->Evaluation->Status->listStatusName(2, 2, 'name_' . $currentLang, 'Status');
		}
		$this->set(compact('infoEval', 'statuses', 'communications'));
	}


	function resend_quest()
	{
		if (!empty($this->params['named']['eval'])) {
			$eval_id = $this->params['named']['eval'];
		}
		if (!empty($this->data)) {
			$this->Evaluation->Order->Employee->id = $this->data['Employee']['id'];
			$this->data['Employee']['email'] = trim($this->data['Employee']['email']);
			if ($this->Evaluation->Order->Employee->saveField('email', $this->data['Employee']['email'])) {

				$this->__sendOrderQuest($this->data['Evaluation']['test_serie'], $this->data['Evaluation']['tokenhash'], $this->data['Employee']['name'], $this->data['Customer']['name'], $this->data['Employee']['id'], $this->data['Employee']['email'], $this->data['Employee']['langue']);
				$this->flashSuccess(__('El cuestionario fué reenviado.', true), 'index/order_code:' . $this->data['Order']['order_code']);
			} else {
				$this->flashWarning(__('El cuestionario no fué reenviado. Intente de nuevo.', true));
			}
		} else {
			$infoEval = $this->Evaluation->infoEval($eval_id);

			# set up default values for form
			$this->data['Order']['order_code'] = $infoEval['Order']['order_code'];
			$this->data['Employee']['name'] = $infoEval['Employee']['first_name'] . ' ' . $infoEval['Employee']['last_name'];
			$this->data['Employee']['email'] = $infoEval['Employee']['email'];
			$this->data['Employee']['id'] = $infoEval['Employee']['id'];
			$this->data['Employee']['langue'] = $infoEval['Employee']['langue'];
			$this->data['Customer']['id'] = $infoEval['Customer']['id'];
			$this->data['Customer']['name'] = $infoEval['Customer']['name'];
			$this->data['Service']['name'] = $infoEval['Service']['name'];
			$this->data['Evaluation']['test_serie'] = $infoEval['Evaluation']['test_serie'];
			$this->data['Evaluation']['tokenhash'] = $infoEval['Evaluation']['tokenhash'];

			$this->data['Requester']['requester_id'] = $infoEval['Evaluation']['requester_id'];
			$this->data['Requester']['name'] = $infoEval['Requester']['last_name'] . ', ' . $infoEval['Requester']['first_name'];
			$this->data['Requester']['teamname'] = $infoEval['Team']['name'];
		}
		$this->set(compact('infoEval'));
	}

	function refuse_test()
	{
		if (!empty($this->params['named']['ouqstapw']) && !empty($this->params['named']['f08n'])) {
			$eval_check = $this->params['named']['ouqstapw'];
			$emp_id = $this->params['named']['f08n'];
		}

		$evalToken = $this->Evaluation->findAllByTokenhash($eval_check);

		if (!empty($evalToken)) {

			if ($evalToken[0]['Evaluation']['status_id'] == 9) {
				$tokenPage = 1;
				$today = date('Y-m-d');
				$current_emp = $emp_id;
				$current_order = $evalToken[0]['Order']['id'];
				$current_eval = $evalToken[0]['Evaluation']['id'];

				$this->Evaluation->id = $evalToken[0]['Evaluation']['id'];

				// Load other models before saving data
				$this->loadModel('Order');
				$this->loadModel('Employee');

				// $data
				$this->data['Evaluation']['last_test'] = 0;
				$this->data['Evaluation']['status_id'] = 88;
				$this->data['Evaluation']['status_date'] = $today;

				$this->data['Order']['id'] = $current_order;
				$this->data['Order']['status_id'] = 88;
				$this->data['Order']['status_date'] = $today;

				// Directly save data with without beforesave and aftersave callbacks 
				if ($this->Evaluation->save($this->data, array('callbacks' => 'false'))) {

					$this->Order->save($this->data, array('callbacks' => 'false'));

					$this->Employee->id = $current_emp;
					$this->Employee->saveField('ind', 0);

					$this->flashSuccess(__('Your request of refusing to complete the questionnaires was completed', true), '/pages/logout_usr');
				}
			} else {
				$tokenPage = 0;
			}
		} else {
			$tokenPage = 2;
		}
		$this->set(compact('tokenPage'));
	}


	function view_claim_letter()
	{
		if (isset($this->params['named']['eval'])) {
			$lang_id = $this->params['named']['elang'];
			$eval_id = $this->params['named']['eval'];
			$test_serie = $this->params['named']['test_serie'];
		}

		# Get the customer address / patient name / order code => to the letter	
		$infoEmployeeEvalOrder = $this->Evaluation->infoEmployeeEvalOrder($eval_id);

		$this->loadModel('DocLabel');
		if ($test_serie == 1) {
			$labelsClaimLReport = $this->DocLabel->labelsQSTXReport(1, $lang_id, 2, 1);
		} elseif ($test_serie > 1) {
			$labelsClaimLReport = $this->DocLabel->labelsQSTXReport(2, $lang_id, 2, 1);
		}
		$this->layout = 'pdf'; //this will use the pdf.ctp layout	
		$this->set(compact('lang_id', 'infoEmployeeEvalOrder', 'labelsClaimLReport', 'test_serie'));
		$this->render();
	}


	function view_incompl_letter()
	{
		if (isset($this->params['named']['eval'])) {
			$lang_id = $this->params['named']['elang'];
			$eval_id = $this->params['named']['eval'];
		}
		# Get the customer address / patient name / order code => to the letter	
		$infoEmployeeEvalOrder = $this->Evaluation->infoEmployeeEvalOrder($eval_id);
		$this->loadModel('DocLabel');
		$labelsIncomplLetter = $this->DocLabel->labelsQSTXReport(4, $lang_id, 1, 1);
		$this->layout = 'pdf'; //this will use the pdf.ctp layout
		$this->set(compact('lang_id', 'infoEmployeeEvalOrder', 'labelsIncomplLetter'));
		$this->render();
	}


	function view_complete_letter($id = null)
	{
		$this->idEmptyRedirect($id, 'index');
		# Get the customer address / patient name / order code => to the letter	
		$infoCustomerEmpEvalOrder = $this->Evaluation->infoCustomerEmpEvalOrder($id);

		$this->loadModel('DocLabel');
		$labelsComplSLFLetter = $this->DocLabel->labelsQSTXReport(7, 2, 1, 0);

		$this->layout = 'pdf'; //this will use the pdf.ctp layout
		$this->set(compact('infoCustomerEmpEvalOrder', 'labelsComplSLFLetter'));
		$this->render();
	}


	function eval_frequency()
	{
		if (!empty($this->data)) {
			$week_rep = 0;
			$year_rep =  $this->data['Evaluation']['report_test_date']['year'];
			$month_rep =  $this->data['Evaluation']['report_test_date']['month'];
			$week_rep =  $this->data['Evaluation']['week_day'];
			$type_rep = $this->data['Evaluation']['rep_test_type'];

			$this->redirect(array('action' => 'tests_report', 'type_rep' => $type_rep, 'year' => $year_rep, 'month' => $month_rep, 'week' => $week_rep));
		}
	}


	function tests_report()
	{
		# First time the page is loaded 
		if (isset($this->params['named']['type_rep'])) {
			$week_rep = 0;
			$type_rep = $this->params['named']['type_rep'];
			$month_rep = $this->params['named']['month'];
			$year_rep = $this->params['named']['year'];
			if (isset($this->params['named']['week'])) {
				$week_rep = $this->params['named']['week'];
			}
		}
		//type_rep:2/year:2013/month:01
		//$reportsData = $this->Evaluation->userTestByStatus('', 1, 2013, 2);
		if (!empty($type_rep)) {
			$reportsData = $this->Evaluation->userTestByStatus($week_rep, $month_rep, $year_rep, $type_rep);
			// var_dump($reportsData);
			// exit;
		}
		$this->layout = 'pdf'; //this will use the pdf.ctp layout
		$this->set(compact('reportsData', 'type_rep', 'week_rep', 'month_rep', 'year_rep'));
		$this->render();
	}


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

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


	####################### Export Cancelled and incomplete Tests to Excel ###################################

	function export_cancels_xls()
	{
		# Cancellations Report

		// Dates added for customized tests. Commented out.
		$previous_month = '2020-12-18';
		$previous_week = '2024-08-06';
		$today = '2024-08-18';

		# Define a 7 day period for the report to run query of cancelled tests.
		// $today = date('Y-m-d', time());
		//$today was changed to the7 previous day the report is generated to allow 
		//a previous week range for the report starting the previous Monday 
		//and ending on Sunday for a report printed every Monday	
		// $today = date('Y-m-d', strtotime("-1 days"));	
		// $previous_week = date('Y-m-d', strtotime("-7 days"));	

		$this->layout = 'ajax';

		# Call to functions from eveluation model to find both cancelled and incomplete tests (partially  answered)	
		$listTestsStatus7s = $this->Evaluation->listTestsStatus7($today, $previous_week);
		$listTestsStatus8Monthlys = $this->Evaluation->listTestsStatus8Monthly($previous_month);
		$listTestsStatus8Weeklys = $this->Evaluation->listTestsStatus8Weekly($today, $previous_week);
		$listTestsStatus14s = $this->Evaluation->listTestsStatus14($today, $previous_week);
		$listTestsStatus16s = $this->Evaluation->listTestsStatus16($today, $previous_week);
		# Commented out support for incomplete tests; now in charge by the incompleteorders Shell. 
		# Removed from APP\views\evaluations\export_cancels_xls.ctp as well.
		$listIncompleteTests = $this->Evaluation->listIncompleteTests($today, $previous_week);

		# Set and render the information for the view    					
		$this->set('listTestsStatus7', $listTestsStatus7s);
		$this->set('listTestsStatus8Monthly', $listTestsStatus8Monthlys);
		$this->set('listTestsStatus8Weekly', $listTestsStatus8Weeklys);
		$this->set('listTestsStatus14', $listTestsStatus14s);
		$this->set('listTestsStatus16', $listTestsStatus16s);
		# Commmented out support for incomplete tests.	
		$this->set('listIncompleteTests', $listIncompleteTests);
		$this->render('export_cancels_xls', 'export_cancels_xls');
	}
			
	function __sendOrderQuest($testSerieCtrl, $tokeval, $nameEmp, $nameCust, $idEmp, $emailEmp, $lang_id){
		$finalMsg ='';
		
		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']; //July 25th 2015 - Fixed a bug where the tokenhash and the language 
		//fields - variables gave an undefined index error message on the system screen. The information fetched by the $infoeval function under 
		//Evaluation.php was improperly called by both this controller and the resend_quest view in the views/evaluations folder
		//changes include lines #586, 560, 331 and 341 on this file as well as line #344 on Evaluation.php and #19 and 24 on the 
		//resend_quest view in the views/evaluations folder. The language of the email is now chosen correctly and the tokenhash 
		//is fetched and inserted in the link to the questionnaire inside the email as it is intended, allowing people to have 
		//access to their online evaluation when resent. */
		########################################################################################################################
				
		$this->loadModel('DocLabel');

		// follow-up email message WPS Experts Inc.		
		if (($testSerieCtrl > 1)  && ($nameCust == 'WPS Experts Inc.')){
			$labelsEmailPatient = $this->DocLabel->labelsEmail(10, 1, $lang_id);	
			
			$this->Email->subject = $labelsEmailPatient[0]['DocLabel'][$field_langue];
			$finalMsg .= $labelsEmailPatient[1]['DocLabel'][$field_langue].'<br/><br/>';
			$finalMsg .= $labelsEmailPatient[2]['DocLabel'][$field_langue].'<br/><br/>'; //' '.$labelsEmailPatient[3]['DocLabel'][$field_langue].'<br/><br/>';
			$finalMsg .= $labelsEmailPatient[3]['DocLabel'][$field_langue].'<br/><br/>';
			$finalMsg .= $labelsEmailPatient[4]['DocLabel'][$field_langue].'<br/><br/>';
			$finalMsg .= '<a href ='.'https://e-testmetrix.ca/pages/validate_emailaccess/wtf:'.$tokeval.'/udans:'.$passw.'/f08n:'.$idEmp.'>'.$labelsEmailPatient[5]['DocLabel'][$field_langue].'</a><br/><br/>';
			$finalMsg .= $labelsEmailPatient[6]['DocLabel'][$field_langue].'<br/><br/>';
			$finalMsg .= 'Testmetrix Admin Service<br/><br/><br/>';		
			//$finalMsg .= '<font size="-2"><i><b>'.$labelsEmailPatient[7]['DocLabel'][$field_langue].'<br/>';
			//$finalMsg .= '<a href ='.'https://e-testmetrix.ca/pages/refuse_emailaccess/ouqstapw:'.$tokeval.'/udans:'.$passw.'/f08n:'.$idEmp.'>'.$labelsEmailPatient[8]['DocLabel'][$field_langue].'</b></i><br/><br/></font>';
		
		}
		// initial email message WPS Experts Inc.
		elseif (($testSerieCtrl == 1) && ($nameCust == 'WPS Experts Inc.')){
			$labelsEmailPatient = $this->DocLabel->labelsEmail(11, 1, $lang_id);				
			
				$this->Email->subject = $labelsEmailPatient[0]['DocLabel'][$field_langue];
				$finalMsg .= $labelsEmailPatient[1]['DocLabel'][$field_langue].'<br/><br/>';
				$finalMsg .= $labelsEmailPatient[2]['DocLabel'][$field_langue].'<br/><br/>'; 
				$finalMsg .= $labelsEmailPatient[3]['DocLabel'][$field_langue].'<br/><br/>';
				$finalMsg .= $labelsEmailPatient[4]['DocLabel'][$field_langue].'<br/><br/>';
				$finalMsg .= $labelsEmailPatient[5]['DocLabel'][$field_langue].'<br/><br/>';
				$finalMsg .= '<a href ='.'https://e-testmetrix.ca/pages/validate_emailaccess/wtf:'.$tokeval.'/udans:'.$passw.'/f08n:'.$idEmp.'>'.$labelsEmailPatient[6]['DocLabel'][$field_langue].'</a><br/><br/>';
				$finalMsg .= $labelsEmailPatient[7]['DocLabel'][$field_langue].'<br/><br/>';
				$finalMsg .= 'Testmetrix Admin Service<br/><br/><br/>';		
				//$finalMsg .= '<font size="-2"><i><b>'.$labelsEmailPatient[8]['DocLabel'][$field_langue].'<br/>';
				//$finalMsg .= '<a href ='.'https://e-testmetrix.ca/pages/refuse_emailaccess/ouqstapw:'.$tokeval.'/udans:'.$passw.'/f08n:'.$idEmp.'>'.$labelsEmailPatient[9]['DocLabel'][$field_langue].'</b></i><br/><br/></font>';			
		}
		// follow-up email message Allan Memorial Institute
		elseif (($testSerieCtrl > 1) && ($nameCust == 'Dr. Howard Margolese')){
			$labelsEmailPatient = $this->DocLabel->labelsEmail(13, 1, $lang_id);				
			
				$this->Email->subject = $labelsEmailPatient[0]['DocLabel'][$field_langue];
				$finalMsg .= $labelsEmailPatient[1]['DocLabel'][$field_langue].'<br/><br/>';
				$finalMsg .= $labelsEmailPatient[2]['DocLabel'][$field_langue].'<br/><br/>'; 
				$finalMsg .= $labelsEmailPatient[3]['DocLabel'][$field_langue].'<br/><br/>';
				$finalMsg .= $labelsEmailPatient[4]['DocLabel'][$field_langue].'<br/><br/>';
				$finalMsg .= $labelsEmailPatient[5]['DocLabel'][$field_langue].'<br/><br/>';
				$finalMsg .= '<a href ='.'https://e-testmetrix.ca/pages/validate_emailaccess/wtf:'.$tokeval.'/udans:'.$passw.'/f08n:'.$idEmp.'>'.$labelsEmailPatient[6]['DocLabel'][$field_langue].'</a><br/><br/>';
				$finalMsg .= $labelsEmailPatient[7]['DocLabel'][$field_langue].'<br/><br/>';
				$finalMsg .= 'Testmetrix Admin Service<br/><br/><br/>';		
				//$finalMsg .= '<font size="-2"><i><b>'.$labelsEmailPatient[8]['DocLabel'][$field_langue].'<br/>';
				//$finalMsg .= '<a href ='.'https://e-testmetrix.ca/pages/refuse_emailaccess/ouqstapw:'.$tokeval.'/udans:'.$passw.'/f08n:'.$idEmp.'>'.$labelsEmailPatient[9]['DocLabel'][$field_langue].'</b></i><br/><br/></font>';			
		}
		// initial email message Allan Memorial Institute
		elseif (($testSerieCtrl == 1) && ($nameCust == 'Dr. Howard Margolese')){
			$labelsEmailPatient = $this->DocLabel->labelsEmail(12, 1, $lang_id);				
			
				$this->Email->subject = $labelsEmailPatient[0]['DocLabel'][$field_langue];
				$finalMsg .= $labelsEmailPatient[1]['DocLabel'][$field_langue].'<br/><br/>';
				$finalMsg .= $labelsEmailPatient[2]['DocLabel'][$field_langue].'<br/><br/>'; 
				$finalMsg .= $labelsEmailPatient[3]['DocLabel'][$field_langue].'<br/><br/>';
				$finalMsg .= $labelsEmailPatient[4]['DocLabel'][$field_langue].'<br/><br/>';
				$finalMsg .= $labelsEmailPatient[5]['DocLabel'][$field_langue].'<br/><br/>';
				$finalMsg .= '<a href ='.'https://e-testmetrix.ca/pages/validate_emailaccess/wtf:'.$tokeval.'/udans:'.$passw.'/f08n:'.$idEmp.'>'.$labelsEmailPatient[6]['DocLabel'][$field_langue].'</a><br/><br/>';
				$finalMsg .= $labelsEmailPatient[7]['DocLabel'][$field_langue].'<br/><br/>';
				$finalMsg .= 'Testmetrix Admin Service<br/><br/><br/>';		
				//$finalMsg .= '<font size="-2"><i><b>'.$labelsEmailPatient[8]['DocLabel'][$field_langue].'<br/>';
				//$finalMsg .= '<a href ='.'https://e-testmetrix.ca/pages/refuse_emailaccess/ouqstapw:'.$tokeval.'/udans:'.$passw.'/f08n:'.$idEmp.'>'.$labelsEmailPatient[9]['DocLabel'][$field_langue].'</b></i><br/><br/></font>';			
		}
		// follow-up email message TELUS Health
		elseif (($testSerieCtrl > 1) && ($nameCust == 'TELUS Health')){
			$labelsEmailPatient = $this->DocLabel->labelsEmail(2, 1, $lang_id);	
			
			$this->Email->subject = $labelsEmailPatient[0]['DocLabel'][$field_langue];
			$finalMsg .= $labelsEmailPatient[1]['DocLabel'][$field_langue].'<br/><br/>';
			$finalMsg .= $labelsEmailPatient[2]['DocLabel'][$field_langue].' '.$labelsEmailPatient[3]['DocLabel'][$field_langue].'<br/><br/>';
			$finalMsg .= $labelsEmailPatient[4]['DocLabel'][$field_langue].'<br/><br/>'.$labelsEmailPatient[5]['DocLabel'][$field_langue].' '.$labelsEmailPatient[6]['DocLabel'][$field_langue].'<br/><br/>';
			$finalMsg .= $labelsEmailPatient[7]['DocLabel'][$field_langue].'<br/><br/>';
			$finalMsg .= '<a href ='.'https://e-testmetrix.ca/pages/validate_emailaccess/wtf:'.$tokeval.'/udans:'.$passw.'/f08n:'.$idEmp.'>'.$labelsEmailPatient[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">'.$labelsEmailPatient[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>'.$labelsEmailPatient[10]['DocLabel'][$field_langue].'<br/>';
			//$finalMsg .= '<a href ='.'https://e-testmetrix.ca/pages/refuse_emailaccess/ouqstapw:'.$tokeval.'/udans:'.$passw.'/f08n:'.$idEmp.'>'.$labelsEmailPatient[11]['DocLabel'][$field_langue].'</b></i><br/><br/></font>';
		
		}
		// initial email message TELUS Health
		elseif (($testSerieCtrl == 1) && ($nameCust == 'TELUS Health')){
			$labelsEmailPatient = $this->DocLabel->labelsEmail(1, 1, $lang_id);	
			
			$this->Email->subject = $labelsEmailPatient[0]['DocLabel'][$field_langue];
			$finalMsg .= $labelsEmailPatient[1]['DocLabel'][$field_langue].'<br/><br/>';
			$finalMsg .= $labelsEmailPatient[2]['DocLabel'][$field_langue].' '.$labelsEmailPatient[3]['DocLabel'][$field_langue].'<br/><br/>';
			$finalMsg .= $labelsEmailPatient[4]['DocLabel'][$field_langue].'<br/><br/>'.$labelsEmailPatient[5]['DocLabel'][$field_langue].' '.$labelsEmailPatient[6]['DocLabel'][$field_langue].'<br/><br/>';
			$finalMsg .= $labelsEmailPatient[7]['DocLabel'][$field_langue].'<br/><br/>';
			$finalMsg .= '<a href ='.'https://e-testmetrix.ca/pages/validate_emailaccess/wtf:'.$tokeval.'/udans:'.$passw.'/f08n:'.$idEmp.'>'.$labelsEmailPatient[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">'.$labelsEmailPatient[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>'.$labelsEmailPatient[10]['DocLabel'][$field_langue].'<br/>';
			//$finalMsg .= '<a href ='.'https://e-testmetrix.ca/pages/refuse_emailaccess/ouqstapw:'.$tokeval.'/udans:'.$passw.'/f08n:'.$idEmp.'>'.$labelsEmailPatient[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->to = $nameEmp.'<'.$emailEmp.'>';
		###ADDED A BLIND CARBON COPY OF EACH ORDER EMAIL###
		$this->Email->bcc = array('admin.service@e-testmetrix.ca','admin@e-testmetrix.ca');		
		$this->Email->template = 'initial_test';
		//$this->set(compact('labelsEmailPatient', 'field_langue', 'finalMsg'));
		$this->set('finalMsg', $finalMsg);
		//$this->Email->send($finalMsg);
		$this->Email->send();			
		
	}
	

}
