<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
// +----------------------------------------------------------------------+
// | PHP version 4/5                                                      |
// +----------------------------------------------------------------------+
// | This source file is a part of iScripts Multicart                     |
// +----------------------------------------------------------------------+
// | Authors: Programmer<programmer@armia.com>        		              |
// +----------------------------------------------------------------------+
// | Copyrights Armia Systems, Inc and iScripts.com  2005                |
// | All rights reserved                                                  |
// +----------------------------------------------------------------------+
// | This script may not be distributed, sold, given away for free to     |
// | third party, or used as a part of any internet services such as      |
// | webdesign etc.                                                       |
// +----------------------------------------------------------------------+
?>
<?php
include "../includes/config.php";
include "../includes/session.php";
include "../includes/functions.php";

if (get_magic_quotes_gpc()) {
    $_POST = array_map('stripslashes_deep', $_POST);
    $_GET = array_map('stripslashes_deep', $_GET);
    $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
}

if(isset( $_SESSION["sess_adminname"]) and $_SESSION["sess_adminname"]!= ""){
	$adminname = $_SESSION["sess_adminname"];
}else{
	header("Location:login.php");
	exit;
}

if (isset($_GET["aid"]) and $_GET["aid"] != "") {
    $aid = $_GET["aid"];
} else if (isset($_POST["aid"]) and $_POST["aid"] != "") {
    $aid = $_POST["aid"];
} else{
	header("Location:affiliates.php");
    exit;
}



if(isset($_GET["txtSearch"]) and $_GET["txtSearch"]!=""){
	$txtSearch = $_GET["txtSearch"];
	$cmbSearchType = $_GET["cmbSearchType"];
}else if(isset($_POST["txtSearch"]) and $_POST["txtSearch"]!=""){
	$txtSearch = $_POST["txtSearch"];
	$cmbSearchType = $_POST["cmbSearchType"];
}

