<?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 H:i:s", $min_date_timestamp);

$prev_month = 1;
$prev_day = 1;

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

$decimal=1; 
$memberid="";
$PHPSESSID = session_id();
$back_step = isset($_REQUEST['back_step']) ? $_REQUEST['back_step'] : 'my_stats_logos';
$domain_id = $_REQUEST['domain_id'];
$type = isset($_REQUEST['type']) ? trim($_REQUEST['type']) : "adv";


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

if($type == "adv") {
    $breadcrumbs [] = array(
        'link' => 'account/my_stats.html?stats_step=my_stats_logos',
        'title' => "Logos"
    );
}
else {
    $breadcrumbs [] = array(
        'link' => 'account/my_stats.html?stats_step=my_stats_banners',
        'title' => "Banners"
    );
}

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

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

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);
}
else{
	echo '<div class="alert alert-danger">Please define either a member, an advertisment or a banner</div>';
}

$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="account/my_stats.html" method="get" class="form-horizontal">
    <input type="hidden" name="stats_step" value="my_stats_analitics"/>
    <input type="hidden" name="domain_id" value="<?=$domain_id;?>"/>
    <input type="hidden" name="type" value="<?=$type;?>"/>
    <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="back_step" value="<?=$back_step;?>"/>
</form>
<div class="alert alert-info">
    <p><b>Note:</b>&nbsp;Due to the big amount of statistics records we will allow displaying statistics data for only
    the current and previous year.</p>
</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' ";
?>

