<?php
/* Get Max & Min Dates **********************************/

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

// 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' => "Banners"
);

$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;
    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>';
}

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();

    $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_banners"/>
    </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 00:00:00' AND added_on <= '$todate 23:59:59' ";

    $query = "SELECT *, SUM(views), MIN(added_on) FROM banner_stats_views_maintained WHERE domain_id>0 and ipfrom in ('left', 'right', 'middle', 'popup')";
    $query .= $wherequery;

    $banners = array();

    $queryadv = "SELECT * FROM banner WHERE member_id='$memberid'";
    //echo $queryadv;
    $resultadv = mysql_query($queryadv);
    $NoOfAdvs = mysql_num_rows($resultadv);
    if ($NoOfAdvs > 0) {
        while ($lineadv = mysql_fetch_assoc($resultadv)) {
            $banners[] = $lineadv['module_id'];
        }

        //print_r($banners);

        $ban_ids = implode(",", $banners);

        $query .= " AND banner_id in ($ban_ids) ";
        $query .= " GROUP BY domain_id";
        $query .= " ORDER BY views DESC";

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

        //echo "<br>VIEWS: $query";

        $result = mysql_query($query) or die (mysql_error());


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

        ?>

        <div class="box box-info">
        <div class="box-header with-border">
            <b>Statistics of <b><?php echo stripslashes($linemembers["companyname"]); ?></b> "Banners" 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;
            $linedomain = array();
            $array_logos = array();
            $array_logos["Impres"] = array();
            $array_logos["first_impr"] = array();
            $array_logos["Clicks"] = 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)) {
                $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") {
                    ?>
                    <tr onmouseover="this.className='stats_hover'" onmouseout="this.className='stats_normal'">
                        <td class="tdsort1stPortal" 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=ban&back_step=my_stats_banners"
                               class="tdsort1stPortal">
                                <?php


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

                                echo $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 (isset($array_logos["first_impr"][$key]) && 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) {
                                echo number_format($line["SUM(views)"], 0, '', ',');
                                $sumviews = $sumviews + $line["SUM(views)"];
                            } else {
                                echo "0";
                            }



                            if ($key > -1) {
                                if(!isset($array_logos["Impres"][$key])) $array_logos["Impres"][$key] = 0;
                                $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 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) ";
                            }

                            $queryclicks .= $wherequery;
                            $queryclicks .= " AND location in ('left', 'right', 'middle', 'popup') ";
                            $queryclicks .= ") a WHERE a.domain_id='" . $line['domain_id'] . "'";

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

                            $resultclicks = mysql_query($queryclicks) or die (mysql_error());
                            $noofclicks = mysql_num_rows($resultclicks);
                            if ($noofclicks > 0) {
                                echo number_format($noofclicks, 0, '', ',');
                                $totalnoofclicks = $totalnoofclicks + $noofclicks;
                            } else {
                                echo $noofclicks = 0;
                            }

                            if ($key > -1) {
                                if(!isset($array_logos["Clicks"][$key])) $array_logos["Clicks"][$key] = 0;
                                $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 {
                                echo "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 echo 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) {
                        echo number_format($sumviews, 0, '', ',');
                    } else {
                        echo $sumviews = 0;
                    }
                    ?>
                </td>
                <td class="tdsortfooter" align="right">
                    <?php
                    if ($totalnoofclicks > 0) {
                        echo 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 {
                        echo "0";
                    } ?>%

                </td>
                <td class="tdsortfooter">&nbsp;</td>
            </tr>
        </table>

        <?php
    } else {
        ?>
        You have no banners.
        <?php
    }

}
?>