if(isset($_POST["btnSettleSelected"]))
{
        $chkreg = $_POST["chkreg"];
	
	if(isNotNull($chkreg))
	{
		$itemsselected = true;
		$regids = implode(",",$chkreg );

		$sql=" SELECT sum(referral_charge) AS total,order_id FROM ".$tableprefix."affiliate_registrations ar
	 	WHERE  ar.affiliate_id='".addslashes($aid)."'  AND ( ar.affiliate_payment_id IS NULL) AND ( ar.registration_id IN (".$regids.")) " . $qryopt . "
		GROUP BY ar.affiliate_id
		";
		$res = mysql_query($sql);
		if(mysql_num_rows($res)!=0)
		{
			$row = mysql_fetch_array($res);
			$total = $row["total"];
			
		}
		$txtDateMarkedForPayment = date("m-d-Y",time());
	}
	else
	{
		$itemsselected = false;
		
		$message = SELECT_AFF_REG;;
	}

}else if(isset($_POST["btnSettleNow"])){

	$regids  = $_POST["regids"];
	$total   = $_POST["total"];
	$orderid = $_POST["orderid"];
	if(isNotNull($regids) and (doubleval($total)> 0 )){
		$sql = "INSERT INTO ".$tableprefix."affiliate_payments
			(
			affiliate_id,
			order_id,
			amount_paid,
			date_marked_for_payment
			)
			VALUES
			(
			'".addslashes($aid)."',
			'".addslashes($orderid)."',
			'".addslashes($total)."',
			now()
			)
		 ";
		 $res = mysql_query($sql);
		 $paymentid = mysql_insert_id();
		 $sql = "UPDATE ".$tableprefix."affiliate_registrations SET affiliate_payment_id = '".$paymentid."' WHERE registration_id IN (".$regids.")";
		 mysql_query($sql);
		 $message = PAY_AFF_SUCCESS;
		 
		 
		 /********************** Send email to affiliate ****************************/
		$af_sql = "select first_name,last_name,email from ".$tableprefix."affiliates where affiliate_id =$aid";
		$af_rs  = mysql_query($af_sql);
		$af_rw  = mysql_fetch_array($af_rs);
		$to     = $af_rw["email"];
		
		$subject = MAIL_SETTLE_PAYMENT_TO_SELLER_SUBJECT." ".stripslashes(SITE_NAME);
		
/*-------Email Template Reading Fuction Call--------*/				
		$adminCurrency	= GetAdminCurrency();
		$mailcontent = readEmailTemplate('affliate_settlement_mail');
                $affliate_login_link = SITE_URL.'/affiliates/login.php';
				
		$mailcontent = str_replace('[commission_amount]',$adminCurrency['currency_symbol']." " .$total,$mailcontent);					
		$mailcontent = str_replace('[site_name]',SITE_NAME,$mailcontent);			
		$mailcontent = str_replace('[affiliate_name]',$af_rw["first_name"]." ".$af_rw["last_name"],$mailcontent);	
		$mailcontent = str_replace('[login_link]',$affliate_login_link,$mailcontent);	
		
		
/*---------------Seller Login Url-------------------*/		
		
		
//********************HEADERS*************************
$headers  = "MIME-Version: 1.0" . "\r\n";
$headers .= "Reply-To: ".SITE_NAME."<".SITE_EMAIL.">" . "\r\n";
$headers .= "Return-Path:  ".SITE_NAME."<noreply@".SITE_EMAIL.">" . "\r\n";
$headers .= "From: ".SITE_EMAIL."<".SITE_EMAIL.">" . "\r\n";
$headers .= "Organization: ".SITE_NAME."\r\n"; 
$headers .= "Content-Type: text/html\r\n"; 
//**************************************************** 
		
		$mailcontent = nl2br($mailcontent);
				
		
		$mail_send_details = '<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <title >'.SITE_NAME.'</title>
  <link href="./themes/'. $active_template[4].' rel="stylesheet" type="text/css">
</head>
<body>

<table width="103%" cellspacing="10" cellpadding="0" bgcolor="#EAEAEA">
   <tr>
     <td align="center" valign="top">
         
         <table width="600" border="0" cellpadding="0" cellspacing="0" bordercolor="#EAEAEA" bgcolor="#FFFFFF" class="manage_table">
            <tr>
               <td align="right" >
              </td>
            </tr>
            <tr>
               <td valign="middle" align="left"><table width="100%"  border="0" cellspacing="0" cellpadding="0">
                 <tr>
                   <td  bgcolor="#EAEAEA" > <img src='.SITE_URL.'/banners/'.getSettingsValue('site_logo').' width="125" height="60"/></td>
                 </tr>
               </table></td>
            </tr>
            <tr>
              <td align="center" valign="top"><table width="100%"  border="0" cellspacing="0" cellpadding="10">
                <tr>
                  <td align="left"><p>'.$mailcontent.'</p>
                  </td>
                </tr>
              </table></td>
            </tr>
            <tr>
               <td align="center" bgcolor="#EAEAEA" class="footer">
                  <p>&nbsp;</p>
              </td>
            </tr>
       </table>

     </td>
   </tr>
</table>


</body>
</html>';
                
               
		
                
		$mailsent = @mail($to, $subject, $mail_send_details, $headers);

		
		/********************** End sending email ********************************/

		 
		 
	}else{
		header("Location:settleaffregistrations.php");
    	exit;
	}
}else{
	$itemsselected = false;
}


/*if(isset($_POST['gotoPage']))
{

	header("Location:".$_SERVER['PHP_SELF']."?page=".$_POST['gotoPage']);
	
		
}*/


$qryopt="";
if($txtSearch != ""){
   if($cmbSearchType == "username"){
            $qryopt .= "  AND  ar.user_name like '" . addslashes($txtSearch) . "%'";
   }else if($cmbSearchType == "useremail"){
            $qryopt .= "  AND  ar.user_email like '" . addslashes($txtSearch) . "%'";
   }else if($cmbSearchType == "datereg"){
   		$dt = $txtSearch;
		$arrdt = explode("-",$dt) ;
		$day = $arrdt[1];
		$month = $arrdt[0];
		$year = $arrdt[2];
		$dt = $year."-". $month ."-".$day;
		$qryopt .= "  AND  ar.registration_date like '" . addslashes($dt) . "%'";
   }
}


	$sql = " SELECT ar.*,a.affiliate_name FROM ".$tableprefix."affiliate_registrations ar 
                        INNER JOIN ".$tableprefix."affiliates a ON a.affiliate_id = ar.affiliate_id
	 		 WHERE  ar.affiliate_id='".addslashes($aid)."'  AND  ar.affiliate_payment_id IS NULL " . $qryopt . "
			 order by ar.registration_date DESC ";


	if(!(isset($pagenum)))
	{
		$pagenum = 1;
	} 
	
	$limit = getSettingsValue('npagination_limit');
	
	$page = isset($_GET['page'])? trim($_GET['page']):1;

	
	if(empty($page))
	{
		$page = 1;
	}
	//echo $sql;
	$result=mysql_query($sql) or die(mysql_error());						
	
	$totalrows = mysql_num_rows($result);
	
	$limitvalue = ($page - 1) * $limit;
	
	$query_string = " LIMIT $limitvalue, $limit";
	
	$sql = $sql.$query_string;
	//echo $sql;   
	$rs = mysql_query($sql) or die(mysql_error());

	$numofpages = ceil($totalrows / $limit);

