<?php 

session_start();
require 'authenticate.user.php';

require 'configuration.php';
require_once 'includes/common.functions.php';
require_once ('classes/database.php');
require_once ('classes/functions.php');
$sqlObj = new mysqlClass;
$funcObj = new funcClass;
$conntion = $sqlObj->mysqlClass();
$table = "##campaigns";
$curFile = basename(__FILE__);

## If the client is logged in then 
## give access to only those campaigns for which
## access has been granted to this user.
$currentUserId 	= intval($_SESSION['SUPER_USER_ID']);
if ($_SESSION['IS_USER_CLIENT'])
	$query 				= "SELECT ID, CAMPAIGN_NAME FROM ##campaigns WHERE IS_SENT='1' AND ID IN (SELECT CAMPAIGN_ID FROM ##client_access WHERE USER_ID = '$currentUserId') ORDER BY ID DESC";
else
	$query 				= "SELECT ID, CAMPAIGN_NAME FROM ##campaigns WHERE IS_SENT='1' ORDER BY ID DESC";

$sentCampaignList 	= array();
$sentCampaignList 	= $funcObj->CustomQuery($query);

if (count($sentCampaignList))
{								  
	$activeCampaign 	= $sentCampaignList[0]['CAMPAIGN_NAME'];
	$activeCampaignID	= $sentCampaignList[0]['ID'];
}

foreach ($sentCampaignList as $val)
{
	
	if (isset($_GET['id']) && $_GET['id'] == $val['ID'])
	{
		$activeCampaign 	= $val['CAMPAIGN_NAME'];
		$activeCampaignID	= $val['ID'];
	}
}

$secureCampId = base64_encode(base64_encode(base64_encode($activeCampaignID)));
$secureCamURL = $absPath . '/campaign.report.php?id=' . $secureCampId;
$secureCamURL = "<a href='$secureCamURL' target='_blank'>".$secureCamURL."</a>";

$query = "SELECT CAMPAIGN_NAME, FROM_NAME, FROM_EMAIL, SUBJECT, DATE_CREATED, DATE_SENT FROM ##campaigns WHERE ID = '{$activeCampaignID}'";

$result = array();
$result = $funcObj->CustomQuery($query);

$query = "SELECT DISTINCT(A.NAME) AS NAME, A.ID AS CAMPAIGNID 
FROM ##addressbook AS A,
##campaign_send_stats AS B
WHERE B.ADDR_ID = A.ID
AND B.CAMPAIGN_ID = '{$activeCampaignID}'";
$AddrResultSet = array();
$AddrResultSet = $funcObj->CustomQueryArray($query);

$addBkArray = array();
foreach($AddrResultSet as $row)
{
	$addBkArray[] = $row['CAMPAIGNID'];
}

/*
Remove bounced emails from all addressbooks used in the active/current campaign
*/
$addBkStr = '0';
$id = intval(isset($_GET['id']) ? $_GET['id'] : '');
$code = isset($_GET['code']) ? $_GET['code'] : '';
if (count($addBkArray))
{
	$addBkStr = implode("," ,$addBkArray);
}


if (isset($_GET['action']) && $_GET['action'] == 'clean')
{
	if (sha1($id)==$code)
	{
		if (count($addBkArray))
		{
			$query = "DELETE FROM ##contacts WHERE ADDR_ID IN ($addBkStr) AND EMAIL IN (SELECT DISTINCT(EMAIL) FROM ##report WHERE CAMPAIGN_ID = '$activeCampaignID' AND ACTION IN ('hardbounce', 'softbounce'))";
			$funcObj->CustomDelete($query);
			$message = "Bounced emails have been successfully removed from the address book(s).";
		}
	}
}

$query 				= "SELECT COUNT(DISTINCT(EMAIL)) AS COUNT FROM smlr_contacts WHERE ADDR_ID IN ($addBkStr) AND IS_USED = 1";
$totalSent			= $funcObj->CustomQueryCount($query)[0]['COUNT'];

