<?php
/**
 * This file is for newsLetter
 *
 * This file is having newLetterCron class for newsletter
 *
 * PHP version 5.0
 *
 * @category	Anova
 * @package		Admin
 * @author 		sridhar_68ag07
 * @copyright 	Copyright (c) 2009 {@link http://www.agriya.com Agriya Infoway}
 * @license		http://www.agriya.com Agriya Infoway Licence
 * @version		SVN: $Id: $
 * @since 		2008-12-26
 *
 **/
require_once('../common/configs/config.inc.php'); //configurations

$CFG['mods']['include_files'][] = 'common/classes/swiftmailer/lib/EasySwift.php';
$CFG['lang']['include_files'][] =	'languages/%s/common/email_notify.inc.php';

//compulsory
$CFG['mods']['is_include_only']['html_header'] = false;
$CFG['html']['is_use_header'] = false;
/**
 * To include various types of files
 */
require($CFG['site']['project_path'].'common/application_top.inc.php');

set_time_limit(0);
class newLetterCron extends FormHandler
	{
		public function getNewsLetter($table_name, $fields_arr=array())
			{
				$sql = 'SELECT ';
				foreach($fields_arr as $field_name)
						$sql .= $field_name . ', ';
				$sql = substr($sql, 0, strrpos($sql, ','));
				$sql .= ' FROM '.$table_name.
						' WHERE status != \'Finished\' ORDER BY news_letter_id limit 0,1';

				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt);
				    if (!$rs)
					    trigger_db_error($this->dbObj);

				$row = array();
				if ($rs->PO_RecordCount())
					$row = $rs->FetchRow();
				else
					return $row;

				$ret_fields_arr = array();
				foreach($fields_arr as $field_name)
					$ret_fields_arr[$field_name] = isset($row[$field_name]) ? $row[$field_name] : '';
				return $ret_fields_arr;
			}

		public function getNewsLetterSetting($user_id)
			{
				$sql = 'SELECT news_letter FROM '.$this->CFG['db']['tbl']['users_ans_log'].
						' WHERE user_id = '.$this->dbObj->Param('user_id');

				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($user_id));
				    if (!$rs)
					    trigger_db_error($this->dbObj);

				if($row = $rs->FetchRow())
					return $row['news_letter'];
			}

		public function sendNewLetter($table_name, $fields_arr=array(), $new_letter_arr, $CFG)
			{
				$new_letter_arr['sql_condition'] = ($new_letter_arr['sql_condition'] == '') ? '1 ' : $new_letter_arr['sql_condition'];

				$sql = 'SELECT ';
				foreach($fields_arr as $field_name)
						$sql .= $field_name . ', ';
				$sql = substr($sql, 0, strrpos($sql, ','));
				$sql .= " FROM ".$table_name.
						" WHERE user_id > ".$this->dbObj->Param($new_letter_arr['upto_user_id']).
						" AND ".html_entity_decode (stripslashes($new_letter_arr['sql_condition'])).
						" ORDER BY user_id limit 0,".$this->dbObj->Param($CFG['news_letter']['send_count']);
				// prepare sql

				$stmt = $this->dbObj->Prepare($sql);
				// execute sql
				$rs = $this->dbObj->Execute($stmt, array($new_letter_arr['upto_user_id'],$CFG['news_letter']['send_count']));
				//raise user error... fatal
				if (!$rs)
						trigger_db_error($this->dbObj);

				$row = array();
				if ($count = $rs->PO_RecordCount())
					{
						while($row = $rs->FetchRow())
							{
								if( $new_letter_arr['based_user_settings'] == 'Yes')
									{
										if($this->getNewsLetterSetting($row['user_id']) == 'No')
											continue;
									}
							 	$subject = $this->getMailContent($new_letter_arr['subject'], array('VAR_USERNAME'=>$row['display_name'], 'VAR_EMAIL'=>$row['email'],'VAR_PASSWORD'=>$row['password']));
								$content = $this->getMailContent($new_letter_arr['body'], array('VAR_USERNAME'=>$row['display_name'], 'VAR_EMAIL'=>$row['email'],'VAR_PASSWORD'=>$row['password']));
								$is_ok = $this->_sendMail($row['email'], $subject, $content, $CFG['site']['noreply_name'], $CFG['site']['noreply_email']);
								$ret_arr = array('user_id'=>$row['user_id'],'total'=>$count);
							}
						return $ret_arr;
					}
				return false;
			}
		private function _sendMail($to_email, $subject, $body, $sender_name, $sender_email)
			{
				$this->buildEmailTemplate($subject, $body, false, true);
				$EasySwift = new EasySwift($this->getSwiftConnection());
				$EasySwift->flush();
				$EasySwift->addPart($this->getEmailContent(), "text/html");
				$from_address = $sender_name.'<'.$sender_email.'>';
				return $EasySwift->send($to_email, $from_address, $this->getEmailSubject());
			}

		public function getMailContent($content, $fieldsArr)
			{
				$content = nl2br($content);
				$chkArray = array('VAR_EMAIL','VAR_PASSWORD','VAR_USERNAME');
				foreach($chkArray as $value)
					{
						$toReplace = $value;
						if(array_key_exists($value, $fieldsArr))
							$content = str_ireplace($toReplace, $fieldsArr[$value], $content);
						else
							$content = str_ireplace($toReplace, '', $content);
					}
				return $content;
			}

		public function updateNewsLetter($table_name, $new_letter_id, $status, $upto=0, $total = 0)
			{
				$val_arr = array();
				$val_arr[] = $status;

				$sql = 'UPDATE '.$table_name .
						' SET '.
						'status='.$this->dbObj->Param($status);

				if ($upto != 0)
					{
						$sql .= ', upto_user_id = '.$this->dbObj->Param($upto);
						$val_arr[] = $upto;
					}
				if ($total != 0)
					{
						$sql .= ', total_sent = total_sent + '.$this->dbObj->Param($total);
						$val_arr[] = $total;
					}
				$sql .= ' WHERE news_letter_id='.$this->dbObj->Param($new_letter_id);
				$val_arr[] = $new_letter_id;
				// prepare sql
				$stmt = $this->dbObj->Prepare($sql);
				// execute sql
				$result = $this->dbObj->Execute($stmt, $val_arr);
				//raise user error... fatal
				if (!$result)
						trigger_db_error($this->dbObj);
			}
	}
//<<<<<-------------- Class LoginFormHandler begins ---------------//
//-------------------- Code begins -------------->>>>>//
$newLetterCron = new newLetterCron();
$newLetterCron->setFormField('news_letter_id', '');
$newLetterCron->setFormField('subject', '');
$newLetterCron->setFormField('body', '');
$newLetterCron->setFormField('upto_user_id', '');

$new_letter_arr = $newLetterCron->getNewsLetter($CFG['db']['tbl']['news_letter'], array('news_letter_id','subject','body','upto_user_id', 'sql_condition', 'based_user_settings'));
if ($new_letter_arr)
	{
		if ($user_arr = $newLetterCron->sendNewLetter($CFG['db']['tbl']['users'], array('user_id',$newLetterCron->getUserTableField('display_name').' AS display_name',$newLetterCron->getUserTableField('name').' AS name','password','email'), $new_letter_arr, $CFG))
			$newLetterCron->updateNewsLetter($CFG['db']['tbl']['news_letter'], $new_letter_arr['news_letter_id'], 'Started', $user_arr['user_id'], $user_arr['total']);
		else
			$newLetterCron->updateNewsLetter($CFG['db']['tbl']['news_letter'], $new_letter_arr['news_letter_id'], 'Finished');
	}
?>