<?php
/**
 * This file is for question reminder
 *
 * This file is having QuestionReminderFormHandler class for question reminder
 *
 * PHP version 5.0
 *
 /**
 * PaymentUpdateFormHandler
 *
 * @package
 * @author saravanan_58ag07
 * @copyright Copyright (c) 2009
 * @version $Id$
 * @access public
 */
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';
$CFG['auth']['is_authenticate'] = false;

//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 PaymentUpdateFormHandler 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 updatePaymentDetails($upto_id, $check_count)
		    {
				if(1)
					{
						$sql = 'SELECT user_id, name, receipt_id, expiry_date, last_paid_date'.
								', DATEDIFF( expiry_date, NOW( ) ) AS trail FROM '.$this->CFG['db']['tbl']['users'].
								' WHERE (DATEDIFF(expiry_date, NOW()) <=0)'.
								' AND user_id > '.$this->dbObj->Param($upto_id).
								' ORDER BY user_id ASC LIMIT 0, '.$this->dbObj->Param($check_count);

						$stmt = $this->dbObj->Prepare($sql);
						$rslog = $this->dbObj->Execute($stmt, array($upto_id, $check_count));

						if ($count = $rslog->PO_RecordCount())
							{

								//echo '<br>coming inside $count block....';
								$ret_arr = array();
								while($payer_details = $rslog->FetchRow())
									{
										//echo '<br>coming inside while block....';
										$log_sql = 'SELECT PP_rec_id, content_type, receipt_id,'.
												' TIMESTAMP FROM '.$this->CFG['db']['tbl']['paypal_transaction_log'].
												' WHERE  ACK = \'Success\' AND updated = \'No\''.
												' AND receipt_id != \''.$payer_details['receipt_id'].'\''.
												' AND TIMESTAMP > '.$this->dbObj->Param('timestamp').
												' AND content_id = '.$this->dbObj->Param('name').
												' ORDER BY PP_rec_id ASC limit 0, 1';

										$log_stmt = $this->dbObj->Prepare($log_sql);
										$log_rs = $this->dbObj->Execute($log_stmt, array($payer_details['last_paid_date'], $payer_details['name']));
										if(!$log_rs->PO_RecordCount())
											{
												continue;
											}

										$rowbilling = $log_rs->FetchRow();
										//update it..
										//then change status for that log..
										$ret_arr = array('user_id'=>$payer_details['user_id'],'count'=>$count);
										if($payer_details)
											{
												//echo '<br>coming inside $payer_details block....';
												$tariff_details = $this->getTariffDetails($rowbilling['content_type']);
												$user_paid_type = 'Free';
												if($tariff_details['plan_amount'])
													$user_paid_type = 'Paid';
												$next_pay_date = $this->getExpiryDate($tariff_details['plan_expired'],  'Day');
												if($payer_details['last_paid_date'] != $rowbilling['TIMESTAMP'])
													$update_expiry = $this->updateExpirydate($this->CFG['db']['tbl']['users'], 'NOW()', $next_pay_date, $payer_details['user_id'], $rowbilling['receipt_id'], $rowbilling['PP_rec_id'], $rowbilling['content_type'], $user_paid_type);
											}
									}
								return $ret_arr;//user id..
							}
						else
							{
								return false;
							}
					}

		    }

		public function updateExpirydate($table, $last_paid, $expiry_date, $user_id,  $receipt_id, $log_id, $signup_type, $user_paid_type='Free')
			{
				$sql = 'UPDATE '.$table.' SET expiry_date = '.$this->dbObj->Param($expiry_date).
						', last_paid_date = '.$last_paid.
						', receipt_id = '.$this->dbObj->Param($receipt_id).
						', signup_type = '.$this->dbObj->Param($signup_type).
						', payment_gateway = \'PAYPAL\''.
						', usr_type = '.$this->dbObj->Param($user_paid_type).
						' WHERE user_id = '.$this->dbObj->Param($user_id);

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

				$sql_rec = 'UPDATE '.$this->CFG['db']['tbl']['paypal_transaction_log'].' SET updated = \'Yes\''.
						' WHERE PP_rec_id = '.$this->dbObj->Param($log_id);

				$stmt_rec = $this->dbObj->Prepare($sql_rec);
				$rs_rec = $this->dbObj->Execute($stmt_rec, array($log_id));
				if (!$rs_rec)
						trigger_db_error($this->dbObj);
			}
	}
//<<<<<-------------- Class QuestionReminderFormHandler begins ---------------//
//-------------------- Code begins -------------->>>>>//
$reminder = new PaymentUpdateFormHandler();
$reminder->member_url = $CFG['site']['url'].$CFG['redirect']['member'].'/';
if ($cron_arr = $reminder->getCronMasterDetails($CFG['db']['tbl']['cron_master'], 'Paymentplan'))
{
	//echo '<br> coming inside the paymentPlanUpdater block.....';
	if ($autoindex_arr = $reminder->updatePaymentDetails($cron_arr['upto_id'], $CFG['question']['send_count']))
		$reminder->updateCronMaster($CFG['db']['tbl']['cron_master'],'Paymentplan', 'Started', 'old',  $autoindex_arr['user_id'], $autoindex_arr['count']);
		else
			$reminder->updateCronMaster($CFG['db']['tbl']['cron_master'],'Paymentplan', 'Started', 'new');}
else
	$reminder->updateCronMaster($CFG['db']['tbl']['cron_master'],'Paymentplan', 'Started', 'new');
?>