$query 				= "SELECT COUNT(ID) AS COUNT FROM ##report WHERE CAMPAIGN_ID = '{$activeCampaignID}' AND ACTION='view'";
$totalViews			= $funcObj->CustomQueryCount($query)[0]['COUNT'];
/*echo"----";
print_r($query); die;*/
$query 				= "SELECT COUNT(DISTINCT(EMAIL)) AS COUNT FROM ##report WHERE CAMPAIGN_ID = '{$activeCampaignID}' AND ACTION='view'";
$totalUniqueViews	= $funcObj->CustomQueryCount($query)[0]['COUNT']; 

$query 				= "SELECT COUNT(DISTINCT(EMAIL)) AS COUNT FROM ##report WHERE CAMPAIGN_ID = '{$activeCampaignID}' AND ACTION='unsubscribe'";
$totalUnsubs		= $funcObj->CustomQueryCount($query)[0]['COUNT'];

$query 				= "SELECT COUNT(EMAIL) AS COUNT FROM ##report WHERE CAMPAIGN_ID = '{$activeCampaignID}' AND ACTION='track'";
$total_Clicks		= $funcObj->CustomQueryCount($query)[0]['COUNT'];

$query 				= "SELECT COUNT(DISTINCT(EMAIL)) AS COUNT FROM ##report WHERE CAMPAIGN_ID = '{$activeCampaignID}' AND ACTION='track'";
$totalUniqueClicks		= $funcObj->CustomQueryCount($query)[0]['COUNT'];

$query 				= "SELECT COUNT(DISTINCT(EMAIL)) AS COUNT FROM ##report WHERE CAMPAIGN_ID = '{$activeCampaignID}' AND ACTION='cantread'";
$totalCantRead		= $funcObj->CustomQueryCount($query)[0]['COUNT'];

$query 				= "SELECT COUNT(DISTINCT(EMAIL)) AS COUNT FROM ##report WHERE CAMPAIGN_ID = '{$activeCampaignID}' AND ACTION IN ('hardbounce','softbounce')";
$totalBounce		= $funcObj->CustomQueryCount($query)[0]['COUNT'];

$query 				= "SELECT TIMES_FORWARDED AS COUNT FROM ##campaigns WHERE ID = '{$activeCampaignID}'";
$timesForwarded		= $funcObj->CustomQueryCount($query)[0]['COUNT'];

$query 				= "SELECT COUNT(DISTINCT(A.EMAIL)) AS COUNT FROM ##contacts AS A, ##report AS B WHERE A.ADDR_ID IN ($addBkStr) AND A.EMAIL = B.EMAIL AND B.CAMPAIGN_ID = '$activeCampaignID' AND B.ACTION IN ('hardbounce', 'softbounce')";
$totalBounceInDb	= $funcObj->CustomQueryCount($query)[0]['COUNT'];

/* ACTIVATE THE TAB */
$activeTab = 'Reports';
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Segnant Mailer - Campaign Report</title>
<link rel="stylesheet" type="text/css" href="includes/css/thickbox.css" />
<link rel="stylesheet" type="text/css" href="includes/css/segnantmailer.css" />
<script src="https://www.openlayers.org/api/OpenLayers.js"></script>
<script type="text/javascript" src="includes/js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="includes/js/common.jquery.js"></script>
<script type="text/javascript" src="includes/amline/swfobject.js"></script>
<script type="text/javascript" src="includes/js/jquery.reports.js"></script>
<script type="text/javascript" src="includes/js/thickbox-compressed.js"></script>
<script type="text/javascript" src="includes/js/chart_loader.js"></script>

<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
</head>

<script type="text/javascript">
		
		var map = new OpenLayers.Map("mapdiv");
		map.addLayer(new OpenLayers.Layer.OSM());
		 <?php
		$query = mysqli_query($conntion,"SELECT `longitude`, `latitude` FROM `smlr_visitor_map` WHERE campaign_id = '{$activeCampaignID}'");
			
			while($row = mysqli_fetch_array($query))
			{
				
			?>
				var lonLat = new OpenLayers.LonLat(<?php echo $row['longitude']; ?>,<?php echo $row['latitude']; ?>)
					  .transform(
						new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
						map.getProjectionObject() // to Spherical Mercator Projection
					  );
				 console.log(lonLat);	  
				var zoom=16;

				var markers = new OpenLayers.Layer.Markers( "Markers" );
				map.addLayer(markers);
				
				markers.addMarker(new OpenLayers.Marker(lonLat));
				
				map.setCenter (lonLat, zoom);
			  
		  <?php
		}

		?>
	
  </script>
