<?php
/**
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link      http://cakephp.org CakePHP(tm) Project
 * @since     0.2.9
 * @license   http://www.opensource.org/licenses/mit-license.php MIT License
 */
 

 
use Cake\Network\Exception\NotFoundException;
use Cake\View\Exception\MissingTemplateException;
use Cake\ORM\TableRegistry;
use Cake\Network\Email\Email;
use Aura\Intl\Exception;
/**
 * User Management and REST API controller
 *
 * This controller will be used to send out email to the uses
 *
 * @link http://book.cakephp.org/3.0/en/controllers/pages-controller.html
 */

 
class EmailsController extends AppController {

	public $uses = array('TempExpenseEmail','ExpenseEmail');
	 
	public function initialize()
	{
		parent::initialize();		
		$this->loadComponent('RequestHandler');
		
	}
	 

 
	/**
	 * This function will be called to login and authenticate user
	 *
	 * @param params will be as post request
	 * @return json response output
	 * @link http://host/Emails/processRegEmails
	*/ 
	public function processRegEmails(){
		
		$this->defineConstant();
		$content = "";// $this->readFileContent();
		try{
			if($content == ""){
				//first time writing in the file
				//$this->writeFileContent("FALSE");
				$this->startFetchAndProcess();
				//$this->writeFileContent("TRUE");
			} else {
				//every 5 second, it will come here and try to fetch DB // set 5 sec in cron job
				$contentArray = explode(':',$content);
				if($contentArray[0] == "FALSE"){
					//if FALSE returns morn than 2 min, then write TRUE in the file
					$currentTime = time();
					$lastUpdatedTimeTime = $contentArray[1];
					if((round(abs($currentTime - $lastUpdatedTimeTime) / 60,2)) > EMAIL_ROWS_PROCESS_TIME_MIN_MAX){ // SET it in constant
						$this->writeFileContent("TRUE");
					}
					return;
				} else {
					$this->writeFileContent("FALSE");
					$this->startFetchAndProcess();
					$this->writeFileContent("TRUE");
				}
			}	
		} catch(Exception $ex){
			
		}	
		exit;
	}
	
	private function startFetchAndProcess(){
		
		//fetch first 10 rows from DB where sending_count < 3	
		$update_time_target =  date("Y-m-d H:i:s", strtotime("-3 min"));
		$emailInfo = $this->TempExpenseEmail->find('all',
				array(
						'conditions' => array('count_email_attempt < ' => MAX_SENDING_COUNT, 'update_date <' =>  $update_time_target),
						'limit' => NUM_OF_EMAIL_ROW_FETCH,
						'order'=>array('create_date ASC')
						
						
				)); // SET it in constant
				
		/* $dbo = $this->TempExpenseEmail->getDatasource();
		$logs = $dbo->_queriesLog;
		var_dump($logs);
	   echo "<pre>";
		print_r($emailInfo);  exit;  
		  */
		if(!empty($emailInfo)){
		
			foreach($emailInfo as $key=>$value){
				
				$value = $value["TempExpenseEmail"];
			  
				$count = $value["count_email_attempt"];
				$count++;
				try{
					$currentDate = "'".date("Y-m-d H:i:s")."'";
					//process each row and update sending count
					$userUpdated = $this->TempExpenseEmail->updateAll(
							array('count_email_attempt' => $count,'update_date' => $currentDate ),
							array('id' => $value["id"]));
					
					 
					
					$emailData = array();
					$emailData["title"] = $value["title"];
					$emailData["unique_url"] = $value["unique_url"];
					$emailData["email"] = $value["email"];
					
					 
					 
					//send email
					$this->sendEmail($emailData);
					
					//insert into ExpenseEmail
					$inputData = array();
					$inputData["id"] = $value["id"];
					$inputData["unique_url"] = $value["unique_url"];
					$inputData["email"] = $value["email"];
					$inputData["title"] = $value["title"];
					$inputData["count_email_attempt"] = $value["count_email_attempt"];
					
					$this->ExpenseEmail->insertExpenseEmail($inputData);
					
					// delete the email record after successful sending
					$result = $this->TempExpenseEmail->deleteAll(array('id' => $value["id"]));	
					
				} catch(Exception $ex){
					
				}
			
			}
		
		}
		
	}
	
	private function writeFileContent($flag){
		$handle = fopen(REGISTRATION_EMAIL_SCHEDULE_TRACKING_FILE,"w+");
		try{
			fwrite($handle, $flag.":".time());
			 
		} catch(Exceptoin $ex){
			 
		} 
		fclose($handle);
	}
	
	private function readFileContent(){
		$handle = fopen(REGISTRATION_EMAIL_SCHEDULE_TRACKING_FILE, "r");
		try{
		 
			$contents = fread($handle, filesize(REGISTRATION_EMAIL_SCHEDULE_TRACKING_FILE));
			 
		} catch(Exceptoin $ex){
			 
		}  
		
		fclose($handle);
		 
		return trim($contents);
	}
	
	private function sendEmail($emailData){ 
		
		 
		 
			$data = array();
 			$data["email"] =  $emailData["email"];
			$data["expense_title"] = $emailData["title"];
			$data["unique_url"] = $emailData["unique_url"]; 
			
			$default = array(
					'host' => Configure::read('expensecount.email.smtp.host'),
					'port' => 587,
					'auth' => 'plain',
					'username' => Configure::read('expensecount.email.smtp.username'),
					'password' => Configure::read('expensecount.email.smtp.password'),
					'tsl' => false,
					'transport' => 'Smtp',
					'from' => array(Configure::read('expensecount.email.smtp.from') => 'ExpenseCount'),
					'returnPath' => Configure::read('expensecount.email.smtp.from'),
					'layout' => false,
					'emailFormat' => 'html',
					//'template' => 'only_text',
					'charset' => 'utf-8',
					'headerCharset' => 'utf-8',
			);
			
			 
			
			 App::uses('CakeEmail', 'Network/Email');
 		
			//echo $Email->			
			$Email = new CakeEmail($default);
	        $Email->to($data["email"]);
	        $Email->emailFormat('html');
	        $Email->template('email',null)->viewVars( array('data' => $data));
	        $Email->subject('ExpenseCount "'.$data["expense_title"].'" ');
	        $Email->replyTo(Configure::read('expensecount.email.smtp.from'));
	        $Email->from(array(Configure::read('expensecount.email.smtp.from') => "ExpenseCount.com"));
	        //$Email->smtpOptions =  $default;
	        $Email->delivery = 'Smtp';
			$Email->send();
		  
	}
	
	private function getEmailTemplate($templatePath,$local){
		return 	 $templatePath."_".$local;
	}
	 
	
	private function defineConstant(){
		
		define("EMAIL_ROWS_PROCESS_TIME_MIN_MAX",2); //value in minute
		define("NUM_OF_EMAIL_ROW_FETCH",10);
		define("MAX_SENDING_COUNT",3);
			
	}
	
}