<?php
/**
 * This file is for question reminder
 *
 * This file is having QuestionResolvedReminderFormHandler class for question reminder
 *
 * 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 QuestionResolvedReminderFormHandler extends FormHandler
	{
		 public function getCronMasterDetails($table_name, $cron_for)
			{
				$sql = 'SELECT upto_id FROM '.$table_name.
						' WHERE cron_for = '.$this->dbObj->Param($cron_for).' AND status = \'Started\' limit 0,1';
				// prepare sql
				$stmt = $this->dbObj->Prepare($sql);
				// execute sql
				$rs = $this->dbObj->Execute($stmt, array($cron_for));
				//raise user error... fatal
				if (!$rs)
						trigger_db_error($this->dbObj);

				if ($rs->PO_RecordCount())
					{
						$row = $rs->FetchRow();
						return $row;
					}

				return false;
			}

		public function updateCronMaster($table_name, $cron_for, $status, $new_old, $upto=0, $total = 0)
			{
				$val_arr = array();
				$val_arr[] = $status;

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

				$sql .= ', upto_id = '.$this->dbObj->Param($upto);
				$val_arr[] = $upto;

				if ($total == 0)
					$sql .= ', total = '.$this->dbObj->Param($total);
					else
						$sql .= ', total = total + '.$this->dbObj->Param($total);
				$val_arr[] = $total;

				if ($new_old == 'new')
					{
						$sql .= ', start_time = '.$this->dbObj->SQLDate('Y-m-d H:i:s');
						$sql .= ', tot_finished_crons = tot_finished_crons + 1';
					}
				$sql .= ' WHERE cron_for = '.$this->dbObj->Param($cron_for);
				$val_arr[] = $cron_for;
				// 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);
			}

		/**
		 *
		 * @access public
		 * @return void
		 **/
		public function emailQuestionDetails($upto_id, $check_count)
		    {
				$sql = 'SELECT ques_id, total_answer, total_stars, question,seo_title, tags, TIMEDIFF(NOW(), date_asked) as date_asked, q.user_id'.
						', '.$this->getUserTableField('display_name').' as asked_by, '.$this->getUserTableField('name').' as name, q.status'.
						' FROM '.$this->CFG['db']['tbl']['questions'].' AS q, '.$this->CFG['db']['tbl']['users'] .' AS u'.
						' WHERE date_closed<=NOW() AND total_answer >0 AND best_ans_id = 0 AND q.user_id=u.'.$this->getUserTableField('user_id').' AND u.'.$this->getUserTableField('usr_status').'=\'Ok\' AND ques_id > '.$this->dbObj->Param($upto_id).' AND q.resolved_mail_count < '.$this->CFG['admin']['number_of_mails']['allowed'].''.
						' ORDER BY ques_id ASC limit 0, '.$this->dbObj->Param($check_count);
				$stmt = $this->dbObj->Prepare($sql);
				$rsques = $this->dbObj->Execute($stmt, array($upto_id, $check_count));
				if (!$rsques)
				        trigger_db_error($this->dbObj);
             	if ($count = $rsques->PO_RecordCount())
					{
						while($rowques = $rsques->FetchRow()){
							$ret_arr = array('user_id'=>$rowques['user_id'],'count'=>$count);

							$asker_details = $this->getUserDetailsFromUsersTable($this->CFG['db']['tbl']['users'], $rowques['user_id']);
							$admin_id = $this->getAdminUserId($this->CFG['db']['tbl']['users']);
									//$i=0;
							$email_options = $this->getEmailOptionsOfUser($rowques['user_id']);
							$send_email = false;
							if ($email_options['keyword_mail'] == 'Yes')
								{
									$reminder_subject = $this->LANG['select_best_answer_mail_subject'];
									$reminder_content = $this->LANG['select_best_answer_mail_content'];
									$send_email = true;
								}

										if (!$send_email) continue;

										$receiver_details = $this->getUserDetailsFromUsersTable($this->CFG['db']['tbl']['users'], $rowques['user_id']);
										$reminder_subject = str_ireplace('VAR_USERNAME', $receiver_details['display_name'], $reminder_subject);

										$reminder_content = str_ireplace('VAR_USERNAME', $receiver_details['display_name'], $reminder_content);
										$asker_url = getMemberUrl($rowques['user_id'], $rowques['name']);
										$asker_name = '<a href="'.$asker_url.'">'.$asker_details['display_name'].'</a>';
										$reminder_content = str_ireplace('VAR_ASKED_BY', $asker_name, $reminder_content);
										$reminder_content = str_ireplace('VAR_SITENAME', $this->CFG['site']['name'], $reminder_content);
										$reminder_content = str_ireplace('VAR_QUESTION_ASKED', '<strong>'.$rowques['question'].'</strong>', $reminder_content);
										$question_link = getUrl('answer', '?title='.$rowques['seo_title'], $rowques['seo_title'].'/', 'root');
										$reminder_content = str_ireplace('VAR_LINK', '<a href="'.$question_link.'">'.$question_link.'</a>', $reminder_content);
										$this->_sendMail($receiver_details['email'],
														 $reminder_subject,
														 $reminder_content,
														 $this->CFG['site']['noreply_name'],
														 $this->CFG['site']['noreply_email']);
										$this->updateQuestionTableResolvedEmailStatus($rowques['ques_id']);
										//$i++;
										//if ($i>10)


									} // while
						// if
						return $ret_arr;
					}
				#die('here');

				return false;
		    }

		/**
		 * To send email
		 *
		 * @param 		string $to_email to email id
		 * @param 		string $subject subject
		 * @param		string $body mail body
		 * @param 		string $sender_name sender name
		 * @param 		string $sender_email sender email
		 * @return 		void
		 * @access 		private
		 */
		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());
			}
		/**
		 *
		 * @access public
		 * @return void
		 **/
		public function updateQuestionTableResolvedEmailStatus($qid)
		    {
				#echo $qid;
				$sql = 'UPDATE '.$this->CFG['db']['tbl']['questions'].' SET resolved_mail_count= resolved_mail_count + 1'.
						' WHERE ques_id='.$this->dbObj->Param('qid');
				#echo $sql;die('here');
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($qid));
				if (!$rs)
					    trigger_db_error($this->dbObj);
		    }

		/**
		 *
		 * @access public
		 * @return void
		 **/
		public function isFavoriteQuestion($uid, $qid)
		    {
				$sql = 'SELECT bookmark_id as fav_id FROM '.$this->CFG['db']['tbl']['user_bookmarked'].
						' WHERE content_id = '.$this->dbObj->Param('qid').
						' AND user_id = '.$this->dbObj->Param('uid').
						' AND content_type = \'Question\'';
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($qid, $uid));
				if (!$rs)
					    trigger_db_error($this->dbObj);
				$ok = false;
				if ($rs->PO_RecordCount())
					$ok = true;
				return $ok;
		    }

		/**
		 *
		 * @access public
		 * @return void
		 **/
		public function getAdminUserId($user_table)
		    {
				$sql = 'SELECT '.$this->getUserTableField('user_id').' AS user_id FROM '.$user_table.' WHERE '.$this->getUserTableField('user_access').' = \'Admin\' LIMIT 1';
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt);
				if (!$rs)
						trigger_db_error($this->dbObj);
				$row = array('user_id'=> 1);
				if ($rs->PO_RecordCount())
					{
						$row = $rs->FetchRow();
					}
				return	$row['user_id'];
		    }
	}
//<<<<<-------------- Class QuestionResolvedReminderFormHandler begins ---------------//
//-------------------- Code begins -------------->>>>>//
$reminder = new QuestionResolvedReminderFormHandler();
$reminder->member_url = $CFG['site']['url'].$CFG['redirect']['member'].'/';
if ($cron_arr = $reminder->getCronMasterDetails($CFG['db']['tbl']['cron_master'], 'Resolved'))
	{
		if ($autoindex_arr = $reminder->emailQuestionDetails($cron_arr['upto_id'], $CFG['question']['send_count']))
			$reminder->updateCronMaster($CFG['db']['tbl']['cron_master'],'Resolved', 'Started', 'old',  $autoindex_arr['user_id'], $autoindex_arr['count']);
			else
				$reminder->updateCronMaster($CFG['db']['tbl']['cron_master'],'Resolved', 'Started', 'new');
	}
else
	$reminder->updateCronMaster($CFG['db']['tbl']['cron_master'],'Resolved', 'Started', 'new');
?>