include "../includes/htmltop.php";
?>
<script language="JavaScript" type="text/JavaScript">
function clickSearch()
{
	document.frmFeedbacks.submit();
}
function changeStatus(id){
	var frm = document.frmFeedbacks;
	if(Confirm("<?php echo CONFIRM_CHANGE_STATUS;?>")){
		document.frmFeedbacks.submit();
	}
}
</script>
<body>
<center>
		<div align="left" id="layout">
				<!--header area start -->
<?php

	include_once("../includes/topheader_admin.php")

?>
				<!--header area end -->
				<div align="left" class="main_body">
				<!--main body start -->
<?php
		include_once("../includes/admintopmenu.php")
?>		
					<div align="left" class="content_area">
					<!--content area start -->
					<div align="left" class="page_title"><?php echo SETTLE_PAY_AFF_REG;?> (<?php echo getAffiliateName($aid); ?>)</div>
					<div align="center" class="text_information grey_tr"><?php echo $message?></div>
            		<br>
					<form action="<?php echo $_SERVER["PHP_SELF"];?>" method="post" name="frmFeedbacks">
					<div align="left">
					<input type="hidden" name="aid" value="<?php echo  htmlentities($aid)?>" >
<?php
					if(!$itemsselected)
					{
?>

						<table width="100%" border="0" cellpadding="0" cellspacing="0" class="manage_top">
						<!--
					  <tr>
						<td width="55%" align="left" valign="middle">
						<select name="cmbSearchType" class="textbox">
							<option value="username"  <?php //if($cmbSearchType == "username" ){ echo("selected"); } ?> >User Name</option>
							<option value="useremail"  <?php //if($cmbSearchType == "useremail"){ echo("selected"); } ?> >User Email</option>
							<option value="datereg"  <?php //if($cmbSearchType == "datereg"){ echo("selected"); } ?>>Date Registered</option>
						</select> &nbsp;
						<input type="text" name="txtSearch" size="20" maxlength="50" value="<?php //echo(htmlentities($txtSearch)); ?>">
						<a style="cursor:pointer" onClick="javascript:clickSearch();" class="search_button">Search</a></td>
																							
						</td>
						
						  </tr>
						  -->
					  </table>
						
						</div>
						
						<div align="left">
						
						<table width="100%" border="0" cellpadding="0" cellspacing="0" class="manage_table">
						  <tr>
							<th width="4%" align="center" valign="middle">#</th>
							<th width="10%" align="left" valign="middle"><?php echo AFFILIATE;?></th>
							<th width="13%" align="left" valign="middle"><?php echo USER_NAME;?></th>
							<th width="13%" align="left" valign="middle"><?php echo USER_EMAIL;?></th>
							<th width="15%" align="center" valign="middle"><?php echo DATE_PURCHASE;?></th>
							<th width="20%" align="center" valign="middle"><?php echo AMT_PURCHASE;?> ( <?php echo $adminCurrency['currency_symbol'];?> )</th>
							<th width="17%" align="center" valign="middle"><?php echo REFERRAL_CHARGE;?> ( <?php echo $adminCurrency['currency_symbol'];?> )</th>
							<th width="8%" align="center" valign="middle" colspan="2"><?php echo PAID;?></th>
						  </tr>
<?php
			
			$total = 0;
			if(mysql_num_rows($result) > 0 )
			{
				while($row = mysql_fetch_array($rs))
				{
					$link = "<a class='links' href='affiliateregdetails.php?rid=".$row["registration_id"]."'>";
					$txtRegistrationDate = (isNotNull($row["registration_date"] and ($row["registration_date"]!= "0000-00-00")) ? dateFormat($row["registration_date"],"Y-m-d","m/d/Y") : "");
					$txtUserFullName = $row["user_first_name"];
					$txtUserFullName.= $row["user_last_name"]!=""? " ".$row["user_last_name"]:"";
					$txtPaid = $row["affiliate_payment_id"]!=""? "Y":"N";
					if($txtPaid=="N"){
						$check = "<input class='checkbox' type='checkbox' name='chkreg[]' value='" . $row["registration_id"] . "' > ";
					}else{
						$check = "&nbsp;";
					}

?>
																
															
				<tr>
					<td align='left'><?php echo $check;?></td>
					<td align='left' class=boxalternatecolor2><?php echo $link .htmlentities($row["affiliate_name"])."</a>";?></td>
					<td align='left'><?php echo $link .htmlentities($row["user_name"])."</a>";?>
				    <input name="user_id[]" type="hidden" id="user_id[]" value="<?php echo $row["user_id"]; ?>"></td>
					<td align='left'><?php echo $link .htmlentities($row["user_email"])."</a>";?></td>
					<td align='center'><?php echo $link .htmlentities($txtRegistrationDate)."</a>";?></td>
					<td align='center'><?php echo $link .htmlentities($row["user_totalpurchasedamount"])."</a>";?></td>
					<td align='right' class="boxalternatecolor"><?php echo $link .htmlentities($row["referral_charge"])."</a>";?></td>
					<td align='center'><?php echo $link .htmlentities($txtPaid)."</a>";?></td>
				</tr>
				
<?php
				$i++;
				$total+= $row["referral_charge"];
				}
					}
					else
					{
										
?>										
					<tr>
						<td align="center" valign="middle" colspan="9" class="text_information"><?php echo NO_REC_FOUND;?></td>
					</tr>
										
								
<?php										
				}
				if($page > 1)
				{
					$pageprev = $page-1;
					
					$previous_page = "<a href=".$_SERVER['PHP_SELF']."?page=$pageprev alt='Previous' border='0' class='small_gray_button'>".TEXT_PREV."</a>";
					
				}
																								
																	
				if($page < $numofpages)
				{
					$pagenext = ($page + 1);
					
					$next = "<a href=".$_SERVER['PHP_SELF']."?page=$pagenext alt='Next' border='0' class='small_gray_button'>".TEXT_NEXT."</a>";
					
				}	
?>				

<?php						
				
				if($total>0){?>
				<tr class="whitebg"><td align="right" colspan="6"><b><?php echo TOTAL_TEXT;?></b>&nbsp;</td><td align="right"  class="boxalternatecolor"><font color="RED"><b><?php echo $total; ?></b></font></td><td>&nbsp;</td></tr>
				<?php }
				?>

				
				 </table>
						</td></tr>

				<tr>
						<td colspan="7" align="center">
							<?php
							if(isNotNull($check)){ ?>
								<input type="submit" name="btnSettleSelected" value="<?php echo SETTLE_SELECT_TEXT;?>" class="button" >
							<?php
							}
							?>
							&nbsp;&nbsp;
							<input type="button" name="btnBack" class="button"  value="<?php echo BACK;?>" onClick="window.location.href='editaffiliate.php?affiliateid=<?php echo $aid;?>';" >
						</td>
				</tr>

			</table>
		</td>
	</tr>
</table>
<?php }else{ ?>
<input type="hidden" name="regids" value="<?php echo  htmlentities($regids)?>" >
<input type="hidden" name="total" value="<?php echo  htmlentities($total)?>" >
<input type="hidden" name="orderid" value="<?php echo  htmlentities($row["order_id"])?>" >
<table width="100%"  border="0" cellpadding="0" cellspacing="0"  align="center" class="manage_table">
	<tr><td width="25%" align="left">Total To Pay:</td><td width="3%">&nbsp;</td><td align="left" class="innertextCopy2"><?php echo number_format($total, 2, '.', ''); ?></td></tr>
	<tr><td align="left">Date Marked for Payment:</td><td >&nbsp;</td><td align="left" class="innertextCopy2"><?php echo $txtDateMarkedForPayment; ?></td></tr>
	<tr><td colspan="3" align="center">&nbsp;</td></tr>
	<tr><td colspan="3" align="center"><input type="submit" name="btnSettleNow" value="Settle Now"  class="button" >&nbsp;<input type="button" class="button"  name="btnBack" value="Back" onClick="window.location.href='editaffiliate.php?affiliateid=<?php echo $aid;?>';" ></td></tr>
</table>
<br>

<?php }

?>
<!-- ***************************************************** -->
</td>
</tr>
</table>
						</div>
				<!--content area end-->
				</div>
				</form>
					<div align="left" class="clear_float"><img src="<?php echo $imagefolder;?>/clear.gif" alt="" width="1" height="1" /></div>
				<!--main body end -->
				</div>
<?php
	include "../includes/footer.php";
?>																						