<?PHP
// reinstate denied affiliate request
function denied_timeout()
	{
	# $row=mysql_query("select afuid, UNIX_TIMESTAMP(ogcreate) from affiliate_user where status='3'");
	$row=mysql_query("select afuid, ogcreate from affiliate_user where status='3'");
	while ($rs=mysql_fetch_row($row))
		{
		if (($rs[1]+2592000)<=time())
			{
			mysql_query("delete from affiliate_user where afuid='".addslashes(trim($rs[0]))."'");
			}
		}
	}

// gives you the monthly commission rate formatted for a single
function affiliate_month_percentage($currency, $currency_type, $monthly_cost, $com_monthly)
	{
	$discounted_amount=$monthly_cost*($com_monthly/100);
	$discounted_amount=sprintf("%01.2f", $discounted_amount);
	$discounted_amount=$currency.$discounted_amount.$currency_type;

	return $discounted_amount;
	}

// gives you the monthly commission rate unformatted for a single
function affiliate_month_percentage_raw($monthly_cost, $com_monthly)
	{
	$discounted_amount=$monthly_cost*($com_monthly/100);
	$discounted_amount=sprintf($discounted_amount);

	return $discounted_amount;
	}

// shows the affiliate links in the client area
function show_affiliate_client($http_images, $uid, $sid, $http_web)
	{
	// start affiliate
	$ct=mysql_fetch_row(mysql_query("select count(*) from affiliate_user where uid='".addslashes(trim($uid))."'"));
	if ($ct[0]<=0)
		{
		$data=("
			<table width='92%' cellpadding='4' cellspacing='1' border='0'>
				<tr>
					<td align='left' valign='top'><img src='".$http_images."/menu_arrow.gif'><b>Become an Affiliate: </b> <a href='".$http_web."/new_affiliate.php?sid=".trim($sid)."'>Click to begin &gt</a></td>
				</tr>
			</table>
			");
		}
	else
		{
		$rsaff=mysql_fetch_row(mysql_query("select status from affiliate_user where uid='".addslashes(trim($uid))."'"));
		if ($rsaff[0]==0)
			{
			$data=("
				<table width='92%' cellpadding='4' cellspacing='1' border='0'>
					<tr>
						<td align='left' valign='top'><img src='".$http_images."/menu_arrow.gif'><b>Affiliate Menu: </b> <a href='".$http_web."/affiliate.php?sid=".trim($sid)."'>Click to view &gt</a></td>
					</tr>
				</table>
				");
			}
		else if ($rsaff[0]==1)
			{
			$data=("
				<table width='92%' cellpadding='4' cellspacing='1' border='0'>
					<tr>
						<td align='left' valign='top'><img src='".$http_images."/menu_arrow.gif'><b>Become an Affiliate: </b> <a href='".$http_web."/new_affiliate.php?sid=".trim($sid)."'>Click to begin &gt</a></td>
					</tr>
				</table>
				");
			}
		else if ($rsaff[0]==2)
			{
			$data=("
				<table width='100%' border='0' cellspacing='1' cellpadding='2'>
					<tr>
						<td align='left' valign='top'><img src='".$http_images."/menu_arrow.gif'><b>Become an Affiliate: </b> Your request is pending approval</td>
					</tr>
				</table>
				");
			}
		}
	
	return $data;
	}

// add in a new referred client
function add_new_referred_client($pid, $afuid, $uid, $oid)
	{
	$rsap=mysql_fetch_row(mysql_query("select com_type, package_name, monthly_cost, com_rate_month, com_rate_onetime from plan_specs where pid='".addslashes(trim($pid))."'"));

	$rsruid=mysql_fetch_row(mysql_query("select uid from affiliate_user where afuid='".addslashes(trim($afuid))."'"));

	if ($rsap[0]==1)
		{
		// one time
		$total_due_to_client=$rsap[4];
		}
	else if ($rsap[0]==2)
		{
		// monthly %
		$total_due_to_client=affiliate_month_percentage_raw($rsap[2], $rsap[3]);
		}
	else if ($rsap[0]==0)
		{
		// no commission defined for this plan
		$total_due_to_client="0";
		}
	
	$ainsert="insert into affiliate_details set ";
	$ainsert.="afuid='".((strlen(trim($afuid))==0)?"0":"".addslashes(trim($afuid))."")."', ";
	$ainsert.="refered_uid='".addslashes(trim($rsruid[0]))."', ";
	$ainsert.="oid='".addslashes(trim($oid))."', ";
	$ainsert.="record_payout_type='".addslashes(trim($rsap[0]))."', ";
	$ainsert.="pid='".addslashes(trim($pid))."', ";
	$ainsert.="package_name='".addslashes(trim($rsap[1]))."', ";
	$ainsert.="total_amount_package='".addslashes(trim($rsap[2]))."', ";
	$ainsert.="total_due_to_client='".addslashes(trim($total_due_to_client))."', ";

	$get_status=mysql_fetch_row(mysql_query("select status from hosting_order where oid='".addslashes(trim($oid))."'"));
	$status=$get_status[0];
	$ainsert.="status='".addslashes(trim($status))."', ";

	$ainsert.="ogcreate='".time."' ";
	
	mysql_query($ainsert);
	}

// update the affiliate details
function update_referred_client($pid, $afuid, $oid, $afdid)
	{
	$rsap=mysql_fetch_row(mysql_query("select com_type, package_name, monthly_cost, com_rate_month, com_rate_onetime from plan_specs where pid='".addslashes(trim($pid))."'"));

	$rsruid=mysql_fetch_row(mysql_query("select uid from affiliate_user where afuid='".addslashes(trim($afuid))."'"));

	if ($rsap[0]==1)
		{
		// one time
		$total_due_to_client=$rsap[4];
		}
	else if ($rsap[0]==2)
		{
		// monthly %
		$total_due_to_client=affiliate_month_percentage_raw($rsap[2], $rsap[3]);
		}
	else if ($rsap[0]==0)
		{
		// no commission defined for this plan
		$total_due_to_client="0";
		}

	$update="update affiliate_details set ";
	$update.="afuid='".((strlen(trim($afuid))==0)?"0":"".addslashes(trim($afuid))."")."', ";
	$update.="refered_uid='".addslashes(trim($rsruid[0]))."', ";
	$update.="oid='".addslashes(trim($oid))."', ";
	$update.="record_payout_type='".addslashes(trim($rsap[0]))."', ";
	$update.="pid='".addslashes(trim($pid))."', ";
	$update.="package_name='".addslashes(trim($rsap[1]))."', ";
	$update.="total_amount_package='".addslashes(trim($rsap[2]))."', ";
	$update.="total_due_to_client='".addslashes(trim($total_due_to_client))."', ";

	$get_status=mysql_fetch_row(mysql_query("select status from hosting_order where oid='".addslashes(trim($oid))."'"));
	$status=$get_status[0];
	$update.="status='".addslashes(trim($status))."', ";

	$update.="ogcreate='".time."' ";
	$update.="where afdid='".addslashes(trim($afdid))."'";
	
	mysql_query($update);
	}

// return the past 3 months
function past_3_months()
	{
	$current_month=date("m");
	$current_year=date("Y");
	if ($current_month==01)
		{
		$past_1=mktime (0,0,0,12,01,$current_year-1);
		$past_2=mktime (0,0,0,11,01,$current_year-1);
		$past_3=mktime (0,0,0,10,01,$current_year-1);
		}
	else if ($current_month==02)
		{
		$past_1=mktime (0,0,0,1,01,$current_year);
		$past_2=mktime (0,0,0,12,01,$current_year-1);
		$past_3=mktime (0,0,0,11,01,$current_year-1);
		}
	else if ($current_month==03)
		{
		$past_1=mktime (0,0,0,2,01,$current_year);
		$past_2=mktime (0,0,0,1,01,$current_year);
		$past_3=mktime (0,0,0,12,01,$current_year-1);
		}
	else if ($current_month>=04)
		{
		$past_1=mktime (0,0,0,$current_month-1,01,$current_year);
		$past_2=mktime (0,0,0,$current_month-2,01,$current_year);
		$past_3=mktime (0,0,0,$current_month-3,01,$current_year);
		}

	return $past_1."|".$past_2."|".$past_3."|";
	}

// grab log to get current period
function read_affiliate_period_log($below_public, $afuid)
	{
	// not there, write it
	if (!file_exists($below_public."/affiliate_period.".$afuid.".log"))
		{		
		$data=time()."|0|";

		$read = fopen ($below_public."/affiliate_period.".$afuid.".log", "w");
		$xdata = fwrite ($read, $data);
		fclose ($read);

		chmod($below_public."/affiliate_period.".$afuid.".log", 0777);

		return $data;
		}
	else
		{
		// read in log file
		$read = fopen ($below_public."/affiliate_period.".$afuid.".log", "r");
		$result = fread ($read, filesize($below_public."/affiliate_period.".$afuid.".log"));
		fclose ($read);

		return $result;
		}
	}

// grab log to get current period
function write_new_affiliate_log($below_public, $afhid, $afuid)
	{
	$data=time()."|".$afhid."|";

	$read = fopen ($below_public."/affiliate_period.".$afuid.".log", "w");
	$xdata = fwrite ($read, trim($data));
	fclose ($read);

	chmod($below_public."/affiliate_period.".$afuid.".log", 0777);
	}

// get last ran period for affiliate reports
function last_ran_client_affiliate_report($below_public)
	{
	// not there, write it
	if (!file_exists($below_public."/affiliate_period_client_report.log"))
		{		
		$data=time();

		$read = fopen ($below_public."/affiliate_period_client_report.log", "w");
		$xdata = fwrite ($read, $data);
		fclose ($read);

		chmod($below_public."/affiliate_period_client_report.log", 0777);

		return 1;
		}
	else
		{
		// read in log file
		$read = fopen ($below_public."/affiliate_period_client_report.log", "r");
		$result = fread ($read, filesize($below_public."/affiliate_period_client_report.log"));
		fclose ($read);

		return $result;
		}
	}

// update the last ran log for client affiliate status
function write_new_last_ran_client_affiliate_report($below_public)
	{
	$read = fopen ($below_public."/affiliate_period_client_report.log", "w");
	$xdata = fwrite ($read, time());
	fclose ($read);

	chmod($below_public."/affiliate_period_client_report.log", 0777);
	}

// notify client of new affiliate sign up
function affiliate_monthly_report($uid, $email_admin, $currency, $currency_type)
	{
	// PULL IN TEMPLATE
	$rs=mysql_fetch_row(mysql_query("select subject, message, default_email from email_templates where emid='17'"));
	$default_email=stripslashes(trim($rs[2]));
	$rs4=mysql_fetch_row(mysql_query("select afuid from affiliate_user where uid='".addslashes(trim($uid))."'"));

	$rt=0;
	$ot=1;
	$mt=1;
	# $row5=mysql_query("select UNIX_TIMESTAMP($ogcreate), record_payout_type, total_due_to_client from affiliate_details where afuid='".addslashes(trim($rs4[0]))."' and status='1'");
	$row5=mysql_query("select ogcreate, record_payout_type, total_due_to_client from affiliate_details where afuid='".addslashes(trim($rs4[0]))."' and status='1'");
	while ($rs5=mysql_fetch_row($row5))
		{
		if (date("mY", $rs5[0])==date("mY"))
			{
			if ($rs5[1]==1)
				{
				@$total_onetimers+=$rs5[2];
				$ot++;
				}
			else if ($rs5[1]==2)
				{
				$total_monthly+=$rs5[2];
				$mt++;
				}

			$rt++;
			}
		}

	if ($ot==1)
		{
		$total_onetimers=0;
		}
	if ($mt==1)
		{
		$total_monthly=0;
		}

	$rs6=mysql_fetch_row(mysql_query("select sum(total_due_to_client) from affiliate_details where afuid='".addslashes(trim($rs4[0]))."' and status='1'"));

	$useremail=mysql_fetch_row(mysql_query("select email from user where uid='".addslashes(trim($uid))."'"));

	// DEFINE VARs
	$generate_date=date("m/d/Y h:i:s a");
	$reporting_month=date("F");
	$referrals_this_month=$rt;
	$affiliate_balance=$rs6[0];

	// ATTRIBUTES AVAILABLE
	// {{generate_date}}
	// {{reporting_month}}
	// {{referrals_this_month}}
	// {{affiliate_balance}}
	// {{total_monthly}}
	// {{total_onetimers}}

	if ($affiliate_balance!=0)
		{
		$affiliate_balance=$currency.$affiliate_balance.$currency_type;
		}

	if ($total_monthly!=0)
		{
		$total_monthly=$currency.$total_monthly.$currency_type;
		}

	if ($total_onetimers!=0)
		{
		$total_onetimers=$currency.$total_onetimers.$currency_type;
		}

	// parse out subject
	// this way is inefficient, but works on all OS's
	$subject=stripslashes(trim($rs[0]));
	$subject=str_replace("{{generate_date}}", $generate_date, $subject);
	$subject=str_replace("{{reporting_month}}", $reporting_month, $subject);
	$subject=str_replace("{{referrals_this_month}}", $referrals_this_month, $subject);
	$subject=str_replace("{{affiliate_balance}}", $affiliate_balance, $subject);
	$subject=str_replace("{{total_monthly}}", $total_monthly, $subject);
	$subject=str_replace("{{total_onetimers}}", $total_onetimers, $subject);

	// parse out subject
	// this way is inefficient, but works on all OS's
	$message=stripslashes(trim($rs[1]));
	$message=str_replace("{{generate_date}}", $generate_date, $message);
	$message=str_replace("{{reporting_month}}", $reporting_month, $message);
	$message=str_replace("{{referrals_this_month}}", $referrals_this_month, $message);
	$message=str_replace("{{affiliate_balance}}", $affiliate_balance, $message);
	$message=str_replace("{{total_monthly}}", $total_monthly, $message);
	$message=str_replace("{{total_onetimers}}", $total_onetimers, $message);

	mail($useremail[0], $subject, $message, "From: ".(($default_email!="")?"".$default_email."":"".$email_admin."")."\nReply-To: ".$email_admin."\nX-Mailer: PHP/" . phpversion());
	}

// admin monthly report
function admin_monthly_report($email_admin, $currency, $currency_type)
	{
	// PULL IN TEMPLATE
	$rs=mysql_fetch_row(mysql_query("select subject, message, default_email from email_templates where emid='19'"));
	$default_email=stripslashes(trim($rs[2]));

	$new_affiliates_for_reporting_month=0;
	# $row0=mysql_query("select afuid, UNIX_TIMESTAMP(ogcreate), uid from affiliate_user");
	$row0=mysql_query("select afuid, ogcreate, uid from affiliate_user");
	while ($rs0=mysql_fetch_row($row0))
		{
		// new affiliate count
		if (date("mY", $rs0[1])==date("mY"))	{ $new_affiliates_for_reporting_month++; }

		// get affiliate name
		$rs1=mysql_fetch_row(mysql_query("select first_name, last_name from user where uid='".addslashes(trim($rs0[2]))."'"));
		
		// get count of all referred
		$rs2=mysql_fetch_row(mysql_query("select count(*) from affiliate_details where afuid='".addslashes(trim($rs0[0]))."' and status='1'"));
		
		// get sum of all referred
		$rs3=mysql_fetch_row(mysql_query("select SUM(total_due_to_client) from affiliate_details where afuid='".addslashes(trim($rs0[0]))."' and status='1'"));
		
		// build summary of all affilates
		@$summary_of_all_affiliates.="".(($new_affiliates_for_reporting_month==0)?"1. ":"".$new_affiliates_for_reporting_month.". ")." ".$rs1[0]." ".$rs1[1].", [".$rs0[0]."], ".$rs2[0]." Total Referrals, ".$currency."".$rs3[0]."".$currency_type."\n";
		
		// build the details list
		@$detail_listing_of_affiliate_referrals.="[".$rs0[0]."], ".$rs1[0]." ".$rs1[1]."\n";
		
		$rct=0;
		$row4=mysql_query("select refered_uid, oid, package_name from affiliate_details where afuid='".addslashes(trim($rs0[0]))."'");
		while ($rs4=mysql_fetch_row($row4))
			{
			// pull in client data
			$rs5=mysql_fetch_row(mysql_query("select user.first_name, user.last_name, hosting_order.domain_name from user, hosting_order where hosting_order.oid='".addslashes(trim($rs4[1]))."' and hosting_order.uid=user.uid order by hosting_order.oid asc limit 0, 1"));
			
			// build the list
			@$detail_listing_of_affiliate_referrals.="--".(($rct==0)?"1":"".$rct."").". http://".$rs5[2].", ".$rs5[0]." ".$rs5[1].", ".$rs4[2]."\n";
			$rct++;
			}
		
		$new_referrals_for_reporting_month=$rct;
		}

	// DEFINE VARs
	$generate_date=date("m/d/Y h:i:s a");
	$reporting_month=date("F");

	// ATTRIBUTES AVAILABLE
	// {{generate_date}}
	// {{reporting_month}}
	// {{new_affiliates_for_reporting_month}}
	// {{new_referrals_for_reporting_month}}
	// {{summary_of_all_affiliates}}
	// {{detail_listing_of_affiliate_referrals}}


	// parse out subject
	// this way is inefficient, but works on all OS's
	$subject=stripslashes(trim($rs[0]));
	$subject=str_replace("{{generate_date}}", $generate_date, $subject);
	$subject=str_replace("{{reporting_month}}", $reporting_month, $subject);
	$subject=str_replace("{{new_affiliates_for_reporting_month}}", $new_affiliates_for_reporting_month, $subject);
	$subject=str_replace("{{new_referrals_for_reporting_month}}", $new_referrals_for_reporting_month, $subject);
	$subject=str_replace("{{summary_of_all_affiliates}}", $summary_of_all_affiliates, $subject);
	$subject=str_replace("{{detail_listing_of_affiliate_referrals}}", $detail_listing_of_affiliate_referrals, $subject);

	// parse out subject
	// this way is inefficient, but works on all OS's
	$message=stripslashes(trim($rs[1]));
	$message=str_replace("{{generate_date}}", $generate_date, $message);
	$message=str_replace("{{reporting_month}}", $reporting_month, $message);
	$message=str_replace("{{new_affiliates_for_reporting_month}}", $new_affiliates_for_reporting_month, $message);
	$message=str_replace("{{new_referrals_for_reporting_month}}", $new_referrals_for_reporting_month, $message);
	$message=str_replace("{{summary_of_all_affiliates}}", $summary_of_all_affiliates, $message);
	$message=str_replace("{{detail_listing_of_affiliate_referrals}}", $detail_listing_of_affiliate_referrals, $message);
	
	#echo nl2br($subject)."<br><br>";
	#echo nl2br($message)."<br><br>";
	#die();
	mail($email_admin, $subject, $message, "From: ".(($default_email!="")?"".$default_email."":"".$email_admin."")."\nReply-To: ".$email_admin."\nX-Mailer: PHP/" . phpversion());
	}

// update the history table
function update_affiliate_history_table($below_public)
	{
	$row0=mysql_query("select afuid from affiliate_user");
	while ($rs0=mysql_fetch_row($row0))
		{
		$afuid=$rs0[0];

		$a=1;
		# $row=mysql_query("select UNIX_TIMESTAMP(ogcreate), total_due_to_client from affiliate_details where afuid='".addslashes(trim($rs0[0]))."' and status='1'");
		$row=mysql_query("select ogcreate, total_due_to_client from affiliate_details where afuid='".addslashes(trim($rs0[0]))."' and status='1'");
		while ($rs=mysql_fetch_row($row))
			{
			if (date("mY", $rs[0])==date("mY")&&$a==1)
				{
				$owed_to_client=$rs[1];
				
				$a++;
				}
			else
				{
				$owed_to_client+=$rs[1];
				}
			}

		// if no new sales for month
		if ($a==1) {$owed_to_client=0;}

		// read in last ran and afhid if applicable
		list($last_ran, $afhid)=split("[|]", read_affiliate_period_log($below_public, $afuid));

		if ($afhid==0)
			{
			// Insert the a record for this month
			// write the log file with good data
			mysql_query("insert into affiliate_history set afuid='".addslashes(trim($rs0[0]))."', period_of='".time."', owed_to_client='".addslashes(sprintf("%01.2f", $owed_to_client))."', status='0'");

			$afhid=mysql_insert_id();

			// update the log
			write_new_affiliate_log($below_public, $afhid, $afuid);
			}
		else
			{
			if (date("mY", $last_ran)==date("mY"))
				{
				// update the record
				mysql_query("update affiliate_history set period_of='".time."', owed_to_client='".addslashes(sprintf("%01.2f", $owed_to_client))."', status='0' where afhid='".addslashes(trim($afhid))."'");
				}
			else
				{
				// Insert the a record for this month
				// write the log file with good data
				mysql_query("insert into affiliate_history set afuid='".addslashes(trim($rs0[0]))."', period_of='".time."', owed_to_client='".addslashes(sprintf("%01.2f", $owed_to_client))."', status='0'");

				$afhid=mysql_insert_id();

				// update the log
				write_new_affiliate_log($below_public, $afhid, $afuid);
				}
			}
		
		// let the server rest!
		usleep(500);
		
		// start over with next client
		unset($a);
		}
	}

?>