<?php
@session_start();
include(dirname(__FILE__) . "/../../adbcon.php");

/* Get Max & Min Dates **********************************/
$max_years_deep = 1;
$current_year = intval(date("Y"));
$current_month = intval(date("m"));
$current_day = intval(date("d"));


$prev_year = $current_year - $max_years_deep;
$min_date_timestamp = strtotime("$prev_year-01-01");
$min_date = date("Y-m-d", $min_date_timestamp);

$prev_month = 1;
$prev_day = 1;

$other = 0;

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

function ip2long_($ip) {
	$ip = explode(".",$ip);
	if (!is_numeric(join(NULL,$ip)) or count($ip) != 4) {return false;}
	else {return $ip[3]+256*$ip[2]+256*256*$ip[1]+256*256*256*$ip[0];}
}
$decimal = 2;
$memberid = "";

if(isset($_REQUEST)) {
	$member_id = isset($_REQUEST['member_id']) ? intval($_REQUEST['member_id']) : 0;
	$domain_id = isset($_REQUEST['domain_id']) ? intval($_REQUEST['domain_id']) : 0;
	$selection = isset($_REQUEST['selection']) ? trim($_REQUEST['selection']) : '';
	$r1 = isset($_REQUEST['r1']) ? trim($_REQUEST['r1']) : 'default';
	$from_day = isset($_REQUEST['from_day']) ? trim($_REQUEST['from_day']) : '';
	$from_month = isset($_REQUEST['from_month']) ? trim($_REQUEST['from_month']) : '';
	$from_year = isset($_REQUEST['from_year']) ? trim($_REQUEST['from_year']) : '';
	$to_day = isset($_REQUEST['to_day']) ? trim($_REQUEST['to_day']) : '';
	$to_month = isset($_REQUEST['to_month']) ? trim($_REQUEST['to_month']) : '';
	$to_year = isset($_REQUEST['to_year']) ? trim($_REQUEST['to_year']) : '';
	$type = isset($_REQUEST['type']) ? trim($_REQUEST['type']) : 'adv';
}


$domain_id = isset($_REQUEST['domain_id']) ? intval($_REQUEST['domain_id']) : 0;

$type = isset($_REQUEST['type']) ? trim(mysql_real_escape_string($_REQUEST['type'])) : 'adv';
if(isset($_GET['member_id']) && intval($_GET['member_id'])>0) {
	$memberid = $_GET['member_id'];
	$querymembers = "SELECT * FROM members WHERE member_id='$memberid'";
	$resultmembers = mysql_query ($querymembers);
	$linemembers=mysql_fetch_array($resultmembers);
}
else {
	if(isset($_SESSION["member_id"])){
		$memberid=$_SESSION["member_id"];
		$querymembers = "SELECT * FROM members WHERE member_id='$memberid'";
		$resultmembers = mysql_query ($querymembers);
		$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);
		$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);
		$linebanner=mysql_fetch_array($resultbanner);
		$memberid=$linebanner["member_id"];
	}
	else{
		echo "Please define either a member or an advertisment or a banner";
	}
}
?>

<div class="box box-default box-solid">
    <div class="box-header with-border">
        <strong><?php echo $linemembers["companyname"]; ?></strong>
    </div>
    <div class="box-body">
        Country Statistics in <b class="text-info">
        <?php
        // Set the default selection parameters
        $fromdate="$from_year-$from_month-$from_day";
        $todate="$to_year-$to_month-$to_day";
        $wherequery=" AND added_on>='$fromdate' AND added_on<='$todate'";
        //extract the domainname from the id
        $linedomain = mysql_fetch_array(mysql_query("SELECT domainname FROM domaincategories WHERE catdom_id='$domain_id'"));
        echo $linedomain["domainname"];
        ?>
        </b>
    </div>
</div>
<?php
//Build up the query for advertisments
$country = array();
$noofips_adv = 0;
$NoOfAdvs = 0;
if($type == "adv") {
	//$query_ips_adv="SELECT * FROM adverts_stats_clicks WHERE domain_id=$domain_id AND click_on LIKE 'www%' AND click_from!='' and click_from not like 'http%' and ipfrom REGEXP '[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}'";
	$query_ips_adv="SELECT * FROM adverts_stats_clicks WHERE domain_id='$domain_id' AND click_on LIKE 'www%' AND click_from!='' AND ipfrom REGEXP '[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}'";
	//echo "<br/>$query_ips_adv";
	//Search for the advertisments which are bound with the member
	$queryadv="SELECT * FROM advertisment WHERE member_id='$memberid'";
	//echo "<br/>$queryadv<br/>";
	$resultadv=mysql_query($queryadv);
	$NoOfAdvs=mysql_num_rows($resultadv);
	if($NoOfAdvs>0){
		$query_ips_adv .= " AND (";	
		$i=1;
		while($lineadv=mysql_fetch_assoc($resultadv)){
			$query_ips_adv .= " advertisment_id = '{$lineadv['advertisment_id']}'";
			//$advert_ids[]=$lineadv[advertisment_id];
			if($i<$NoOfAdvs){ $query_ips_adv .= " OR ";}
			$i++;
		}
		$query_ips_adv .= ")";
		$query_ips_adv .=$wherequery;
		$query_ips_adv .="";
		
		//echo "<br/>".$query_ips_adv;
		
		$result_ips_adv=mysql_query($query_ips_adv) or die(mysql_error());
		$noofips_adv=mysql_num_rows($result_ips_adv);
	
	}
}