<body>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td height="79" class="headerbg"><?php require_once 'includes/inc.header.php' ?>
    </td>
  </tr>

  <tr>
    <td class="canvas" height="300" valign="top"><table width="100%" border="0" cellspacing="10" cellpadding="4">
        <tr>
          <td colspan="2" class="heading" height="50" valign="top">Campaign Report</td>
        </tr>
        <tr>
          <td colspan="2" bgcolor="#eaeaea" style="padding:10px;">
          <table width="100%" cellspacing="0" cellpadding="0">
          <tr>
          <td>
          <table cellspacing="0" cellpadding="0" class="tabtable">
              <tr>
                <?php
				$file = basename($_SERVER['PHP_SELF']);
				
				## ADD EXCEPTIONS
				
				$tabArray = array("<td nowrap=\"nowrap\" style=\"cursor:pointer;\" onclick=\"javascript:window.location.href='reports.php'\"> Graphical Report </td>",
						"<td nowrap=\"nowrap\" style=\"cursor:pointer;\" onclick=\"javascript:window.location.href='reports.listing.php'\"> Listing Report </td>");
				foreach ($tabArray as $key => $val)
				{
					$strpos = strpos($val, $file);
				
					if ($strpos > 0)
					{
						$newString = str_replace('style="cursor:pointer;"','style="cursor:pointer;" class="active" ',$val);
						echo $newString;
					}
					else
					{
						echo $val;
					}	
				}
				?>
              </tr>
            </table>
            </td>
            <td width="70%" align="right"><strong>Direct URL:</strong> <?php echo $secureCamURL; ?> </td>
            </tr>
            </table>
            <table width="100%" border="0" cellspacing="0" cellpadding="4">
              <tr>
                <td height="405" bgcolor="#FFFFFF" valign="top"><table width="100%" border="0" cellspacing="1" cellpadding="1">
                    <tr>
                      <td valign="top">
                      <table width="100%" border="0">
                      <tr>
                      <td height="55" width="75%" valign="middle" align="left"> 
                      <?php if (!empty($message))
					  echo "
                      <div class='message'>$message</div>
					  ";
					  ?>
                      </td>
                      <td align="right">
                      <form name="formSelCampaign" action="reports.php" method="get" style="margin: 0;">
                          <table border="0" cellspacing="2" cellpadding="2" align="right">
                            <tr>
                              <td nowrap="nowrap"><strong>Choose Campaign</strong></td>
                              <td>
                              <select name="id" id="id" class="textbox" onchange="showreport(this.value)">
                              <?php
							  if (count($sentCampaignList))
							  {	  
								  $activeCampaign 	= $sentCampaignList[0]['CAMPAIGN_NAME'];
							  	  $activeCampaignID	= $sentCampaignList[0]['ID'];
							  }
							  foreach ($sentCampaignList as $val)
							  {
									
									$selected = '';
									if ($_GET['id'] == $val['ID'])
									{
										$activeCampaign 	= $val['CAMPAIGN_NAME'];
										$activeCampaignID	= $val['ID'];
										$selected 		= 'selected="selected"';
									}
									echo "<option value='{$val["ID"]}' $selected>" .$val['CAMPAIGN_NAME']. "</option>\n";
							  }
							  
							  if (count($sentCampaignList) == 0)
							  {
							  		echo "<option value='0'>No Sent Campaign Available</option>\n";
							  } 
							  ?>
                              </select>
                              
                              <?php
							 
							  /*
							  Query for Overview Report
							  */ 
							  	$failedEmails				= $totalBounce;	
							 
								$query = "SELECT A.ID AS CAMPAIGNID 
								FROM ##addressbook AS A,
								##campaign_send_stats AS B
								WHERE B.ADDR_ID = A.ID
								AND B.CAMPAIGN_ID = '{$activeCampaignID}'";
								$AddrResultSet1 = array();
								$AddrResultSet1 = $funcObj->CustomQueryArray($query);
								
								$campIds = array();
								foreach($AddrResultSet1 as $row)
								{
									$campIds[] = $row['CAMPAIGNID'];									
								}
								
								if (count($AddrResultSet1) == 0)
									$campIds[] = 0;
								
								$campIdsStr = implode(",", $campIds);
								######################################################
								
								########## 	calculate total row and store that into SESSION	for faster retrieval####
								$totalEmailsSent 					= $totalSent;
								
								if ($totalEmailsSent == 0)
								{
									$query 							= "SELECT COUNT(DISTINCT(EMAIL)) AS TOTAL FROM ##contacts WHERE ADDR_ID IN ($campIdsStr)";
									$resultCampIds 					= $funcObj->CustomQuery($query);
									$totalEmailsSent 				= $resultCampIds[0]['TOTAL'];
								}
															  
							  $query = "SELECT COUNT(DISTINCT(EMAIL)) AS `READ` FROM ##report WHERE CAMPAIGN_ID = '{$activeCampaignID}' LIMIT 1";
							  $totalEmailViewsResultSet		= array();
							  $totalEmailViewsResultSet 	= $funcObj->CustomQuery($query);
							  $totalEmailsRead				= $totalEmailViewsResultSet[0]['READ'];
							  
							  $emailsNotRead 				= (($totalEmailsSent - $failedEmails) - $totalUniqueViews);
							  
							  if ($emailsNotRead < 0)
							  	$emailsNotRead = 0;
							  	
							  $overviewReportData 	= 'Emails Read;'.$totalUniqueViews.';true;008930\nEmails Not Read;'.$emailsNotRead.';false;eeb300\nEmails Failed;'.$failedEmails.';false;e04117';
							
							  ####### OVERVIEW REPORT QUERIES END###################
							  					
								
							  ####### OVERALL SUCCESS RATE REPORT ###################								 
							  $query = "SELECT COUNT(DISTINCT(EMAIL)) AS `CLICKS` FROM ##report WHERE CAMPAIGN_ID = '{$activeCampaignID}' AND ACTION = 'track' LIMIT 1";
							  $totalEmailClicksResultSet		= array();
							  $totalEmailClicksResultSet 		= $funcObj->CustomQuery($query);
							  $totalEmailClicks					= $totalEmailClicksResultSet[0]['CLICKS'];
							  if ($totalEmailClicks > 0)
							  		$totalClicks						= (($totalEmailClicks / ($totalEmailsSent - $failedEmails)) * 100);
							  else
							  		$totalClicks = 0;
							  
							  ####### OVERALL SUCCESS RATE REPORT END###################								 
							  
							 
  							  $query = "SELECT COUNT(ID) AS COUNT, ACTION, DATE_TIME, DATE_FORMAT(DATE_TIME, '%e %b') AS DATE 
							  FROM smlr_report WHERE CAMPAIGN_ID = '{$activeCampaignID}' GROUP BY ACTION, DATE_TIME ORDER BY DATE_TIME ASC";
							  
							  $activityReportResultSet	= array();
							  $activityReportResultSet 	= $funcObj->CustomQuery($query);
							  
							  $activityReportReportData = "";
							  
							  $views = 0;
							  $unsubs = 0;
							  $tracks = 0;
							  $date = "";
							  $iCount = 1;
							  $popRows = 1;
							  foreach ($activityReportResultSet as $row)
							  {
								 
							  		if ($date == "")
									{
										$date = $row['DATE'];
									}
									
									// if the date is same
									if ($date == $row['DATE'])
									{
										if ($row['ACTION'] == 'track')
											$tracks = $row['COUNT'];
										else if ($row['ACTION'] == 'unsubscribe')		
											$unsubs = $row['COUNT'];
										else if ($row['ACTION'] == 'view')			
											$views = $row['COUNT'];
										$date = $row['DATE'];	
									}
									else
									{
										$activityReportReportData .= $date . ';' . $views . ';' . $tracks . ';' . $unsubs . "\n";
										
										if ($popRows == 15)
											break;
											 
										$popRows++;
										
										$views = 0;
										$unsubs = 0;
										$tracks = 0;
										$date = "";

										// assign a new date
										$date = $row['DATE'];	
										
										if ($row['ACTION'] == 'track')
											$tracks = $row['COUNT'];
										else if ($row['ACTION'] == 'unsubscribe')		
											$unsubs = $row['COUNT'];
										else if ($row['ACTION'] == 'view')			
											$views = $row['COUNT'];
										
										
									}
									if ($iCount == count($activityReportResultSet))
										$activityReportReportData .= $date . ';' . $views . ';' . $tracks . ';' . $unsubs . "\n";
										
									$iCount++;
							  }
							  ?>                                                            </td>
                              <td>
                              <input type="hidden" name="action" value="selCampaign" />                              </td>
                            </tr>
                            <tr>
                              <td height="50" colspan="3" nowrap="nowrap" align="right" valign="middle" class="orange size14 bold"><strong>Export Report</strong> &nbsp;&nbsp;&nbsp;<a href="export-excel.php?id=<?=$activeCampaignID?>&amp;type=excel"><img src="images/Excel_48.png" alt="Export to Excel format" border="0" align="absmiddle" hspace="6" /></a><a href="export-excel.php?id=<?=$activeCampaignID?>&amp;type=html"><img src="images/HTML_48.png" alt="Export to HTML format" border="0" hspace="6" align="absmiddle" /></a></td>
                            </tr>
                          </table>
                        </form>
                        </td>
                        </tr>
                        </table>
                        </td>
                    </tr>
                    <tr>
                      <td class="size18 orange bold" style="padding-bottom: 18px;" height="35">Report for: <?=$activeCampaign?></td>
                    </tr>
                    <tr>
                      <td class="size15 bold" height="20">&nbsp;</td>
                    </tr>
                    <tr>
                      <td class="size15 bold" height="30" style="border-bottom: 2px solid #ccc"><img src="images/overview.png" alt="" align="left" hspace="5" />Overview Report<br />
                      <small style="font-weight: normal; font-size: 11px;">The report will show the overall result of newsletter campaign. Like how many emails failed, how many people read or unread the newsletter.</small>                      </td>
                    </tr>
                    <tr>
                      <td>&nbsp;                      </td>
                    </tr>
                    <tr>
                      <td>
					  <?php 
					 
						if (count($totalEmailViewsResultSet))
						{
						?>
							<div id="piechart"></div>
							
							<script type="text/javascript">
							var emailRead ='<?php echo $totalUniqueViews;?>';
							var emailsNotRead ='<?php echo $emailsNotRead;?>';
							var failedEmails ='<?php echo $failedEmails;?>';
							// Load google charts
							google.charts.load('current', {'packages':['corechart']});
							google.charts.setOnLoadCallback(drawChart);

							// Draw the chart and set the chart values
							function drawChart() {
							  var data = google.visualization.arrayToDataTable([
							  ['How many people read or unread the newsletter', 'Per newsletter'],
							  ['Total Unique Views', emailRead],
							  ['Emails Not Read', emailsNotRead],
							  ['Emails Bounced', failedEmails],
							 
							]);

							  // Optional; add a title and set the width and height of the chart
							  var options = {'title':' ', 'width':550, 'height':400};

							  // Display the chart inside the <div> element with id="piechart"
							  var chart = new google.visualization.PieChart(document.getElementById('piechart'));
							  chart.draw(data, options);
							}
							</script>

							
						<?php } ?>
                        <?php
						
                        ## only load the graph if the data is available
						
                        ?>                      </td>
                    </tr>
                    <tr>
                      <td class="size15 bold" height="50">&nbsp;</td>
                    </tr>
                    <tr>
                      <td class="size15 bold" height="30" style="border-bottom: 2px solid #ccc"><img src="images/success.png" alt="" align="left" hspace="5" />Overall Success  Report (%)<br />
                      <small style="font-weight: normal; font-size: 11px;">The report will show the overall sucess of the campaign. Based upon how many people actually visited the target website.</small>                      </td>
                    </tr>
                    <tr>
                      <td>&nbsp;                      </td>
                    </tr>
                    <tr>
                      <td>
                        <div id="successreport"> 
                       		<img src="image.php?percentage=<?=$totalClicks?>" alt="<?=$totalClicks?> Percent" title="<?=$totalClicks?> Percent" />                            
                        </div>
					</td>
                    </tr>
                    <tr>
                      <td height="60">&nbsp;</td>
                    </tr>
                    <tr>
                      <td class="size15 bold" height="30" style="border-bottom: 2px solid #ccc"><img src="images/User-group-48.png" alt="" align="left" hspace="5" />Activity Report<br />
                      <small style="font-weight: normal; font-size: 11px;">The report will show how many people viewed, clicked, unsubscribed the newsletter.</small>                      </td>
                    </tr>
                    <tr>
                      <td>&nbsp;                      </td>
                    </tr>
                    <tr>
                      <td>
                       
                        <?php
						$activityReportReportData .= $date . ';' . $views . ';' . $tracks . ';' . $unsubs . "\n";
                        ## only load the graph if the data is available
						if (count($activityReportResultSet))
						{
							?>
							<div id="piechart_2"></div>
							
							<script type="text/javascript">
							var views ='<?php echo $totalViews;?>';
							var tracks ='<?php echo $total_Clicks;?>';
							var unsubs ='<?php echo $totalUnsubs;?>';
							// Load google charts
							google.charts.load('current', {'packages':['corechart']});
							google.charts.setOnLoadCallback(drawChart);

							// Draw the chart and set the chart values
							function drawChart() {
							  var data = google.visualization.arrayToDataTable([
								  ['How many people viewed, clicked, unsubscribed the newsletter.', 'Per newsletter'],
								  ['Total Views', views],
								  ['Total Clicks', tracks],
								  ['Emails Unsubscribe', unsubs],
								 
								]);

							  // Optional; add a title and set the width and height of the chart
							  var options = {'title':' ', 'width':550, 'height':400};

							  // Display the chart inside the <div> element with id="piechart"
							  var chart = new google.visualization.PieChart(document.getElementById('piechart_2'));
							  chart.draw(data, options);
							}
							</script>
							
							
							
							<?php
                        }
                        ?>                      </td>
                    </tr>
                    <tr>
                      <td>&nbsp;</td>
                    </tr>
                    <tr>
                      <td class="size15 bold" height="30" style="border-bottom: 2px solid #ccc"><img src="images/Globe-48.png" alt="" align="left" hspace="5" />Geographical Location Report<br />
                      <small style="font-weight: normal; font-size: 11px;">The report will show geographical location of newsletter readers (recipients).</small> &nbsp;&nbsp;&nbsp;<span class="help"><a href="#TB_inline?height=100&amp;width=400&amp;inlineId=aboutgeodata" class="thickbox orange">about geographic data</a></span>                      </td>
                    </tr>
                    <tr>
                      <td>&nbsp;</td>
                    </tr>
                    <tr>
                      <td><div id="mapdiv" style="width: 640px; height: 400px"></div></td>
                    </tr>
                    <tr>
                      <td>&nbsp;</td>
                    </tr>

                </table></td>
                <td valign="top" align="left" width="300">
                    <table width="100%" border="0" cellspacing="1" cellpadding="1" class="inputformtable">
                      <tr>
                        <td class="pageHeadingRt" colspan="2"><?php echo ucwords(isset($ACTION) ? $ACTION : '') ?> Campaign Statistics
                          <?php if (isset($ACTION) && $ACTION == 'edit') { echo "&nbsp;&nbsp;<small>(<a href='{$_SERVER["PHP_SELF"]}'>Cancel Edit</a>)</small>"; } ?>                        </td>
                      </tr>
                      <tr>
                      <td class="size14 bold" colspan="2" height="45" style="border-bottom: 2px solid #ccc"><img src="images/stats2-48.png" alt="" hspace="3" align="absmiddle" /> <?=$activeCampaign?></td>
                     </tr>
                      <tr>
                        <td colspan="2" class="inputlabel">Subject: <?=$result[0]['SUBJECT']?></td>
                      </tr>
                      <tr>
                        <td colspan="2" class="inputlabel">Date Created/Updated: <?= date("M j, Y", strtotime($result[0]['DATE_CREATED']));?></td>
                      </tr>
                      <tr>
                        <td class="inputlabel" colspan="2">Date Sent: <?= date("M j, Y", strtotime($result[0]['DATE_SENT']));?></td>
                      </tr>
                      <tr>
                        <td width="40%" class="inputlabel" style="padding-top: 8px" colspan="2">Address Book(s): <br />
                        <div style="font-weight: normal; margin-top: 5px;">
						<?php
						$iCount = 1;
						  foreach($AddrResultSet as $row)
						  {
							echo $iCount . '. ' . $row['NAME'] . '<br />';
							$iCount++;
						  }
						  ?>
						</div>
                        </td>
                      </tr>
                      <tr>
                        <td height="32" colspan="2">&nbsp;</td>
                      </tr>
                      <tr>
                        <td class="size14 bold" height="45" style="border-bottom: 2px solid #ccc"><img src="images/Time-Machine-48.png" alt="" hspace="3" align="absmiddle" /> To-Date Status </td><td align="right" style="border-bottom: 2px solid #ccc"><span class="help"><a href="#TB_inline?height=500&amp;width=800&amp;inlineId=statsdata" class="thickbox orange">What's this?</a></span></td>
                      </tr>
                      
                      <tr>
                        <td height="45" colspan="2">
                        <table width="100%" cellpadding="0" cellspacing="0">
                        <tr class="row1">
                        <td width="60%">Total Sent:</td>
                        <td><?php
                        $actualSent = $totalSent - $totalBounce;
						if ($totalSent > 0)
							$percentSent = ($actualSent * 100) / $totalSent;
						else
							$percentSent = 0;
						
						echo $actualSent . " (";
						printf("%.2f",$percentSent);
						echo '%)'
						?></td>
                      </tr>
                        <tr class="row0">
                        <td width="60%">Total Views:</td>
                        <td><?=$totalViews?></td>
                      </tr>
                        <tr class="row1">
                          <td>Total Unique Views:</td>
                          <td><?php
						  $percentSent = 0;
						  if ($actualSent > 0)
							$percentSent = ($totalUniqueViews * 100) / $actualSent;
						else
							$percentSent = 0;
						
						echo $totalUniqueViews . " (";
						printf("%.2f",$percentSent);
						echo '%)'
						  
						  ?></td>
                        </tr>
                        <tr class="row0">
                        <td>Total Un-subscriptions:</td>
                        <td><?=$totalUnsubs?></td>
                      </tr>
                      <tr class="row1">
                        <td>Total Click-throughs:</td>
                        <td><?=$total_Clicks?></td>
                      </tr>
                      <tr class="row0">
                        <td>Unique Click-throughs:</td>
                        <td><?php
						$percent = 0;
						  if ($actualSent > 0)
							$percent = ($totalUniqueClicks * 100) / $actualSent;
						else
							$percent = 0;
						
						echo $totalUniqueClicks . " (";
						printf("%.2f",$percent);
						echo '%)'
						?></td>
                      </tr>
                      <tr class="row1">
                        <td>Total Can't Read clicks:</td>
                        <td><?=$totalCantRead?></td>
                      </tr>
                      <tr class="row0">
                        <td>Times Forwarded:</td>
                        <td><?=$timesForwarded?></td>
                      </tr>
                      <tr class="row1">
                        <td>Total Bounced Emails:</td>
                        <td><?php
						$percent = 0;
						  if ($actualSent > 0)
							$percent = ($totalBounce * 100) / $actualSent;
						else
							$percent = 0;
						
						echo $totalBounce . " (";
						printf("%.2f",$percent);
						echo '%)'
						?></td>
                      </tr>
                        </table>
                        </td>
                      </tr>
                      <tr>
                        <td height="32" colspan="2">&nbsp;</td>
                      </tr>
                      <tr>
                        <td class="size14 bold" colspan="2" height="45" style="border-bottom: 2px solid #ccc"><img src="images/addressbook.png" alt="" hspace="3" align="absmiddle" /> Clean Address Book</td>
                      </tr>
                      <tr>
                        <td colspan="2">Did you know that you can remove all bounced emails from your address book and it's just a click away?<br />
                          <br />
                          <?php
						  if ($totalBounceInDb > 0)
						  {
						       echo "<a href='javascript:confirmAction(\"Are you sure you want to delete all bounced emails \\nfrom all address books used in this campaign?\",\"reports.php?action=clean&amp;id=$activeCampaignID&amp;code=".sha1($activeCampaignID)."\")'>Remove all bounced emails</a> &nbsp;($totalBounceInDb)";
                          }
                          else
                          {
                          		echo "<a href='javascript:alert(\"There are no bounced emails to remove.\")'>Remove all bounced emails</a> &nbsp;($totalBounceInDb)";
                          }
						  ?>
                          </td>
                      </tr>
                    </table>
                </td>
              </tr>
            </table></td>
        </tr>
      </table></td>
  </tr>
  <?php require_once 'includes/inc.footer.php' ?>