<a class="btn btn-info btn-sm" href="account/my_stats.html?stats_step=<?php echo $back_step; ?>&from_date=<?php echo $_REQUEST['from_date'];?>&to_date=<?php echo $_REQUEST['to_date'];?>">&lt;&lt; Go back</a>
<br>
<div id="print_me" class="print_me">
    <?php
    // Get the domainname
    $domainname = '';
    $qd = "SELECT * FROM domaincategories WHERE catdom_id='$domain_id' AND parent_id='0';";
    $rd = @mysql_query($qd);
    if($rd && mysql_num_rows($rd) == 1) {
        $rowd = mysql_fetch_assoc($rd);
        $domainname = str_replace('www.', '', $rowd['domainname']);
    }

	$showipaddresses="no";
	if($type == "adv"){
		$queryadvertisment = "SELECT * FROM advertisment WHERE member_id='$memberid'";
		$resultadvertisment = @mysql_query ($queryadvertisment);

		if(mysql_num_rows($resultadvertisment)>0){
			while($lineadv = mysql_fetch_assoc($resultadvertisment)){
				$query_report1="SELECT SUM(a.views), MIN(a.added_on) FROM ( SELECT * FROM adverts_stats_views_maintained WHERE advertisment_id='".$lineadv['advertisment_id']."'";
				
				$query_end = ") a WHERE a.domain_id='$domain_id' ";
				$query_report2=" GROUP BY a.ipfrom";
				
				$show_query=$query_report1 . " AND view_from!=''" . $wherequery . $query_end. $query_report2;
				
				//echo $show_query;
                //die();
				
				if(isset($_REQUEST['debugstats'])) {
        			echo "$show_query<br/>";
        		}

				$show_result=mysql_query($show_query) or die(mysql_error());
				if($show_result && mysql_num_rows($show_result)>0) {
                    ?>
                    <br>
                    <div class="box box-info">
                        <div class="box-header with-border">
                            <b>Advert Statistics in <span class="text-info"><?=$domainname;?></span> </b>
                        </div>
                        <div class="box-body text-center">
                            <b><?= stripslashes($lineadv["short_title_en"]); ?></b><br>
                            <?php
                            $imageadvert = "../images/advertisments/" . $lineadv['advertisment'];
                            if (file_exists($imageadvert) && is_file($imageadvert)) {
                                ?>
                                <img src="<?= $path; ?>images/advertisments/<?php echo $lineadv["advertisment"]; ?>"
                                     class="img img-thumbnail">
                                <?php
                            }
                            if ($lineadv["website"] <> "") {
                                ?>
                                <br><a href="<?= $lineadv["website"]; ?>" target="_blank">
                                    <?php echo $lineadv["website"]; ?>
                                </a>
                                <?
                            }
                            ?>
                        </div>
                    </div>
                    <div class="table-responsive">
                        <table class="table table-bordered">
                            <thead>
                            <tr>
                                <th><?php $count_loc = 0; ?>Portal Section</th>
                                <th>First Impres.</th>
                                <th><?php $total_impr = 0; ?>Impressions</th>
                                <th><?php $totalnoofclicks = 0; ?>Clicks</th>
                                <th><?php $totalctr = 0; $CountTotalctr = 0; ?>CTR</th>
                                <th>
                                    <?php
                                    $queryactive1 = "SELECT * FROM advertisment WHERE advertisment_id='" . $lineadv['advertisment_id'] . "'";
                                    $queryactive = $queryactive1 . " AND ";
                                    $domain_idx2 = sprintf("%04.0f", $domain_id);
                                    $queryactive .= " (catdom_id LIKE '%$domain_idx2%'";
                                    $result_sub = mysql_query("SELECT * FROM  domaincategories WHERE parent_id='$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);
                                    ?>
                                    Current status
                                </th>
                            </tr>
                            </thead>
                            <tbody>

                            <?php
                            $query_report_home = $query_report1 . " AND (view_from='top' OR view_from='sel') AND (ipfrom='' OR ipfrom='0' OR ipfrom='$domain_id') ";
                            $query_report_home .= $wherequery . $query_end;
                            $report_home = mysql_query($query_report_home);

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


                            $line_report_home = mysql_fetch_assoc($report_home);
                            $query_categ = "SELECT * FROM domain_advertisment,advertisment WHERE ((domain_advertisment.active='yes' OR (domain_advertisment.active_from <= NOW() AND domain_advertisment.active_to >= NOW())) OR (domain_advertisment.category_top='yes' OR (domain_advertisment.category_top_from <= NOW() AND domain_advertisment.category_top_to >= NOW()))) AND advertisment.active='yes' AND domain_advertisment.advertisment_id=advertisment.advertisment_id";
                            if ($line_report_home["SUM(a.views)"] > 0) {
                                ?>
                                <tr>
                                    <td><? $count_loc++; ?><b>Home page</b></td>
                                    <td>
                                        <?php
                                        if ($line_report_home["MIN(a.added_on)"] <> "") {
                                            echo date("d-M-Y", strtotime($line_report_home["MIN(a.added_on)"]));
                                        } else {
                                            echo "N/A";
                                        }
                                        ?>
                                    </td>
                                    <td class="text-right">
                                        <?php
                                        $total_impr = $line_report_home["SUM(a.views)"];
                                        if ($line_report_home["SUM(a.views)"] > 0) {
                                            $impr = $line_report_home["SUM(a.views)"];
                                            echo number_format($impr, 0, '', ',');
                                        } else {
                                            echo $impr = 0;
                                        }
                                        ?>
                                    </td>
                                    <td class="text-right">
                                        <?php
                                        //$queryclicks="SELECT advert_stats_id FROM adverts_stats_clicks WHERE advertisment_id = '$lineadv[advertisment_id]' AND domain_id='$domain_id' AND click_on LIKE 'www%' AND (catdom_id='0' or catdom_id='$domain_id') AND (click_from='sel' OR click_from='top') and ipfrom REGEXP '[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}'";
                                        $queryclicks = "SELECT a.advert_stats_id FROM (SELECT * FROM adverts_stats_clicks WHERE advertisment_id = '{$lineadv['advertisment_id']}' AND click_on LIKE 'www%' AND (catdom_id='0' or catdom_id='$domain_id') AND (click_from='sel' OR click_from='top') AND ipfrom REGEXP '^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$'";
                                        $queryclicks .= $wherequery;
                                        $queryclicks .= ") a WHERE a.domain_id='$domain_id'";

                                        $resultclicks = mysql_query($queryclicks) or die (mysql_error());
                                        $noofclicks = mysql_num_rows($resultclicks);

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

                                        echo number_format($noofclicks, 0, '', ',');

                                        $totalnoofclicks = $totalnoofclicks + $noofclicks;
                                        ?>
                                    </td>
                                    <td class="text-right">
                                        <?php
                                        if ($impr > 0) {
                                            echo $ctr = round($noofclicks / $impr * 100, $decimal);
                                            $totalctr = $totalctr + $ctr;
                                            $CountTotalctr++;
                                        } else {
                                            echo 0;
                                        } ?> %
                                    </td>
                                    <td class="text-center">
                                        <?php
                                        $query_categhome = $query_categ . " AND advertisment.advertisment_id='{$lineadv['advertisment_id']}' AND domain_advertisment.catdom_id ='$domain_id' ";
                                        $result_categhome = mysql_query($query_categhome);
                                        if (mysql_num_rows($resultactive) > 0 && mysql_num_rows($result_categhome) > 0) {
                                            ?>
                                            <span class="label label-success">Active</span>
                                            <?php
                                        } else {
                                            ?>
                                            <span class="label label-danger">Inactive</span>
                                            <?
                                        }
                                        ?>
                                    </td>
                                </tr>
                                <?php
                            }

                            $querydomaincategories = "SELECT * FROM  domaincategories WHERE parent_id='$domain_id' ORDER BY order_seq ASC";
                            $resultdomaincategories = mysql_query($querydomaincategories);
                            if (mysql_num_rows($resultdomaincategories) > 0) {
                                while ($linedomaincategories = mysql_fetch_array($resultdomaincategories)) {
                                    $query_duration = "SELECT SUM(days) FROM adver_prom_history WHERE advertisment_id='" . $lineadv['advertisment_id'] . "' AND domain_id='" . $linedomaincategories['catdom_id'] . "'";
                                    $result_duration = mysql_query($query_duration) or die(mysql_error());
                                    $line_duration = mysql_fetch_assoc($result_duration);
                                    if ($line_duration["SUM(days)"] > 0) {
                                        ?>
                                        <tr>
                                            <td><?php $count_loc++; ?><b><?=$linedomaincategories["title_el"];?></b></td>
                                            <td>
                                                <?php
                                                $query_report_home = $query_report1 . " AND (view_from='top' OR view_from='sel') AND ipfrom='" . $linedomaincategories['catdom_id'] . "'";
                                                $query_report_home .= $wherequery . $query_end;
                                                $line_report_home = mysql_fetch_assoc(mysql_query($query_report_home));
                                                ?>
                                                <?php
                                                if ($line_report_home["MIN(a.added_on)"] <> "") {
                                                    echo date("d-M-Y", strtotime($line_report_home["MIN(a.added_on)"]));
                                                } else {
                                                    echo "N/A";
                                                }
                                                ?>
                                            </td>
                                            <td class="text-right">
                                                <?php
                                                $total_impr = $total_impr + $line_report_home["SUM(a.views)"];
                                                if ($line_report_home["SUM(a.views)"] > 0) {
                                                    echo $impr = $line_report_home["SUM(a.views)"];
                                                } else {
                                                    echo $impr = 0;
                                                }
                                                ?>
                                            </td>

                                            <td class="text-right">
                                                <?php
                                                //$queryclicks = "SELECT advert_stats_id FROM adverts_stats_clicks WHERE advertisment_id = '$lineadv[advertisment_id]' AND domain_id=$domain_id AND click_on LIKE 'www%' AND (click_from='sel' OR click_from='top') AND catdom_id='".$linedomaincategories['catdom_id']."' and ipfrom REGEXP '[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}'";
                                                $queryclicks = "SELECT a.advert_stats_id FROM (SELECT * FROM adverts_stats_clicks WHERE advertisment_id = '{$lineadv['advertisment_id']}' AND click_on LIKE 'www%' AND (click_from='sel' OR click_from='top') AND catdom_id='" . $linedomaincategories['catdom_id'] . "' and ipfrom REGEXP '^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$' ";
                                                $queryclicks .= $wherequery;
                                                $queryclicks .= ") a WHERE a.domain_id=$domain_id";

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

                                                $resultclicks = mysql_query($queryclicks) or die (mysql_error());
                                                $noofclicks = mysql_num_rows($resultclicks);
                                                echo number_format($noofclicks, 0, '', ',');
                                                $totalnoofclicks = $totalnoofclicks + $noofclicks;
                                                ?>
                                            </td>
                                            <td class="text-right">
                                                <?php
                                                if ($impr > 0) {
                                                    echo $ctr = round($noofclicks / $impr * 100, $decimal);
                                                    $totalctr = $totalctr + $ctr;
                                                    $CountTotalctr++;
                                                } else {
                                                    echo 0;
                                                }
                                                ?>
                                                %
                                            </td>
                                            <td class="text-center">
                                                <?php
                                                $query_categtown = $query_categ . " AND advertisment.advertisment_id='" . $lineadv['advertisment_id'] . "' AND domain_advertisment.catdom_id ='" . $linedomaincategories['catdom_id'] . "' ";
                                                $result_categhome = mysql_query($query_categtown);
                                                if (mysql_num_rows($resultactive) > 0 && mysql_num_rows($result_categhome) > 0) {
                                                    echo '<span class="label label-success">Active</span>';
                                                } else {
                                                    ?>
                                                    <span class="label label-danger">Inactive</span>
                                                    <?php
                                                }
                                                ?>
                                            </td>
                                        </tr>
                                        <?
                                    }
                                }

                            }
                            ?>
                            <?php
                            $query_report_home = $query_report1 . " AND view_from='s'";
                            $query_report_home .= $wherequery;

                            $query_report_home .= $query_end;

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

                            $line_report_home = mysql_fetch_assoc(mysql_query($query_report_home));
                            //if($line_report_home["SUM(a.views)"]>0){
                            ?>
                            <tr>
                                <td><?php $count_loc++;?><b>Internal Search Result</b></td>
                                <td>
                                    <?php
                                    if ($line_report_home["MIN(a.added_on)"] <> "") {
                                        echo date("d-M-Y", strtotime($line_report_home["MIN(a.added_on)"]));
                                    } else {
                                        echo "N/A";
                                    }
                                    ?>
                                </td>

                                <td class="text-right">
                                    <?php
                                    $total_impr = $total_impr + $line_report_home["SUM(a.views)"];
                                    if ($line_report_home["SUM(a.views)"] > 0) {
                                        echo $impr = $line_report_home["SUM(a.views)"];
                                    } else {
                                        echo $impr = 0;
                                    }
                                    ?>
                                </td>
                                <td class="text-right">
                                    <?php
                                    //$queryclicks = "SELECT advert_stats_id FROM adverts_stats_clicks WHERE advertisment_id = '".$lineadv['advertisment_id']."' AND domain_id='$domain_id' AND click_on LIKE 'www%' AND catdom_id='0' AND click_from='s' and ipfrom REGEXP '[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}' ";
                                    $queryclicks = "SELECT a.advert_stats_id FROM (SELECT * FROM adverts_stats_clicks WHERE advertisment_id = '" . $lineadv['advertisment_id'] . "' AND click_on LIKE 'www%' AND click_from='s' AND ipfrom REGEXP '^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$'";
                                    $queryclicks .= $wherequery;
                                    $queryclicks .= ")a WHERE a.domain_id='$domain_id'";

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

                                    $resultclicks = mysql_query($queryclicks) or die (mysql_error());
                                    $noofclicks = mysql_num_rows($resultclicks);
                                    echo number_format($noofclicks, 0, '', ',');
                                    $totalnoofclicks = $totalnoofclicks + $noofclicks;
                                    ?>
                                </td>
                                <td class="text-right">
                                    <?php
                                    if ($impr > 0) {
                                        $ctr = round($noofclicks / $impr * 100, $decimal);
                                        echo $ctr;
                                        $totalctr = $totalctr + $ctr;
                                        $CountTotalctr++;
                                    } else {
                                        echo 0;
                                    }
                                    ?>
                                    %
                                </td>
                                <td class="text-center">
                                    <?php
                                    $lineactive1 = mysql_fetch_assoc(mysql_query($queryactive1));
                                    if ($domain_id == 611 && $lineactive1["active"] == 'yes') {
                                        echo '<span class="label label-success">Active</span>';
                                    } elseif (mysql_num_rows($resultactive) > 0) {
                                        echo '<span class="label label-success">Active</span>';
                                    } else {
                                        ?>
                                        <span class="label label-danger">Inactive</span>
                                        <?
                                    }
                                    ?>
                                </td>
                            </tr>
                            <?php
                            //}
                            ?>
                            <tr>
                                <td><?php $count_loc++; ?><b>More Info Page</b></td>
                                <td>
                                    <?php
                                    $query_report_home = $query_report1 . " AND (view_from='adv' OR  view_from='e')";
                                    $query_report_home .= $wherequery;

                                    $query_report_home .= $query_end;

                                    if (isset($_REQUEST['debugstats'])) {
                                        echo "<br/>More Info: $query_report_home<br/>";
                                    }
                                    $r_report_home = mysql_query($query_report_home) or die("<strong>$query_report_home</strong>" . mysql_error());
                                    $line_report_home = mysql_fetch_assoc($r_report_home);

                                    if ($line_report_home["MIN(a.added_on)"] <> "") {
                                        echo date("d-M-Y", strtotime($line_report_home["MIN(a.added_on)"]));
                                    } else {
                                        echo "N/A";
                                    }
                                    ?>
                                </td>
                                <td class="text-right">
                                    <?php
                                    $total_impr = $total_impr + $line_report_home["SUM(a.views)"];
                                    if ($line_report_home["SUM(a.views)"] > 0) {
                                        echo $impr = $line_report_home["SUM(a.views)"];
                                    } else {
                                        echo $impr = 0;
                                    }
                                    ?>
                                </td>
                                <td class="text-right">
                                    <?php
                                    //$queryclicks = "SELECT advert_stats_id FROM adverts_stats_clicks WHERE advertisment_id = '".$lineadv['advertisment_id']."' AND domain_id='$domain_id' AND click_on LIKE 'www%' AND (click_from='adv' OR click_from='e') and ipfrom REGEXP '[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}'";
                                    $queryclicks = "SELECT a.advert_stats_id FROM (SELECT * FROM adverts_stats_clicks WHERE advertisment_id = '" . $lineadv['advertisment_id'] . "'  AND click_on LIKE 'www%' AND (click_from='adv' OR click_from='e') AND ipfrom REGEXP '^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$'";
                                    $queryclicks .= $wherequery;
                                    $queryclicks .= ") a WHERE a.domain_id='$domain_id'";

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

                                    $resultclicks = mysql_query($queryclicks) or die (mysql_error());
                                    $noofclicks = mysql_num_rows($resultclicks);
                                    echo number_format($noofclicks, 0, '', ',');
                                    $totalnoofclicks = $totalnoofclicks + $noofclicks;
                                    ?>
                                </td>
                                <td class="text-right">
                                    <?php
                                    if ($impr > 0) {
                                        $ctr = round($noofclicks / $impr * 100, $decimal);
                                        echo $ctr;
                                        $totalctr = $totalctr + $ctr;
                                        $CountTotalctr++;
                                    } else {
                                        echo 0;
                                    }
                                    ?>
                                    %
                                </td>
                                <td class="text-center">
                                    <?php
                                    if (mysql_num_rows($resultactive) > 0) {
                                        echo '<span class="label label-success">Active</span>';
                                    } else {
                                        ?>
                                        <span class="label label-danger">Inactive</span>
                                        <?php
                                    }
                                    ?>
                                </td>
                            </tr>
                            <tr>
                                <td><b>Total - all <?php echo $count_loc; ?>Section(s)</b></td>
                                <td>&nbsp;</td>
                                <td class="text-right text-bold"><?php echo number_format($total_impr, 0, '', ','); ?></td>
                                <td class="text-right text-bold"><?php echo number_format($totalnoofclicks, 0, '', ',');
                                    if ($totalnoofclicks > 0) $showipaddresses = "yes"; ?></td>
                                <td class="text-right text-bold">
                                    <?php if ($total_impr > 0 && $totalnoofclicks > 0) {
                                        echo round(($totalnoofclicks / $total_impr) * 100, $decimal);
                                    } else {
                                        echo 0;
                                    }
                                    ?>
                                    %
                                </td>
                                <td>&nbsp;</td>
                            </tr>
                            </tbody>
                        </table>
                    </div>

                    <?php
                }
			}
			
		}
		else{
			?>
			No Advertisment found
			<?php 
		}
	}
	?>

	<?php 
	if($type == "ban"){
		$querybanner = "SELECT * FROM banner WHERE member_id='$memberid'";
		$resultbanner = mysql_query ($querybanner);
		if(mysql_num_rows($resultbanner)>0){
			while($lineadv=mysql_fetch_assoc($resultbanner)){
				$query_report1 = "SELECT a.*, SUM(a.views), MIN(a.added_on) FROM (SELECT * FROM banner_stats_views_maintained WHERE banner_id='".$lineadv['module_id']."'";
				$query_report2 = " GROUP BY a.ipfrom";
				$query_end2 = ") a WHERE a.domain_id='$domain_id'";
				$query_report = $query_report1 .$wherequery .$query_end2 .$query_report2;
				//$result_banner = mysql_query($query_report) or die(mysql_error());
				$show_query = $query_report1 . $wherequery . $query_end2 . $query_report2;
				
				if(isset($_REQUEST['debug'])) {
					echo "<br>BAN VIEWS: $show_query";
				}
				
				$show_result = mysql_query($show_query) or die(mysql_error());
				if(mysql_num_rows($show_result)>0){
				?>
                    <br>
                    <div class="box box-info">
                        <div class="box-header with-border">
                            <b>Banner Statistics in <span class="text-info"><?=$domainname;?></span> </b>
                        </div>
                        <div class="box-body text-center">
                            <b><?= stripslashes($lineadv["title_en"]); ?></b><br>
                            <?php
                            $imageadvert = "../images/banners/" . $lineadv['banner'];
                            if (file_exists($imageadvert) && is_file($imageadvert)) {
                                ?>
                                <img src="<?= $path; ?>images/banners/<?php echo $lineadv["banner"]; ?>"
                                     class="img img-thumbnail">
                                <?php
                            }
                            if ($lineadv["url"] <> "") {
                                ?>
                                <br><a href="http://<?= str_replace('http://', '', $lineadv["url"]); ?>" target="_blank">
                                    <?php echo $lineadv["url"]; ?>
                                </a>
                                <?
                            }
                            ?>
                        </div>
                    </div>
				<table class="table table-bordered">
                    <thead>
					<tr>
						<th>Portal Section</th>
						<th>First Impr.</th>
						<th><?php $total_impr=0; ?>Impressions</th>
						<th><?php $totalnoofclicks=0;?>Clicks</th>
						<th><?php $totalctr=0; $CountTotalctr=0;?>CTR</th>
						<th>
							<?php  
							$queryactive = "SELECT * FROM left_content WHERE catdom_id='$domain_id' AND (module_active='yes' OR (active_from <= NOW() AND active_to >= NOW())) AND module_id='".$lineadv['module_id']."' AND type='banner'";
							$resultactive=mysql_query($queryactive);
							?>
							Current Status
						</th>
					</tr>
                    </thead>
                    <tbody>
					<?php 
					$count_loc=0;
					while($line_banner=mysql_fetch_assoc($show_result)){
						?>
						<tr>
							<th scope="row">All Pages -
								<?php 
								switch ($line_banner["ipfrom"]){
									case "left":
										echo "Left Column";
										break;
									case "right":
										echo "Right Column";
										break;
									case "middle":
										echo "Middle Column";
										break;
								}
								?>
							</th>
							<td>
								<?php 
								if($line_banner["MIN(a.added_on)"]<>""){
									echo date("d-M-Y", strtotime($line_banner["MIN(a.added_on)"]));
								}
								else{
									echo "N/A";
								}
								?>
							</td>
							<td class="text-right">
								<?php 
								if($line_banner["SUM(a.views)"]>0){
									$impr = $line_banner["SUM(a.views)"];
									echo number_format($impr, 0, '', ',');
									$total_impr = $total_impr + $impr;
								}
								else{
									echo $impr=0;
								}
								?>
							</td>
							<td class="text-right">
								<?php 
								$queryclicks = "SELECT a.banner_stats_id FROM (SELECT * FROM banner_stats_clicks WHERE banner_id='".$line_banner['banner_id']."'  AND location='".$line_banner['ipfrom']."' AND ipfrom REGEXP '^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$'";
								$queryclicks .= $wherequery;
								$queryclicks .= ")a WHERE a.domain_id='$domain_id'";
								
								if(isset($_REQUEST['debug'])) {
									echo "$queryclicks<br/>";
								}
								
								$resultclicks=mysql_query($queryclicks) or die (mysql_error());
								$noofclicks = mysql_num_rows($resultclicks);
								echo number_format($noofclicks, 0, '', ',');
								$totalnoofclicks = $totalnoofclicks + $noofclicks;
								?>
							</td>
							<td class="text-right">
								<?php 
								if($impr>0){
									echo $ctr = round($noofclicks/$impr*100,$decimal);
									$totalctr = $totalctr + $ctr;
									$CountTotalctr++;
								}
								else{
									echo 0;
								}
								?>
								%
							</td>
							<td class="text-center">
								<?php  
								$queryactive = "SELECT * FROM left_content WHERE catdom_id='$domain_id' AND (module_active='yes' OR (active_from <= NOW() AND active_to >= NOW())) AND module_id='".$lineadv['module_id']."' AND type='banner' AND location='".$line_banner['ipfrom']."'";
								$resultactive=mysql_query($queryactive);
								if(mysql_num_rows($resultactive)>0){
									echo '<span class="label label-success">Active</span>';
								}
								else{
									?>
                                    <span class="label label-danger">Inactive</span>
									<?php 
								}
								?>
							</td>
						</tr>
						<?php 
						$count_loc++;
					}
				    ?>
                    </tbody>
                    <tfoot>
                        <tr>
                            <th>Total - all <?php echo $count_loc;?> Section(s) </th>
                            <td>&nbsp;</td>
                            <td class="text-right"><?php echo number_format($total_impr, 0, '', ',');?></td>
                            <td class="text-right">
                                <?php 
                                echo number_format($totalnoofclicks, 0, '', ',');
                                if($totalnoofclicks>0)$showipaddresses="yes";
                                ?></td>
                            <td class="text-right">
                                <?php 
                                if($total_impr>0 && $totalnoofclicks>0){
                                    echo round(($totalnoofclicks/$total_impr)*100,$decimal);
                                }
                                else{
                                    echo 0;
                                }
                                ?>
                                %
                            </td>
                            <td class="text-right">&nbsp;</td>
                        </tr>
                    </tfoot>
			</table>            
			<br />
			<?php 
				}
			}
		}
		else{
			?>
			No Banner found
			<?php 
		}
		?>
		<br />
		<?php 
	}
	?>
	</div>
    <div class="alert alert-info">
        <p><i class="fa fa-info-circle"></i> Reporting is not real-time. Clicks and impressions received in the last 24 hours may not be included.</p>
    </div>
	<br />
	<?php 
		if($showipaddresses=="yes"){
			
			$from_timestamp = strtotime($fromdate);
			$to_timestamp = strtotime($todate);
			
			$from_day = date("d", $from_timestamp);
			$from_month = date("m", $from_timestamp);
			$from_year = date("Y", $from_timestamp);
			
			$to_day = date("d", $to_timestamp);
			$to_month = date("m", $to_timestamp);
			$to_year = date("Y", $to_timestamp);
			
			?>
            <div class="row">
                <div class="col-sm-5 text-center">
                    <a href="account/my_stats.html?stats_step=pop-country-statistic&member_id=<?php echo $memberid;?>&domain_id=<?php echo $domain_id;?>&from_day=<?=$from_day;?>&from_month=<?=$from_month;?>&from_year=<?=$from_year;?>&to_day=<?=$to_day;?>&to_month=<?=$to_month;?>&to_year=<?=$to_year;?>&type=<?=$type;?>&page=1" class="btn btn-primary btn-block" onclick="NewWindow(this.href,'ipstats','500','400','yes');return false;"><i class="fa fa-globe"></i> <b>Country Statistics</b></a><br>
                </div>
                <div class="col-sm-5 text-center">
                    <a href="account/my_stats.html?stats_step=pop-ip&member_id=<?php echo $memberid;?>&domain_id=<?=$domain_id;?>&from_day=<?=$from_day;?>&from_month=<?=$from_month;?>&from_year=<?=$from_year;?>&to_day=<?=$to_day;?>&to_month=<?=$to_month;?>&to_year=<?=$to_year;?>&type=<?=$type;?>&page=1" class="btn btn-primary btn-block" onclick="NewWindow(this.href,'ipstats','500','400','yes');return false"><i class="fa fa-wifi"></i> <b>IP Addresses</b></a>
                </div>
            </>
			<?php
		}
	?>

<script type="text/javascript">
	function NewWindow(mypage,myname,w,h,scroll){
		LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
		TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
		settings = 'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',resizable';
		win = window.open(mypage,myname,settings);
	}
	
	function MM_openBrWindow(theURL,winName,features) { //v2.0
		window.open(theURL,winName,features);
	}
	
	jQuery.jPrintArea=function(el,css)
	{
		var iframe=document.createElement('IFRAME');
		var doc=null;
		$(iframe).attr('style','position:absolute;width:800px;height:800px;');
		document.body.appendChild(iframe);
		doc=iframe.contentWindow.document;
		
		doc.write('<'+'html'+'><'+'head'+'><'+'title'+'>Printing...<'+'/'+'title'+'>');
		//if(css != '') {
			doc.write('<'+'link'+' type="text/css" rel="stylesheet" href="https://cypruswebsites.com/print_stats.css"'+' media="print,screen"><'+'/'+'link'+'>');
		//}
		doc.write('<'+'/'+'head'+'><'+'body'+' onload="self.print();">');
		
		var links=window.document.getElementsByTagName('link');
		for(var i=0;i<links.length;i++)
			if(links[i].rel.toLowerCase()=='stylesheet')
				doc.write('<link type="text/css" rel="stylesheet" href="'+links[i].href+'"></link>');
		doc.write('<div class="'+$(el).attr("class")+'">'+$(el).html()+'</div>');
		doc.write('<'+'/'+'body'+'><'+'/'+'html'+'>'); 
		doc.close();
		iframe.contentWindow.focus();
		alert('Printing...');
		document.body.removeChild(iframe);
	}
	
	
	$(function(){
		$('.print_link').click(function(e){
			$.jPrintArea('.print_me', '');
			return false;
		});
	});
	
</script>