<?php

function getParentDomain($parent_id) {
	$q = "select catdom_id, domainname from domaincategories where catdom_id='$parent_id';";
	$r = @mysql_query($q);
	if($r && mysql_num_rows($r) == 1) {
		$row = mysql_fetch_assoc($r);
		return array("domain_id"=>$row['catdom_id'], "domainname"=>$row['domainname']);
	}
	return false;
}

//echo '<pre>', var_export($_POST, true), '</pre>';

// Breadcrumbs
$breadcrumbs [] = array(
    'link' => 'account/my_account.html',
    'title' => 'My Account'
);

$breadcrumbs [] = array(
    'link' => '',
    'title' => "Stats Overview"
);

$banner_views = 0;
$banner_clicks = 0;

/* 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;

/*********************************************************/

function datediff($date1, $date2) { 
	$difference = strtotime($date2) - strtotime($date1);
	return $difference/60/60/24; //Calculates Days Old
}
$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;
}


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");
}

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

if($show_stats) {
    $date_1 = new DateTime("yesterday");
    $date_2 = new DateTime("yesterday");
    $from_date = (isset($_REQUEST['from_date']))? strtotime($_REQUEST['from_date']) : $date_1->getTimestamp();
    $to_date = (isset($_REQUEST['to_date']))? strtotime($_REQUEST['to_date']) : $date_2->getTimestamp();


	?>
    <form id="stats-form" role="form" class="form-horizontal">
        <div class="form-group">
            <div class="col-xs-10">
                <div id="reportrange-container" class="clearfix">
                    <input type="hidden" name="from_date" id="from_date" value="<?php echo ($from_date > 0) ? date("Y-m-d", $from_date) : date("Y-m-d", $date_1->getTimestamp());?>">
                    <input type="hidden" name="to_date" id="to_date" value="<?php echo ($to_date > 0) ? date("Y-m-d", $to_date) : date("Y-m-d", $date_2->getTimestamp());?>">
                    <div id="reportrange" class="pull-left" style="cursor: pointer; padding: 5px 10px; border: 1px solid #ccc">
                        <i class="glyphicon glyphicon-calendar fa fa-calendar"></i>
                        <span></span> <b class="caret"></b>

                    </div>
                    <button type="submit" name="retrieve" class="btn btn-success btn-sm">Submit</button>
                </div>
            </div>
        </div>
        <input type="hidden" name="module_page" value="account"/>
        <input type="hidden" name="account_url" value="my_stats"/>
        <input type="hidden" name="stats_step" value="my_stats_overview"/>
    </form>
    <div class="alert alert-info hidden">
	    <b>Note:</b>&nbsp;Due to the big amount of statistics records we will allow displaying statistics data for only the current and previous years.
    </div>
		<!-- Start the LOGIC -->
		<?php 
        $fromdate 	= date("Y-m-d", $from_date);
        $todate		= date("Y-m-d", $to_date);
        $wherequery = " AND added_on >= '$fromdate' AND added_on <= '$todate' ";


		// The basic parameters
		$ALL_VIEWS_COUNTER = 0;
		$ALL_CLICKS_COUNTER = 0;
		
		
		// ***** LOGOS
		
		//Build the query
		$query = "SELECT *, SUM(views) as sum_views FROM adverts_stats_views_maintained WHERE view_from!=''";
		
		// Add the where clause
		$query .=$wherequery;
		
		//print "<br/>A at: ".$stopwatch->now();
		
		$queryadv  = "SELECT HIGH_PRIORITY * FROM advertisment WHERE member_id='$memberid'";
		$resultadv = mysql_query($queryadv) or die("<br><b>".$queryadv."</b><br>".mysql_error());
		$NoOfAdvs  = mysql_num_rows($resultadv);
		//print $NoOfAdvs;
		//print "<br/>B at: ".$stopwatch->now();
		### Get the domain names and adverts ids
		$advert_ids = array();   // holds all the advertisment ids of a member
		$domains = array();
		while($lineadv = mysql_fetch_array($resultadv)){
			$advert_ids[] = $lineadv['advertisment_id'];
			$catdomids = explode(";", $lineadv['catdom_id']);
			//print $lineadv['catdom_id'];
			for($i=0; $i<count($catdomids); $i++) {
				if(trim($catdomids[$i]) != "") $domains[] = intval($catdomids[$i]);
			}
		}
		//print "<br/>C at: ".$stopwatch->now();
		//print_r($domains);
		$domains[] = 611;
		$unique_domains = implode(",",array_unique($domains));
		$qdomains = "SELECT HIGH_PRIORITY catdom_id, domainname, parent_id FROM domaincategories WHERE catdom_id IN (".$unique_domains.");";
		//print "Date 2: ".date("H:i:s")."<br>";
		$rdomains = mysql_query($qdomains) or die("<br><b>".$qdomains."</b><br>".mysql_error());
		$linedomain = array();
		while($rowdomain = mysql_fetch_assoc($rdomains)) {
			$dim = array();
			if(intval($rowdomain['parent_id']) == 0) {
				$dim = array("domain_id"=>intval($rowdomain['catdom_id']), "domainname"=>$rowdomain['domainname']);
			}
			else {
				$parent_domain = getParentDomain($rowdomain['parent_id']);
				if($parent_domain && is_array($parent_domain)) {
					$dim = $parent_domain;
				}
			}
			if(count($dim) > 0) $linedomain[] = $dim;
		}
		
		//echo '<pre>', print_r($linedomain), '</pre>';
		//print "<br/>D at: ".$stopwatch->now();
		if($NoOfAdvs > 0){
			$query .= " AND advertisment_id IN (";	
			
			$advertsids = implode(",", $advert_ids);
			
			$query .= $advertsids . ")";
			$query .= " AND domain_id>0 ";
			$query .=" GROUP BY advertisment_id";
					
			//print "<br/>Main: ".$query."<br/>";	
			
			if(isset($_REQUEST['debug'])) {
				echo "<br/>Main: ".$query."<br/>";
			}
			
			//print "Date 3: ".date("H:i:s");
			$logo_views = 0;
			$result = mysql_query($query) or die("<br><b>Error:".$query."</b><br>".mysql_error());
			if($result && mysql_num_rows($result)>0) {
				while ($row = mysql_fetch_array($result)) {
					$sumviews = $row['sum_views'];	
					$logo_views += $sumviews;
					$ALL_VIEWS_COUNTER += $sumviews;
				}
			}
			//print "<br/>E at: ".$stopwatch->now();
			//print "Date 4: ".date("H:i:s")."<br>";
			
			// GET THE CLICKS

			$click_logo_domains = array();
			foreach ($linedomain as $key=>$domain) {
				$click_logo_domains[] = $domain['domain_id'];
			}
			$click_logo_domains_ids = implode(",", array_unique($click_logo_domains));
			
			$queryclicks="SELECT HIGH_PRIORITY count(advert_stats_id) as sum_clicks FROM adverts_stats_clicks WHERE domain_id IN ($click_logo_domains_ids) 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}'"; 
			$queryclicks .= " AND advertisment_id IN (".$advertsids.") ";	
			$queryclicks .= $wherequery;
			$queryclicks .= " group by domain_id ";
 			
			if(isset($_REQUEST['debug'])) {
 				echo "<br/>[<b>$queryclicks</b>]<br/>";
			}
			
			$resultclicks = mysql_query($queryclicks) or die("<br><b>".$queryclicks."</b><br>".mysql_error());
			$logo_clicks = 0;
			while($rowclicks = mysql_fetch_array($resultclicks)) {
				$noofclicks = $rowclicks['sum_clicks'];
				$logo_clicks += $noofclicks;
				//echo "<br/>$noofclicks";
				$ALL_CLICKS_COUNTER += $noofclicks;
			}
			
			//print "<br/>Logo clicks: " . $logo_clicks. '<br/>';
			
			
		}

		
		
		
		// ***** END LOGOS
		
		
		// **** BANNERS
		$query="SELECT *, SUM(views) as sum_views FROM banner_stats_views_maintained WHERE domain_id>0 and ipfrom in ('left', 'right', 'middle') ";
		$query .= $wherequery;
		
		$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_assoc($resultadv)){
				$banners[] = $lineadv['module_id'];
				//$ALL_CLICKS_COUNTER += $line_adv['clicks']; // Get the Banner Clicks
			}
			
			$ban_ids = implode(",", $banners);
			
			//(not used now) get the domain ids associated with the banners
			$qbd = "select domain_id from banner_bind_history where banner_id IN ($ban_ids)";
			$rbd = mysql_query($qbd) or die("<b>$qbd</b>".mysql_error());
			$bdomains = array();
			if($rbd && mysql_num_rows($rbd)>0) {
				while ($rowbd = mysql_fetch_array($rbd)) {
					$bdomains[] = $rowbd['domain_id'];
				}
			}
			
			
			
			$query .= " AND banner_id in ($ban_ids) ";
			$query .=" GROUP BY domain_id";
			
			if(isset($_REQUEST['debug'])) {
				echo "<br>QUERY: $query";
			}
			
			$result = mysql_query($query) or die (mysql_error());
			$banner_views = 0;
			
			$linedomain = 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))";

            if(isset($_REQUEST['debug'])) {
                echo "<br>qdom: $qdom";
            }

			$rdom = mysql_query($qdom) or die("<b>$qdom</b><br/>".mysql_error());
			while($ldomain = mysql_fetch_assoc($rdom)) {
				
				$linedomain[$ldomain['catdom_id']] = array("domain_id"=>$ldomain['catdom_id'], "domainname"=>$ldomain['domainname']);
			}
			
			$ban_domains = array(0);
			
			if($result && mysql_num_rows($result)>0) {
				while ($row = mysql_fetch_array($result)) {
					if(isset($linedomain[$row['domain_id']])) {
						$ban_domains [] = $row['domain_id'];
						$sumviews = $row['sum_views'];	
						$banner_views += $sumviews;
						$ALL_VIEWS_COUNTER += $sumviews;
					}
				}
			}
			
			// Banner Clicks
			$queryclicks = "SELECT a.banner_stats_id FROM (SELECT * FROM banner_stats_clicks WHERE ipfrom REGEXP '[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}' "; 
			if(isset($ban_ids) && strlen($ban_ids)>1){
				$queryclicks .= " AND banner_id in ($ban_ids) ";	
			}

			if(isset($bdomains) && count($bdomains)>0){
				//$bdomains_ids = implode(",", array_unique($bdomains));
				//$queryclicks .= " AND domain_id in ($bdomains_ids) ";	
				//$queryclicks .= " AND domain_id > 0 ";	
			}
			
			$queryclicks .= $wherequery;
			$queryclicks .=" AND location in ('left', 'right', 'middle') ";
			$queryclicks .=") a WHERE a.domain_id in (" . implode(",", $ban_domains) . ") ";
		
			if(isset($_REQUEST['debug'])) {
				echo "<br/>BAN CLICKS: <b>$queryclicks</b><br/>";
			}
			
			$banner_clicks = 0;
			$resultclicks=mysql_query($queryclicks) or die ("$queryclicks | " . mysql_error());
			$noofclicks=mysql_num_rows($resultclicks);
			//print "<br/>Banner clicks: " . $noofclicks. '<br/>';
			$banner_clicks = $noofclicks;
			$ALL_CLICKS_COUNTER += $noofclicks;
			
		}
		// *** END BANNERS
		
		
		/*$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";
			}
		}*/
		
		
		
		//print "All Impressions: " . number_format($ALL_VIEWS_COUNTER, 0, '', ' ');
		//print "<br/>All Clicks: " . number_format($ALL_CLICKS_COUNTER, 0, '', ' ');


		$period_string = "<span>".date('F d, Y', strtotime($fromdate)) . "</span> to <span>" . date('F d, Y', strtotime($todate))."</b>";

		?>           
		<!-- END The Logic   -->
		
		<div class="box box-info">
		    <div class="box-header with-border">
		        <b>Overview Statistics In All Portals</b>
                <br><?php echo $period_string; ?>
            </div>
            <div class="box-body">
                <table class="table">
                    <thead>
                    <tr>
                        <th class="text-left">Type</th>
                        <th class="text-right">Impressions</th>
                        <th class="text-right">Clicks</th>
                        <!--td nowrap="nowrap" class="tdsort" align="right">CTR</td-->
                        <th class="text-center"><i class="fa fa-cogs"></i></th>
                    </tr>
                    </thead>

                    <tbody>
                    <tr>
                        <th scope="row">
                            <a href="account/my_stats.html?stats_step=my_stats_logos&memberid=<?php print $memberid;?>&domain_id=<?php print $domain_id;?>&from_date=<?php print date("Y-m-d", ($from_date));?>&to_date=<?php print date("Y-m-d", ($to_date));?>&type=adv&back_step=my_stats_overview" class="tdsort1stPortal">
                                LOGOS
                            </a>
                        </th>
                        <td class="text-right"><?php echo number_format($logo_views, 0, '', ','); ?></td>
                        <td class="text-right"><?php echo number_format($logo_clicks, 0, '', ','); ?></td>
                        <!--td class="tdsortstats" align="right"><?php echo $ctr = round($logo_clicks/$logo_views,3)*100; ?>%</td-->
                        <td class="text-center">
                            <a href="account/my_stats.html?stats_step=my_stats_logos&memberid=<?php print $memberid;?>&domain_id=<?php print $domain_id;?>&from_date=<?php print date("Y-m-d", ($from_date));?>&to_date=<?php print date("Y-m-d", ($to_date));?>&type=adv&back_step=my_stats_overview" class="tdsort1stPortal">
                                Details
                            </a>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <a href="account/my_stats.html?stats_step=my_stats_banners&memberid=<?php print $memberid;?>&domain_id=<?php print $domain_id;?>&from_date=<?php print date("Y-m-d", ($from_date));?>&to_date=<?php print date("Y-m-d", ($to_date));?>&type=ban&back_step=my_stats_overview" class="tdsort1stPortal">
                                BANNERS
                            </a>
                        </th>
                        <td class="text-right"><?php echo number_format($banner_views, 0, '', ','); ?></td>
                        <td class="text-right"><?php echo number_format($banner_clicks, 0, '', ','); ?></td>
                        <!--td class="tdsortstats" align="right"><?php echo $ctr = round($banner_clicks/$banner_views,3)*100; ?>%</td-->
                        <td class="text-center">
                            <a href="account/my_stats.html?stats_step=my_stats_banners&memberid=<?php print $memberid;?>&domain_id=<?php print $domain_id;?>&from_date=<?php print date("Y-m-d", ($from_date));?>&to_date=<?php print date("Y-m-d", ($to_date));?>&type=ban&back_step=my_stats_overview" class="tdsort1stPortal">
                                Details
                            </a>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><b>TOTAL</b></th>
                        <td class="text-right"><?php echo number_format($ALL_VIEWS_COUNTER, 0, '', ','); ?></td>
                        <td class="text-right"><?php echo number_format($ALL_CLICKS_COUNTER, 0, '', ','); ?></td>
                        <!--td class="tdsortfooter" align="right"><?php echo $ctr = round($ALL_CLICKS_COUNTER/$ALL_VIEWS_COUNTER,3)*100; ?>%</td-->
                        <td class="text-center">
                            &nbsp;
                        </td>
                    </tr>
                    </tbody>
                </table>
            </div>
        </div>

			
<?php
}
?>