</table>
<div id="aboutgeodata" style="display:none">
  <p>Although data about country location is accurate, and state level data is usually pretty accurate, detailed local data can sometimes be inaccurate due to how ISPs handle IP addresses.</p>
  <p> </p>
</div>
<div id="statsdata" style="display:none">
  <p><h3>Typical Email Campaign Stats and What They Mean</h3>
<p>Let's go over some typical email campaign stats, and how email  marketers should use them. These are stats you'll find in Segnant Mailer campaign reports, but you'll find them in any decent email marketing  service.</p>
<h4>Total Sent</h4>
<p>This one's pretty obvious. It's basically the number of emails sent in this campaign. Not all deliveries will  be successful, though...</p>
<h4>Total Views</h4>
<p>This is a stat with lots of &quot;wow&quot; factor, but don't let it get to  your head. Your email might have been opened 10,000 times, and that  sounds really cool. But what if it was just one guy (a guy with way too  much time on his hands) who opened your email 10,000 times? That's  pretty extreme, but you get the gist. It's not a totally useless stat.  For example, if you sell banner advertisements in your email campaigns,  then an open is an impression, and you want to show total impressions  (even if one of your recipients is a whacko). </p>
<h4>Total Unique Views</h4>
<p>This is a more accurate stat. It tells you how many individuals  opened your campaign. So if two (very sad, very lonely) people opened  your campaigns 500 times each, that would be 1,000 total opens. This  stat would show, &quot;2 recipients opened&quot; which is a lot more useful to  email marketers.</p>
<h4>Total Un-subscriptions</h4>
<p>If any email campaign stat is capable of bringing a tear to your eye, this is the one. We've seen average unsubscribe rates of less than half of one percent. Anything above that means you did something to make a lot of people very angry at you. </p>
<h4>Total Click-throughs</h4>
<p>This is the total number of clicks your email got. It's handy in  determining how much overall web traffic you'll get to your website  after a campaign is sent. For instance, it might be nice to know that  &quot;after every email marketing campaign I send, our website gets about  100,000 visits.&quot; </p>
<h4>Unique Click-throughs</h4>
<p>This stat counts how many times your recipients clicked on links inside your email campaign, <em>minus</em> any duplicate clicks. So if some weirdo clicked on 2 different links 500 times each, we tell you that you had 2 unique clicks. </p>
<h4>Total Online Views</h4>
<p>This stat tells how many recipients actually visited your email/newsletter on the web. This could mean that these recipients had faced difficulty in viewing your email in their email program.</p>
<h4>Times forwarded</h4>
<p>Segnant Mailer lets you insert a link into your email campaign that  allows your recipient to forward a copy of your campaign to a friend.  We'll actually track how many times the email was forwarded using this  link. Note that we do <strong>not</strong> track who your emails were  forwarded to, and we certainly don't add them to your mailing list. And we  can't tell if you forward a campaign from your own email account. That  would be evil.</p>
<h4>Total Bounced Emails</h4>
<p>When you send a campaign, you get bouncebacks. Bounce in simple terms means that the email fails to reach at recipient's inbox. There are two types of bounces you should know about. A "Hard bounce" basically means you sent your campaign to a bad, "undeliverable" email address. Maybe the person closed down their account, or got fired. Whatever the case, you shouldn't send anymore emails to that address, or the recipient's email server will start blocking you. Segnant Mailer instantly removes hard bounced emails from your mailing list for you. The other bounce type is a "soft" bounce. In general, a soft bounce just means the recipient's email account was "temporarily unavailable." Maybe their server was busy, or their account was too full. Currently Segnant Mailer does not track soft bounce emails. The future versions of Segnant Mailer will certainly have this feature too.</p></p>
  <p> </p>
</div>
</body>

</html>
