<style type="text/css">
	div.success { background-color:#E4FFDF; color: #277F17; border: 1px solid #197F07; padding: 10px; font: 12px Arial; }
	div.error { background-color:#FFEFF0; color: #990000; border: 1px solid #990000; padding: 10px; font: 12px Arial; }
	div.period { color: #277F17; padding: 5px; font: 12px Arial; } 
</style>

<?php
function datediff($date1, $date2) { 
	$difference = strtotime($date2) - strtotime($date1);
	return $difference/60/60/24; //Calculates Days Old
}


class stopwatch {
	var $round = 3;

	function stopwatch() {
		$this->start = microtime();
	}

	function now() {
		$start = $this->math($this->start);
		$now = $this->math();
		return round($now - $start, $this->round);
	}
	function math ($time = FALSE) {
		if ( !$time ) $time = microtime();
		$temp = explode(' ', $time);
		return $temp[0] + $temp[1];
	}
}

$stopwatch = new stopwatch();
//print $stopwatch->now();

$show_stats = true;

$memberid = "0";
if(isset($_SESSION['member_id']) && $_SESSION['member_id'] >0){
	$memberid = $_SESSION['member_id'];
	$querymembers = "SELECT * FROM members WHERE member_id='$memberid'";
	$resultmembers = mysql_query ($querymembers) or die("<br><b>".$querymembers."</b><br>".mysql_error());
	$linemembers = mysql_fetch_array($resultmembers);
}
elseif(isset($advertisment_id) && $advertisment_id>0){
	$queryadvertisment = "SELECT * FROM advertisment WHERE advertisment_id='$advertisment_id'";
	$resultadvertisment = mysql_query ($queryadvertisment) or die("<br><b>".$queryadvertisment."</b><br>".mysql_error());
	$lineadvertisment=mysql_fetch_array($resultadvertisment);
	$memberid=$lineadvertisment["member_id"];
}
elseif(isset($banner_id) && $banner_id>0){
	$querybanner = "SELECT * FROM banner WHERE module_id='$banner_id'";
	$resultbanner = mysql_query ($querybanner) or die("<br><b>".$querybanner."</b><br>".mysql_error());
	$linebanner=mysql_fetch_array($resultbanner);
	$memberid=$linebanner["member_id"];
}
else{
	$show_stats = false;
	print "<br/>";
	print '<div class="success">';
	print '<b>You have been logged out!</b><br/>';
	print 'In order to better protect our members accounts we have put in place a mecanism to expire the browser sessions after a predefined amount of time since no website interraction has been detected. 
	<br/><br/>This will ensure that if you forget to logout or leave your computer unattended, no-one can use your account and act on your behalf.
	<br/><br/>Kindly use the login form to <b>Login</b> again.
	';
	print '</div>';
	//echo "Please define either a member, an advertisment or a banner";
	//exit;
}

function getTimestamp($date) {
	if(!empty($date)) {
		$parts = explode("/", $date);
		$timestamp = mktime(12, 0, 0 , intval($parts[1]), intval($parts[0]), intval($parts[2]));
		return $timestamp;
	}
	return date("Y-m-d H:i:s");
}

//print "<br/>Ready to get into content at: ".$stopwatch->now();

if($show_stats) {
?>


<table width="100%" border="0" cellspacing="0" cellpadding="0">
	<tr>
		<td>
	
	
<?php
// Set the default selection parameters
if(!isset($_REQUEST['r1']) || $_REQUEST['r1']!="FDTD") $r1 = "default";
if(!isset($_REQUEST['selection'])){
	$_REQUEST['selection'] = "ALL";
	$selection = $_REQUEST['selection'];
}
else {
	$selection = $_REQUEST['selection'];
}

if(isset($_REQUEST['r1']) && $_REQUEST['r1']!="") $r1 = $_REQUEST['r1'];
// Get the where clause from selection

if($r1=="FDTD"){
	$fromdate 	= date("Y-m-d 00:00:00", getTimestamp($_REQUEST['from_date']));
	$todate		= date("Y-m-d 23:59:59", getTimestamp($_REQUEST['to_date']));
	$wherequery=" AND added_on >= '$fromdate' AND added_on <= '$todate' ";
}
else{
	$selection = $_REQUEST['selection'];
	if($selection=="CM"){
		$fromdate 	= date("Y-m-d 00:00:00", getTimestamp("01/".date("m/Y")));
		$todate		= date("Y-m-d H:i:s");
		$wherequery=" AND added_on >= '$fromdate' AND added_on <= '$todate' ";
	}
	elseif($selection=="LM"){
		$cm = intval(date("m"));
		$last_month = ($cm > 1) ? ( ($cm > 10) ? ($cm-1): "0".($cm-1) ) : 12;
		$last_month_year = (intval($last_month) == 12) ? (intval(date("Y"))-1):intval(date("Y"));
		$temp_last_month = mktime(12, 0, 0, intval($last_month), 1, intval($last_month_year));
		$last_day_of_last_month = date("t", $temp_last_month);
		
		$fromdate 	= date("Y-m-d 00:00:00", getTimestamp("01/$last_month/$last_month_year"));
		$todate		= date("Y-m-d 00:00:00", getTimestamp("$last_day_of_last_month/$last_month/$last_month_year"));
		$wherequery=" AND added_on >= '$fromdate' AND added_on <= '$todate' ";
	}
	elseif($selection=="Y"){
		$today = intval(date('d'));
		if($today == 1) {
			$cm = intval(date("m"));
			$last_month = ($cm > 1) ? ( ($cm > 10) ? ($cm-1): "0".($cm-1) ) : 12;
			$last_month_year = (intval($last_month) == 12) ? (intval(date("Y"))-1):intval(date("Y"));
			$temp_last_month = mktime(12, 0, 0, intval($last_month), 1, intval($last_month_year));
			$last_day_of_last_month = date("t", $temp_last_month);
		}
		else {
			$last_month = date("m");
			$last_month_year = date("Y");
			$last_day_of_last_month = $today - 1;
			$last_day_of_last_month = ($last_day_of_last_month >= 10) ? $last_day_of_last_month : "0".$last_day_of_last_month;
		}
		
		$fromdate 	= date("Y-m-d 00:00:00", getTimestamp("$last_day_of_last_month/$last_month/$last_month_year"));
		$todate		= date("Y-m-d 00:00:00");
		$wherequery=" AND added_on >= '$fromdate' AND added_on <= '$todate' ";
	}
	else{
		$fromdate 	= date("Y-m-d");
		$todate 	= date("Y-m-d");
		$wherequery = "";
	}
}

if(!isset($wherequery) || $wherequery == "") {
	$today=date("Y-m-d H:i:s");
	$wherequery .=" AND added_on < '$today' AND added_on > '2005-10-16 23:59:59'";
}



?>


<table width="99%" align="center" border="0" cellspacing="0" cellpadding="0" class="stats_period">
	<tr>
		<th width="32%" align="left" scope="row" valign="top">
			<strong class="tdheadername"><?=$linemembers["companyname"]; ?></strong>
			<br/>
			<span class="small">Statistics of &nbsp;<b>BANNERS</b> in all portals.</span>
		</th>
		<td width="68%" rowspan="2" align="right">
			<form action="" method="POST" enctype="application/x-www-form-urlencoded" name="form1" id="form1">
			<table border="0" cellspacing="0" cellpadding="2">
				<tr>
					<td class="left">
						<input name="r1" type="radio" value="default" <?php print ($r1 == "default")? ' checked="checked" ':''; ?>>
					</td>
					<td align="left" class="left">
						<select name="selection" id="selection">
							<option value="All" <?php if(isset($_REQUEST['selection']) && $_REQUEST['selection'] == "ALL")  echo ' selected="selected" ';?>>ALL Time</option>
							<option value="Y"  <?php if(isset($_REQUEST['selection']) && $_REQUEST['selection'] == "Y")  echo ' selected="selected" ';?>>Yesterday</option>
							<option value="CM" <?php if(isset($_REQUEST['selection']) && $_REQUEST['selection'] == "CM") echo ' selected="selected" ';?>>Current Month</option>
							<option value="LM" <?php if(isset($_REQUEST['selection']) && $_REQUEST['selection'] == "LM") echo ' selected="selected" ';?>>Last Month</option>
						</select>
						<input name="memberid" type="hidden" id="memberid" value="<?php print $memberid;?>">
					</td>
					<td class="left">&nbsp;</td>
					<td class="left">&nbsp;</td>
				</tr>
                <tr>
                	<td nowrap="nowrap" class="left">
                		<input name="r1" type="radio" value="FDTD"  <?php print ($r1 == "FDTD")? ' checked="checked" ':''; ?>>
                    </td>
                    <td nowrap="nowrap" class="left">
						From date: <input type="text" name="from_date" id="from_date" size="8" value="<?php print date("d/m/Y", strtotime($fromdate)); ?>" maxlength="10"/>
						To date: <input type="text" name="to_date" id="to_date" size="8" value="<?php print date("d/m/Y", strtotime($todate)); ?>" maxlength="10"/>
                    </td>
                    <td nowrap="nowrap" class="left">&nbsp;</td>
					
					<td nowrap="nowrap" class="left">
						<input type="submit" name="Submit" value="Go" class="form_submit" />
						<input type="hidden" name="module_page" value="my_stats"/>
						<input type="hidden" name="stats_step" value="my_stats_banners"/>
					</td>
				</tr>
			</table>
			</form>
		</td>
	</tr>
</table>
&nbsp;&nbsp;&nbsp;<b>Note:</b>&nbsp;Statistics recording started on the 17th of October 2005<br/><br/>

<?php 
	$query="SELECT *, SUM(views), MIN(added_on) FROM banner_stats_views_maintained WHERE 1";
	$query .= $wherequery;
	
	$banners = array();
	
	$queryadv = "SELECT * FROM banner WHERE member_id='$memberid'";
 	$resultadv = mysql_query($queryadv);
	$NoOfAdvs=mysql_num_rows($resultadv);
	if($NoOfAdvs>0){
		while($lineadv=mysql_fetch_assoc($resultadv)){
			$banners[] = $lineadv['module_id'];
		}
		
		$ban_ids = implode(",", $banners);
		
		$query .= " AND banner_id in ($ban_ids) ";
		$query .=" GROUP BY domain_id";
		$query .=" ORDER BY views DESC";
		$result = mysql_query($query) or die (mysql_error());
 


$period_string = "";
		
if($r1 == "FDTD") {
	$period_string = " from <b>".date('F d, Y', strtotime($fromdate)) . "</b> to <b>" . date('F d, Y', strtotime($todate))."</b>";
}
else {
	if($selection == "ALL") {
		$period_string = " ALL TIME ";
	}
	if($selection == "CM") {
		$period_string = " current month";
	}
	if($selection == "LM") {
		$period_string = " last month";
	}
	if($selection == "Y") {
		$period_string = " yesterday";
	}
}

?>

<div class="period">
	<b>Display Period: </b> <?php echo $period_string; ?>
</div>

<table width="99%" border="0" align="center" cellpadding="3" cellspacing="0" bordercolor="#BEBEBE" class="tableresults">
	<tr>
		<td colspan="6" class="tdshowall">
			<strong>&nbsp; Statistics of <?php print $linemembers["companyname"]; ?> "Banners" in All Portals </strong>
		</td>
	</tr>
	<tr>
		<th align="left" nowrap="nowrap" class="tdsort" scope="row">Portal name</th>
		<td nowrap="nowrap" class="tdsort">First Impr. </td>
		<td align="left" nowrap="nowrap" class="tdsort"><?php $sumviews=0; ?>Impressions</td>
		<td nowrap="nowrap" class="tdsort"><?php $totalnoofclicks=0; ?>Clicks</td>
		<td nowrap="nowrap" class="tdsort"><?php $totalctr=0; ?>CTR</td>
		<td nowrap="nowrap" class="tdsort">Current status</td>
	</tr>
	<?php 
	$countdomains=1;
	$linedomain = array();
	$array_logos = array();
	$qdom = "SELECT catdom_id, domainname FROM domaincategories WHERE catdom_id in (select domain_id from banner_bind_history where banner_id in ($ban_ids))";
	$rdom = mysql_query($qdom) or die("<b>$qdom</b><br/>".mysql_error());
	while($ldomain = mysql_fetch_array($rdom)) {
		$array_logos["domain_id"][] = $ldomain['catdom_id'];
		$linedomain[] = array("domain_id"=>$ldomain['catdom_id'], "domainname"=>$ldomain['domainname']);
	}
	
	while( $line = mysql_fetch_assoc($result) ){
		?>
		<tr onmouseover="this.className='stats_hover'" onmouseout="this.className='stats_normal'">
			<td  class="tdsort1stPortal" scope="row">
				<a href="index.php?module_page=my_stats&stats_step=my_stats_analitics&memberid=<?php print $memberid;?>&domain_id=<?php print $line['domain_id'];?>&selection=<?php print $selection;?>&r1=<?php print $r1;?>&from_date=<?php print date("d/m/Y", strtotime($fromdate));?>&to_date=<?php print date("d/m/Y", strtotime($todate));?>&type=ban&back_step=my_stats_banners" class="tdsort1stPortal">
				<?php 
					
					
					$line_domain_name = "Undefined";
        			for($i=0; $i<count($linedomain); $i++) {
        				if($linedomain[$i]['domain_id'] == $line['domain_id']) {
        					$line_domain_name = $linedomain[$i]['domainname'];
        					
        				}
        			}
        			if($line_domain_name == "Undefined") {
        				if($line['domain_id'] == 611) {
        					$line_domain_name = "cyprusnet.com";	
        				}
        				else {
        					//print "<br/>X at: ".$stopwatch->now();
            				$qdom = "SELECT domainname FROM domaincategories WHERE catdom_id='".$line['domain_id']."'";
            				$rdom = mysql_query($qdom) or die("<b>$qdom</b><br/>".mysql_error());
            				if($rdom && mysql_num_rows($rdom)>0) {
            					$rowdom = mysql_fetch_array($rdom);
            					$line_domain_name = $rowdom['domainname']."__";	
            				}
            				//print "<br/>Y at: ".$stopwatch->now();
        				}
        			}
        			
        			print $line_domain_name;
					
				?>
				</a>
				<?php  
					if(is_array($array_logos) && count($array_logos)>0) {
						$key = array_search($line["domain_id"], $array_logos["domain_id"]);
						if($key>-1){
							//echo "ok";
						}
						else{
							$array_logos["domain_id"][]=$line['domain_id'];
						}
					}
					else {
						$array_logos["domain_id"][]=$line['domain_id'];
					}
				?>
			</td>
			<td class="tdsortstats" align="right">
				<?php 
				if($line["MIN(added_on)"]<>""){
					echo date("d-M-Y",strtotime($line["MIN(added_on)"]));
				}
				else{
					echo "N/A";
				}
 
				if($key>-1){
					if(datediff($line["MIN(added_on)"], $array_logos["first_impr"][$key])>0){
						$array_logos["first_impr"][$key]=$line["MIN(added_on)"];
					}
				}
				else{
					$array_logos["first_impr"][]=$line["MIN(added_on)"];
				}
				?>
			</td>
			<td nowrap="nowrap" class="tdsortstats" align="right">
				<?php 
				if($line["SUM(views)"]>0){
					print number_format($line["SUM(views)"], 0, '', ',');
					$sumviews=$sumviews+$line["SUM(views)"];
				}
				else{
					echo "0";
				}
				
				if($key>-1){
					$array_logos["Impres"][$key] = $array_logos["Impres"][$key] + $line["SUM(views)"];
				}
				else{
					$array_logos["Impres"][] = $line["SUM(views)"];
				}
				?>
			</td>
			<td class="tdsortstats" align="right">
				<?php 
				$queryclicks = "SELECT banner_stats_id FROM banner_stats_clicks WHERE domain_id='".$line['domain_id']."'"; 
				if(isset($ban_ids) && strlen($ban_ids)>1){
					$queryclicks .= " AND banner_id in ($ban_ids) ";	
				}
	
				$queryclicks .= $wherequery;
				$queryclicks .=" AND location != ''";
			
				$resultclicks=mysql_query($queryclicks) or die (mysql_error());
				$noofclicks=mysql_num_rows($resultclicks);
				if($noofclicks>0){
					print number_format($noofclicks, 0, '', ',');
					$totalnoofclicks=$totalnoofclicks+$noofclicks;
				}
				else{
					echo $noofclicks=0;
				}
			
				if($key>-1){
					$array_logos["Clicks"][$key]=$array_logos["Clicks"][$key]+$noofclicks;
				}
				else{
					$array_logos["Clicks"][] = $noofclicks;
				}
				?>
			</td>
			<td class="tdsortstats">
				<?php 
				if($noofclicks>0 && $line["SUM(views)"]>0){
					echo $ctr=round($noofclicks/$line["SUM(views)"],3)*100;
					$totalctr=$totalctr+$ctr/100;
				}
				else{
					print "0"; 
				}
				?>%
			</td>
			<td class="tdsortactive">
				<?php  
				$active="no"; 
				reset($banners);
				while (list($keyban, $ban_id) = each($banners)) {
					$queryactive = "SELECT * FROM left_content WHERE catdom_id='".$line['domain_id']."' AND (module_active='yes' OR (active_from <= NOW() AND active_to >= NOW())) AND module_id='$ban_id' AND type='banner'";
					$resultactive = mysql_query($queryactive);
					if(mysql_num_rows($resultactive)>0){
						$active="yes";
					}
				}
				
				if($active==="yes"){
					?>
					Active
					<?php 
				}
				else{
					?>
					<span class="tdsortinactive">Inactive</span>
					<?php 
				}
				
				if($key>-1){
					if($active=="yes"){
						$array_logos["Active"][$key] = "yes";
					}
				}
				else{
					$array_logos["Active"][] = $active;
				}
				?>
			</td>
		</tr>
		<?php $countdomains++;
	}
	?>
	<tr>
		<th class="tdsort1stfooter" scope="row">Total - all <?php print mysql_num_rows($result);?> Portal(s)</th>
		<td nowrap="nowrap" class="tdsortfooter">&nbsp;</td>
		<td nowrap="nowrap" class="tdsortfooter" align="right">
			<?php 
			if($sumviews>0){
				print number_format($sumviews, 0, '', ',');
			}
			else{
				echo $sumviews=0;
			}
			?>
		</td>
		<td class="tdsortfooter" align="right">
			<?php 
			if($totalnoofclicks>0){
				print number_format($totalnoofclicks, 0, '', ',');
			}
			else{
				echo $totalnoofclicks=0;
			}
			?>
		</td>
		<td class="tdsortfooter">
			<?php  
			if($sumviews>0 && $totalnoofclicks>0){
				echo round($totalnoofclicks/$sumviews,3)*100;
			}
			else{
				print "0"; 
			}?>%
			
		</td>
		<td class="tdsortfooter">&nbsp;</td>
	</tr>
</table>

<?php 
	}
	else{
		?>
		You have no banners.
		<?php 
	}
	?>
	</td>
</tr>
</table>

<?php
}
?>