<?php
App::uses('AppController', 'Controller');
App::uses('CakeEmail', 'Network/Email');	
/**
 * Controller name
 *
 * @var string
 */

class Y3cronController extends AppController {
	function beforeFilter(){
		$this->Auth->allow();
	}
	function index(){
		if (empty($this->request->query['rtoken']) || ($this->request->query['rtoken'] != CRONTOKEN) ){
			exit;
		}
		ini_set('memory_limit', '512M');
		$this->loadModel('User');
		
		$date1 = date('Y-m-d H:i:s', strtotime('-2 hours', time()) );
		$date2 = date('Y-m-d H:i:s');
		$joins = array(array('table'=>'user_trackings', 'alias'=>'UserTracking', 'type'=>'left', 'conditions'=>array("User.id = UserTracking.user_id AND UserTracking.created between '$date1' and '$date2'" )));
		$fields = array('User.*', 'Depot.title', 'Region.title', 'Role.*','UserTracking.*');
		$users = $this->User->find('all', array('fields'=>$fields, 'conditions'=>array('UserTracking.id IS NULL', 'User.status'=>ACTIVE), 'order'=>array('User.first_name'=>'asc', 'User.last_name'=>'asc'),'joins'=>$joins, 'group'=>array('User.id')));
		
		
		//$to = 'chand@smalution.com';
		$to = 'y3hqinsp@fastmail.fm';
		
		//echo Configure::version();
		if ($users){
			$Email = new CakeEmail();
			$Email->charset = "ISO-8859-1";
			$Email->from( 'info@smalution.com'  );
			$Email->to($to);
			//$Email->addHeaders(array('X-Mailer' => "PHP/" . phpversion(), "Content-Type"=>"text/html"));
			$Email->emailFormat('html');
			$Email->template('notification','default');
			$Email->viewVars(array('users'=>$users));
			$Email->subject('Notification');
			
			if ($Email->send()){
				echo 'Send mail';
			}
			/*
			$Email=new CakeEmail();
			$Email->template('notification','default')
				  ->viewVars(array('users'=>$users))
				  ->emailFormat('html')
				  ->to($to)
				  ->subject('Notification')
				  ->from(array('info@smalution.com'=>'Y3Distribution'))
				  ->send();
			*/
			//pr($Email);
		}
		//pr($users);
		exit;
	}
}