<?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;
}


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

$breadcrumbs [] = array(
    'link' => 'account/my_stats.html?stats_step=my_stats_overview',
    'title' => "Stats"
);

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

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

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

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();
//echo $stopwatch->now();

$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;
	echo "<br/>";
	echo '<div class="success">';
	echo '<b>You have been logged out!</b><br/>';
	echo '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.
	';
	echo '</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");
}

//echo "<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();

    $range = isset($_REQUEST['range']) ? trim($_REQUEST['range']) : '';
    if ($range != "") {
        $range = (base64_decode($range));
        $qs = array();
        parse_str($range, $qs);

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

        if (isset($qs['from_date'])) $from_date = strtotime(date('Y-m-d 00:00:00', strtotime($qs['from_date'])));
        if (isset($qs['to_date'])) $to_date = strtotime(date('Y-m-d 23:59:59', strtotime($qs['to_date'])));

        //echo '<br>$from_date = ' . date("Y-m-d H:i:s", $from_date);
        //echo '<br>$to_date = ' . date("Y-m-d H:i:s", $to_date);

        if (trim($from_date) == "") $from_date = strtotime('first day of this month', time());
        if (trim($to_date) == "") $to_date = time();

    }

    ?>
    <form id="stats-form" role="form" action="" method="post" 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_logos"/>
    </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>

    <?php

    $fromdate = date("Y-m-d", $from_date);
    $todate = date("Y-m-d", $to_date);
    $wherequery = " AND added_on >= '$fromdate' AND added_on <= '$todate' ";


    //Build the query
    $query = "SELECT HIGH_PRIORITY *, SUM(views) as sum_views, MIN(added_on) as min_added_on FROM adverts_stats_views_maintained WHERE view_from!=''";

    // Add the where clause
    $query .= $wherequery;

    //echo "<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);
    //echo $NoOfAdvs;
    //echo "<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']);
        //echo $lineadv['catdom_id'];
        for ($i = 0; $i < count($catdomids); $i++) {
            $domains[] = intval($catdomids[$i]);
        }
    }
    //echo "<br/>C at: ".$stopwatch->now();
    //print_r($domains);
    $unique_domains = implode(",", array_unique($domains));
    //$qdomains = "SELECT HIGH_PRIORITY catdom_id, domainname,parent_id FROM domaincategories WHERE parent_id=0 and catdom_id IN (".$unique_domains.");";
    $qdomains = "SELECT HIGH_PRIORITY catdom_id, domainname,parent_id FROM domaincategories WHERE catdom_id IN (" . $unique_domains . ");";
    //echo "Date 2: ".date("H:i:s")."<br>";
    $rdomains = mysql_query($qdomains) or die("<br><b>" . $qdomains . "</b><br>" . mysql_error());
    $linedomain = array();
    $linedomain_ids = array();
    while ($rowdomain = mysql_fetch_array($rdomains)) {
        $dim = array();
        if (intval($rowdomain['parent_id']) == 0) {
            $linedomain_ids[] = $rowdomain['catdom_id'];
            $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)) {
                $linedomain_ids[] = $rowdomain['parent_id'];
                $dim = $parent_domain;
            }
        }
        if (count($dim) > 0) $linedomain[] = $dim;
    }

    $linedomain_ids_str = implode(",", $linedomain_ids);
    //echo "<br/>D at: ".$stopwatch->now();
    if ($NoOfAdvs > 0) {
        $query .= " AND advertisment_id IN (";

        $advertsids = implode(",", $advert_ids);

        $query .= $advertsids . ")";
        //$query .= " AND domain_id in ($linedomain_ids_str)";
        //$query .= " AND domain_id>0 ";
        $query .= " GROUP BY domain_id";
        $query .= " ORDER BY sum_views DESC";

        //echo "<br/>Main: ".$query."<br/>";
        //echo "Date 3: ".date("H:i:s");
        $result = mysql_query($query) or die("<br><b>Error:" . $query . "</b><br>" . mysql_error());
        //echo "<br/>E at: ".$stopwatch->now();
        if (isset($_REQUEST['debugs'])) {
            echo "<br/>$query";
        }
        //echo "Date 4: ".date("H:i:s")."<br>";

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


        <div class="box box-info">
            <div class="box-header with-border">
                <b>Statistics of <b><?php echo stripslashes($linemembers["companyname"]); ?></b> "Logos" in all
                    portals.</b>
                <br><?php echo $period_string; ?>
            </div>
            <div class="box-body table-responsive no-padding">
                <table class="table table-bordered table-hover">
                    <thead>
                    <tr>
                        <th>Portal name</th>
                        <th class="text-right">First Impr.</th>
                        <th class="text-right"><?php $sumviews = 0; ?>Impressions</th>
                        <th class="text-right"><?php $totalnoofclicks = 0; ?>Clicks</th>
                        <th class="text-right"><?php $totalctr = 0; ?>CTR</th>
                        <th class="text-center">Status</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php
                    $countdomains = 1;
                    while ($line = mysql_fetch_assoc($result)) {
                        ?>
                        <tr>
                            <th scope="row">
                                <a href="account/my_stats.html?stats_step=my_stats_analitics&memberid=<?php echo $memberid; ?>&domain_id=<?php echo $line['domain_id']; ?>&from_date=<?php echo date("Y-m-d", ($from_date)); ?>&to_date=<?php echo date("Y-m-d", ($to_date)); ?>&type=adv&back_step=my_stats_logos" class="">
                                    <?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 {
                                            //echo "<br/>X at: ".$stopwatch->now();
                                            $qdom = "SELECT HIGH_PRIORITY 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'];
                                            }
                                            //echo "<br/>Y at: ".$stopwatch->now();
                                        }
                                    }

                                    echo $line_domain_name;
                                    ?>
                                </a>
                                <?php $array_logos["domain_id"][] = $line['domain_id']; ?>
                            </th>
                            <td class="text-right">
                                <?php
                                if ($line["min_added_on"] <> "") {
                                    echo date("d-M-Y", strtotime($line["min_added_on"]));
                                    $array_logos["first_impr"][] = $line["min_added_on"];
                                } else {
                                    echo "N/A";
                                    $array_logos["first_impr"][] = "N/A";
                                }
                                ?>
                            </td>
                            <td class="text-right">
                                <?php
                                if ($line["sum_views"] > 0) {
                                    echo number_format($line["sum_views"], 0, '', ',');
                                    $sumviews = $sumviews + $line["sum_views"];
                                    $array_logos["Impres"][] = $line["sum_views"];
                                } else {
                                    echo "0";
                                    $array_logos["Impres"][] = 0;
                                }
                                //}
                                ?>
                            </td>
                            <td class="text-right">
                                <?php
                                //echo "<br/>i at: ".$stopwatch->now();
                                //$queryclicks="SELECT HIGH_PRIORITY count(advert_stats_id) as sum_clicks FROM adverts_stats_clicks WHERE domain_id='".$line['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}'";
                                $queryclicks = "SELECT HIGH_PRIORITY count(a.advert_stats_id) as sum_clicks FROM (SELECT * FROM adverts_stats_clicks WHERE  click_on LIKE 'www%' AND click_from!='' and click_from not like 'http%' ";

                                if ($NoOfAdvs > 0) {
                                    $queryclicks .= " AND advertisment_id IN (" . $advertsids . ") ";
                                }
                                $queryclicks .= $wherequery;
                                $queryclicks .= " AND ipfrom REGEXP '[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}' ";

                                $queryclicks .= ") a WHERE a.domain_id='" . $line['domain_id'] . "'";

                                //echo "<br/><b>$queryclicks</b><br/>";

                                if (isset($_REQUEST['debugstats'])) {
                                    echo "$queryclicks<br/>";
                                }

                                $resultclicks = mysql_query($queryclicks) or die("<br><b>" . $queryclicks . "</b><br>" . mysql_error());
                                $rowclicks = mysql_fetch_array($resultclicks);
                                $noofclicks = $rowclicks['sum_clicks'];
                                $array_logos["Clicks"][] = $noofclicks;
                                echo number_format($noofclicks, 0, '', ',');
                                $totalnoofclicks = $totalnoofclicks + $noofclicks;
                                //echo "<br/>j at: ".$stopwatch->now();
                                ?>
                            </td>
                            <td class="text-right">
                                <?php
                                if ($noofclicks > 0 && $line["sum_views"] > 0) {
                                    echo $ctr = round($noofclicks / $line["sum_views"], 3) * 100;
                                    $totalctr = $totalctr + $ctr / 100;
                                } else {
                                    echo "0";
                                }
                                echo "%";
                                ?>
                            </td>
                            <td class="text-right">
                                <?php
                                if ($line["domain_id"] == 611) {
                                    $active = "yes";
                                } else {
                                    $active = "no";
                                    //echo "<br/>00 at: ".$stopwatch->now();
                                    reset($advert_ids);
                                    while (list($key, $advert_id) = each($advert_ids)) {
                                        $queryactive = "SELECT HIGH_PRIORITY * FROM advertisment WHERE active='yes' AND advertisment_id='$advert_id'";
                                        $queryactive .= " AND ";
                                        // echo $domain_id;
                                        $domain_idx2 = sprintf("%04.0f", $line["domain_id"]);
                                        $queryactive .= " (catdom_id LIKE '%$domain_idx2%'";
                                        $result_sub = mysql_query("SELECT HIGH_PRIORITY * FROM  domaincategories WHERE parent_id='" . $line['domain_id'] . "'");
                                        if (mysql_num_rows($result_sub) <> 0) {
                                            while ($line_sub = mysql_fetch_array($result_sub)) {
                                                $domain_idx2 = sprintf("%04.0f", $line_sub["catdom_id"]);
                                                $queryactive .= " OR catdom_id LIKE '%$domain_idx2%'";
                                            }
                                        }
                                        $queryactive .= ")";
                                        //  echo $queryactive;
                                        $resultactive = mysql_query($queryactive) or die("<br><b>" . $queryactive . "</b><br>" . mysql_error());
                                        if (mysql_num_rows($resultactive) > 0) {
                                            $active = "yes";
                                        }
                                    }
                                    //echo "<br/>01 at: ".$stopwatch->now();
                                }
                                if ($active == "yes") {
                                    echo "Active";
                                } else {
                                    ?>
                                    <span class="label label-default">Inactive</span>
                                    <?php
                                }
                                ?>
                                <?php $array_logos["Active"][] = $active; ?>
                            </td>
                        </tr>
                        <?php
                        $countdomains++;
                    }
                    ?>
                    </tbody>
                    <tfoot>
                    <tr>
                        <th scope="row">Total - All <?= mysql_num_rows($result); ?> Portal(s)</th>
                        <td>&nbsp;</td>
                        <td class="text-right">
                            <?php
                            if ($sumviews > 0) {
                                echo number_format($sumviews, 0, '', ',');
                            } else {
                                echo $sumviews = 0;
                            } ?>
                        </td>
                        <td class="text-right">
                            <?php
                            if ($totalnoofclicks > 0) {
                                echo number_format($totalnoofclicks, 0, '', ',');
                            } else {
                                echo $totalnoofclicks = 0;
                            }
                            ?>
                        </td>
                        <td class="text-right">

                            <?php
                            if ($sumviews > 0 && $totalnoofclicks > 0) {
                                echo round($totalnoofclicks / $sumviews, 3) * 100;
                            } else {
                                echo "0";
                            }
                            echo "%";
                            ?>

                        </td>
                        <td>&nbsp;</td>
                    </tr>
                    </tfoot>
                </table>
            </div>
        </div>
        <?php
    }
    else {
        ?>
        No Logos are bound with this Customer.
        <?php
    }
}