$noofips_ban = 0;
$NoOfBans = 0;
if($type == "ban") {
	//Build up the query for banners
	//$query_ips_ban="SELECT * FROM banner_stats_clicks WHERE domain_id=$domain_id AND ipfrom REGEXP '[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}' AND location!='' ";
	$query_ips_ban="SELECT * FROM banner_stats_clicks WHERE domain_id='$domain_id' AND location in ('left', 'right', 'middle') AND ipfrom REGEXP '[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}'";
	//Search for the advertisments which are bound with the member
	$queryadv="SELECT * FROM banner WHERE member_id='$memberid'";
	$resultadv=mysql_query($queryadv);
	$NoOfBans=mysql_num_rows($resultadv);
	if($NoOfBans>0){
		$query_ips_ban .= " AND (";	
		$i=1;
		while($lineadv=mysql_fetch_assoc($resultadv)){
			$query_ips_ban .= " banner_id = '{$lineadv['module_id']}'";
			//$advert_ids[]=$lineadv[advertisment_id];
			if($i<$NoOfBans){ $query_ips_ban .= " OR ";}
			$i++;
		}
		$query_ips_ban .= ")";
		$query_ips_ban .=$wherequery;
		$query_ips_ban .="";
		
		//echo '<br>' . $query_ips_ban . '<br>';
		
		$result_ips_ban=mysql_query($query_ips_ban) or die(mysql_error());
		$noofips_ban= mysql_num_rows($result_ips_ban);
	}
}


if($NoOfAdvs>0){
	while($line_ips_adv=mysql_fetch_assoc($result_ips_adv)){
		$ip_long=ip2long_($line_ips_adv["ipfrom"]);?>
	    <?php 
		//$query_country="SELECT Country FROM ip2country1 WHERE $ip_long between IPfrom AND IPto";
		$query_country="SELECT country_name as Country FROM ip2location_db1_ipv4 WHERE ip_from <= $ip_long ORDER BY ip_from DESC limit 1";
		$result_country=@mysql_query($query_country);
		if($result_country && mysql_num_rows($result_country)>0){
			$line_country=mysql_fetch_assoc($result_country);
			$key = array_search($line_country["Country"],$country);
			if($key>-1){
				$country_count[$key]++;
			}
			else{
				$country[]=$line_country["Country"];
				$country_count[]=1;
			}
		}
		else{
			if($other>0){
				$other++;
			}else{
				$other=1;
			}
		}
	
	}
}

if($NoOfBans>0){
			while($line_ips_ban=mysql_fetch_assoc($result_ips_ban)){
				$ip_long=ip2long_($line_ips_ban["ipfrom"]);?>
                <?php 
				//$query_country="SELECT Country FROM ip2country1 WHERE IPfrom<=$ip_long AND IPto>=$ip_long";
                $query_country="SELECT country_name as Country FROM ip2location_db1_ipv4 WHERE ip_from <= $ip_long ORDER BY ip_from DESC limit 1";
				$result_country = @mysql_query($query_country);
				if($result_country && mysql_num_rows($result_country)>0){
					$line_country=mysql_fetch_assoc($result_country);
					$key=array_search($line_country["Country"],$country);
					if($key>-1){
						$country_count[$key]++;
					}else{
						$country[]=$line_country["Country"];
						$country_count[]=1;
					}
				}
				else{
					if($other>0){
						$other++;
					}else{
						$other=1;
					}
				
				}
			}
}
if(is_array($country_count)){
	arsort($country_count);
}

?>

<table class="table table-bordered">
    <thead>
    <tr>
        <th colspan="3">Total Number Of Clicks: <?php echo $total_noofips = $noofips_adv + $noofips_ban; ?></th>
    </tr>
    </thead>
    <tbody>
        <tr>
            <th>Country</th>
            <th class="text-right">Clicks</th>
            <th class="text-right">Percentage</th>
        </tr>
        <?php if (is_array($country_count)) {
            foreach ($country_count as $key => $val) { ?>
                <tr>
                    <td><?php echo "$country[$key]"; ?></td>
                    <td class="text-right"><?php echo $val; ?></td>
                    <td class="text-right"><?php echo round($val / $total_noofips * 100, 2); ?>%</td>
                </tr>
            <?php }
        }
        if($other > 0) {
            ?>
            <tr>
                <td>Other</td>
                <td class="text-right"><?php echo $other; ?></td>
                <td class="text-right"><?php echo round($other / $total_noofips * 100, 2); ?>%</td>
            </tr>
            <?php
        }
        ?>
    </tbody>
    <tfoot>
    <tr>
        <td>Total</td>
        <td class="text-right"><?=$total_noofips?></td>
        <td class="text-right">100%</td>
    </tr>
    </tfoot>
</table>