<style type="text/css">
	div.ip_container { height: 240px; overflow-y: auto; padding: 0px; margin:0px; text-align: center; }
	div.error { background-color:#FFEFF0; color: #990000; border: 1px solid #990000; padding: 10px; font: 12px Arial; }
</style>

<?php

/*
echo "<pre>";
print_r($_REQUEST);
echo "</pre>";
*/
?>

<?php
function ip2long_($ip)
{
	$ip = explode(".",$ip);
	if (!is_numeric(join(NULL,$ip)) or count($ip) != 4) {
			return false;
	}
	else {
		return ip2long($ip);
	}
}

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");
}
$type = "adv";
$type_title = "Logos";
if(isset($_REQUEST['type']) && $_REQUEST['type'] == "banner") {
	$type = $_REQUEST['type'];
	$type_title = "Banners";
}
$decimal = 2;
$memberid = "";
$domain_id = $_REQUEST['domain_id'];

$show_stats = true;

$memberid = "0";
if(isset($_SESSION['member_id']) && $_SESSION['member_id'] >0){
	$memberid = $_SESSION['member_id'];
	$querymembers = "SELECT HIGH_PRIORITY * 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 HIGH_PRIORITY * 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 HIGH_PRIORITY * 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;
}


 
// 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'";
}


if($show_stats) {
	?>
	
	<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"><?php print $linemembers["companyname"]; ?></strong>
				<br/>
				<span class="small">
					<?php
					$qdom = "SELECT domainname FROM domaincategories WHERE catdom_id='$domain_id'";
					$rdom = mysql_query($qdom);
					$linedomain = mysql_fetch_array($rdom);
					print "<b>".$linedomain["domainname"] ."</b> IP Addresses";
					print '<br/><b>'.$type_title."</b> analytics";
					?>
				</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_country1"/>
						</td>
					</tr>
				</table>
				</form>
			</td>
		</tr>
	</table>
	&nbsp;&nbsp;&nbsp;&nbsp; <b>* Note:</b> Country statistics have records starting from April 22, 2008  
	<br/>
	<br/>
	
	<?php 
		$NoOfAdvs = 0;
		$NoOfBans = 0;
		$no_of_results = 0;
		$country  = array();
		//Build up the query for advertisments
		if($type == "adv") {
			//adverts_stats_clicks.ipfrom, banner_stats_clicks.ipfrom
			$query_ips_adv = "SELECT country, ipfrom, count(ipfrom) as ip_qty FROM adverts_clicks_from_country WHERE 1=1 ";
			//Search for the advertisments which are bound with the member
			$adverts = array();
			$noofips_adv = 0;
			$queryadv = "SELECT * FROM advertisment WHERE member_id='$memberid'";
			$resultadv = mysql_query($queryadv);
			$NoOfAdvs=mysql_num_rows($resultadv);
			if($NoOfAdvs>0){
				while ($lineadv = mysql_fetch_array($resultadv)) {
					$adverts[] = $lineadv['advertisment_id'];
				}
				
				$adverts_ids = implode(",", $adverts);
					
				$query_ips_adv .= " AND advertisment_id IN ($adverts_ids) ";
				$query_ips_adv .= " AND domain_id='$domain_id' AND click_on LIKE 'www%' ";	
				
				$query_ips_adv .= " AND click_from!=''";
		
				$query_ips_adv .= $wherequery;
				$query_ips_adv .= " group by ipfrom ";
				//print "<br/>".$query_ips_adv;
				
				
				$result_ips_adv = mysql_query($query_ips_adv) or die(mysql_error());
				$noofips_adv = mysql_num_rows($result_ips_adv);
				
			}
			
			$no_of_results = $noofips_adv; 
		}
			//Build up the query for banners
		if($type == "banner") {
			$query_ips_ban = "SELECT country, ipfrom, count(ipfrom) as ip_qty FROM banner_clicks_from_country WHERE ";
			//Search for the advertisments which are bound with the member
			$noofips_ban = 0;
			$banners = array();
			$queryadv = "SELECT * FROM banner WHERE member_id='$memberid'";
			$resultadv = mysql_query($queryadv);
			$NoOfBans = mysql_num_rows($resultadv);
			if($NoOfBans>0){
				while ($lineadv = mysql_fetch_array($resultadv)) {
					$banners[] = $lineadv['module_id'];
				}
				$banners_ids = implode(",", $banners);
				
				$query_ips_ban .= "  banner_id IN ($banners_ids) ";
				$query_ips_ban .= " AND domain_id='$domain_id' ";
					
				$query_ips_ban .= " AND location!='' ";	
				
				$query_ips_ban .=$wherequery;
				$query_ips_ban .= " group by ipfrom ";
				//print "<br/>".$query_ips_ban;
				
				
				$result_ips_ban=mysql_query($query_ips_ban) or die(mysql_error());
				$noofips_ban= mysql_num_rows($result_ips_ban);
				
			}
			
			$no_of_results = $noofips_ban; 
		}

	if($no_of_results > 0) {
	?>
	
		<table width="99%" align="center" border="0" cellpadding="0" cellspacing="0" class="tableresults">
			<tr>
				<th colspan="2" align="left" scope="row" class="tdshowall"> &nbsp;&nbsp;&nbsp; IP Table | 
					<?php echo $no_of_results; ?> Results
				</th>
				<tr>
			        <th align="left" nowrap="nowrap" class="tdsort" scope="row" width="50%">IP Address</th>
			        <th align="left" nowrap="nowrap" class="tdsort" scope="row" width="50%">
			        	<?php 
			        		$country = array(); 
			        		$other=0; 
			        	?>
			        	Country
			        </th>
				</tr>
				<tr>
					<td colspan="2" align="center">
						<div id="ip_container" class="ip_container">
							<table width="100%" align="center" cellpadding="0" cellspacing="0" border="0">
								<?php 	
								$ip_long = false;
								
								if($NoOfAdvs>0){
									while($line_ips_adv = mysql_fetch_array($result_ips_adv)){
										$ip_long = ip2long($line_ips_adv["ipfrom"]);
										if($ip_long === -1 || $ip_long === FALSE) {
											// bad ip
										}
										else {
											?>              
											<tr onmouseover="this.className='classover'" onmouseout="this.className=''">
							                	<th class="tdsort1stPortal" scope="row" width="50%">
							                		<?php 
							                			print $line_ips_adv["ipfrom"];
							                			
							                		?>
							                	</th>
							                	<th class="tdsort1stPortal" scope="row" width="50%">
							                		&nbsp;&nbsp;&nbsp;
							                		<?php
							                			if($line_ips_adv['country'] != "-1") {
							                				echo $line_ips_adv['country'];
							                				$key = array_search($line_ips_adv['country'], $country);
															if($key>-1){
																$country_count[$key] += $line_ips_adv["ip_qty"];
															}
															else{
																$country[] = $line_ips_adv['country'];
																$country_count[] = $line_ips_adv["ip_qty"];
															}
							                			}
							                			else {
							                				echo "Other";
															if($other>0){
																$other += $line_ips_adv["ip_qty"];
															}
															else{
																$other = $line_ips_adv["ip_qty"];
															}
							                			}
													?>
												</th>
											</tr>
											<?php 
										}
									}
								}
								?>
						
								<?php 	
								$ip_long = false;
								if($NoOfBans>0){
									while($line_ips_ban=mysql_fetch_array($result_ips_ban)){
										$ip_long = ip2long($line_ips_ban["ipfrom"]);
										if($ip_long === -1 || $ip_long === FALSE) {
											// bad ip
										}
										else {
											?>              
											<tr onmouseover="this.className='classover'" onmouseout="this.className=''">
												<th class="tdsort1stPortal" scope="row" width="50%">
													<?php 
														print $line_ips_ban["ipfrom"];
														
													?>
												</th>
												<th class="tdsort1stPortal" scope="row" width="50%">
													<?php 
														if($line_ips_ban['country'] != -1) {
															echo $line_ips_ban['country'];
															$key = array_search($line_ips_ban['country'], $country);
															if($key>-1){
																$country_count[$key] += $line_ips_ban["ip_qty"];
															}
															else{
																$country[]=$line_ips_ban['country'];
																$country_count[] = $line_ips_ban["ip_qty"];
															}
														}
														else {
															echo "Other";
															if($other>0){
																$other += $line_ips_ban["ip_qty"];
															}
															else{
																$other = $line_ips_ban["ip_qty"];
															}
														}
													?>
												</th>
											</tr>
											<? 
										}
									}
								}
								?>      
							</table>
						</div>
					</td>
				</tr>
			</table>
			<br/>

		<?php
	}
	else {
		?>
		<div class="error">
			<p>There are no records in the database.</p>
		</div>
		<?php
	}
	
	if(is_array($country_count)){
			
		arsort($country_count);
					
			?>
			
			<table width="99%" cellpadding="0" cellspacing="0" border="0" align="center">
				<tr>
					<td width="50%" align="left">
						<table align="center" width="99%" border="0" cellpadding="3" cellspacing="0" class="tableresults">
							<tr>
								<th colspan="2" align="left" scope="row"class="tdshowall" > Country Statistics</th>
							</tr>
							<tr>
								<th align="left" nowrap="nowrap" class="tdsort" scope="row">Country</th>
								<td nowrap="nowrap" class="tdsort">Percentage</td>
							</tr>
							<?php 
								if(is_array($country_count)){
									$chart_data = array();
									foreach ($country_count as $key => $val) {
										?>
										<tr onmouseover="this.className='classover'" onmouseout="this.className=''">
											<th class="tdsort1stPortal" scope="row">
												<?php  
													print $country[$key]." ($val)";
												?>
											</th>
											<td class="tdsortstats">
												<?php 
													$percent = round($val/$no_of_results*100,2);
													print $percent;
													$country_str = $country[$key];
													if($country_str == "UNITED KINGDOM") $country_str = "UK";
													$chart_data[] = array("country"=>$country_str, "percent"=>$percent);
												?>%
											</td>
										</tr>
										<? 
									}
									//print_r($chart_data);
								}
							?> 
							<tr onmouseover="this.className='classover'" onmouseout="this.className=''">
								<th class="tdsort1stPortal" scope="row">Other (<? echo $other;?>)</th>
								<td class="tdsortstats">
									<?php 
										print round($other/$no_of_results*100,2);
										$chart_data[] = array("country"=>"OTHER", "percent"=>round($other/$no_of_results*100,2));
									?>%
								</td>
							</tr>
							<tr>
								<th class="tdsort1stfooter" scope="row">Total</th>
								<td class="tdsortfooter">100%</td>
							</tr>
						</table>       
					</td>
					<td width="50%" align="center" valign="top">
						<?php
						
						if(isset($chart_data) && is_array($chart_data)) {
							$chd = array();
							$chl = array();
							$perc = array();
							foreach ($chart_data as $key=>$data) {
								$perc[$key] = $data['percent'];
							}
							
							array_multisort($perc, SORT_DESC, $chart_data);
							
							$cnt = 0;
							$remaining = 0;
							foreach ($chart_data as $key=>$data) {
								if ($cnt < 4) {
									$chd[] = $data["percent"];
									$chl[] = $data["country"];
									$remaining += $data["percent"];
								}
								$cnt++;
							}
							
							$chd_str = implode(",", $chd);
							$chl_str = implode("|", $chl);
							
							if(100 - $remaining > 0) {
								$chd_str .= ",".(100 - $remaining);
								$chl_str .= "|*";
							}
							
							$chart = "http://chart.apis.google.com/chart?cht=p3&chd=t:$chd_str&chs=300x100&chl=$chl_str";
							print '<img src="'.$chart.'" border="0"/>';
						}
						else {
							print "&nbsp;";
						}
						
						?>
						
					</td>
				</tr>
			</table>			
			
			
			<?php
			
		}

}
?>