<?php

/**
* @desc This class handles setup and distrubution of reports per email
*/
if(!defined('APP_INCLUDE')){ die('invalid inclusion'); }

include_once logaholic_dir()."includes/pdf.php";

class EmailAlerts {
    
    var $profilename;
    var $sender;
	
    var $alertdata;
	
	var $from;
	var $to;

	var $send; # counts how many alerts are send
    
    function __construct() {
        global $conf, $cm, $profile;

        if (!isset($conf)) { die("No profile selected"); }
        $this->profilename=$conf;
        if (isset($_SERVER['HTTP_HOST'])) {
            $edomain = $_SERVER['HTTP_HOST'];    
        } else {
            $edomain = @php_uname("n");     
        }
        $this->sender="noreply@".$edomain;

        if(!empty($cm->pdf_email_reply)){
        	$this->sender = $cm->pdf_email_reply;
        }
        $this->send = 0;

        //dashboards could have been deleted, make a list of valid dashboards
        $this->valid_dashboards = [];
        foreach($profile->dashboards as $dash) {
        	$n = json_decode($dash['Value'], true);        	
        	$this->valid_dashboards[] = $n["name"];
        }
    }
    function EmailAlerts() {
        __construct();
    }
    
    /**
    * @desc This function will allow a user to create an email alert
    */
    function CreateAlert() {
        $this->ValidateForm();
        echo "<h3>"._CREATE_ALERT."</h3>\n";
        
        echo "<form id=\"emailalerts\">\n";
	        echo "<div class='form-group col-sm-6'><label>"._EMAIL_ADDRESS.":</label><input class='form-control' type=text name=\"email\"></div>\n";

	        echo "<div class='form-group col-sm-6' id='emailalerts_intervals'><label>"._SELECT_INTERVAL.":</label>".$this->SelectInterval()."</div>\n";



			echo "<div class='form-group col-sm-6' id='emailalerts_dashs'><label>"._DASHBOARDS.":</label>".$this->SelectDashboards()."</div>\n";
	        echo "<div class='form-group col-sm-6' id='emailalerts_reports'><label>"._SELECT_REPORTS.":</label>".$this->SelectReports()."</div>\n";

	        echo "<input type=hidden name=\"conf\" value=\"$this->profilename\">\n";
	        echo "<div class='form-group col-sm-6'><button class='btn btn-primary submitbut'>"._SAVE_EMAIL_ALERTS."</button></div>\n";
	        echo "<div style='clear:both;'></div>";
    }
    
    /**
    * @desc This function will allow a user to select from a list of reports
    */
    function SelectReports() {
        global $l_constant,$t_constant,$reports;
        $o = "<select class='form-control' name=\"reports[]\" MULTIPLE size=5>";
        $i=0;
		$noTableReports = [];
		
		foreach($reports as $k => $v) {
			if ($v['Category'] == "_KEY_METRIC") {
				continue;
			}
			if((isset($v['EmailAlerts']) && $v['EmailAlerts'] == false) || (isset($v['hidden']) && $v['hidden'] == true)) {
				$noTableReports[] = $k;
				continue;
			}
			if(in_array($k,$noTableReports) == FALSE){
				$o.= "<option value=\"$k\">".constant($k)."</option>\n";
			}
		}
        $o.= "</select>";
        return $o;
    }
    
	/**
    * @desc This funtion will allow a user to receive a infographic
    */
	function SelectInfograhpic(){
		$o = "<input type='checkbox' name='infographics' style='display:block;margin-top:5px;'>\n";		
		return $o;
	}	
	
	/**
    * @desc This function will allow a user to select from a list of dashboards
    */
    function SelectDashboards() {
        global $l_constant,$t_constant,$reports,$db,$profile,$session;        
	
		$dashboards = [];
		foreach($profile->dashboards as $dashboarddata) {
			$dashboard_data_array = json_decode(stripslashes($dashboarddata['Value'])); # JSON decode the fetched data, so we can use it in PHP.
			if (!$session->isAdmin()) {
				if (isset($dashboard_data_array->private) && $dashboard_data_array->private=="on") {
					if ($dashboard_data_array->userid!=$session->userinfo["userid"]) {
						continue;
					}
				}
			}
			$dashboards[] = $dashboard_data_array->name;
		}
	
		$o = "<select class='form-control' name=\"dashboards[]\" MULTIPLE size=5>";
        $i=0;
		foreach($dashboards as $k => $v) {			
				$o.= "<option value=\"$v\">".$v."</option>\n";
		}
        $o.= "</select>";
        return $o;
    }
	
    /**
    * @desc This funtion will allow a user to select an interval at which the email is to be sent
    */
    function SelectInterval() {
        $o ="<select class='form-control' name=\"emailinterval\">\n";
        $o.="<option value=\"Daily\">"._DAILY."</option>\n";
        $o.="<option value=\"Weekly\">"._WEEKLY."</option>\n";
        $o.="<option value=\"Monthly\">"._MONTHLY."</option>\n";
        $o.="</select>";
        return $o;
    }
    
    /**
    * @desc This function validates the create form
    */
    function ValidateForm() {
        ?>
        <script type="text/javascript">
        function validate(form_id,email) {
           var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
           var address = document.forms[form_id].elements[email].value;
           if(reg.test(address) == false) {
              alert('<?php echo _INVALID_EMAIL;?>');
              return false;
           }
           if (document.forms[form_id].elements['reports[]'].value=="" && document.forms[form_id].elements['dashboards[]'].value=="") {
                alert('<?php echo _SELECT_AT_LEAST_ONE_REPORT;?>');
                return false;    
           }           
        }
        </script>
        <?php
    }
    
    /**
    * @desc This function will store the email alert in the database     
    */
    function StoreAlert($alertData,$lastsent="0") {
    	global $profile;

        # first give it a unique name
    	unset($alertData['key']);
        $name = "emailalerts.".md5(json_encode($alertData));        
        # now add a 'last sent' timestamp to the array
        $alertData["lastsent"] = $lastsent;
        # now serialize the array and store it
        $value = json_encode($alertData);
        $profile->SetOtherSettings($name,$value);                
    }
    
	function SetDateRange(){
		# Set the From and To for the reports
		$today = time();		
		$this->to = $today;
		
		if($this->alertdata["emailinterval"] == "Monthly"){
			$this->from = mktime(0,0,0,date("m")-1,1,date("Y")); # first day last full month
			$this->to = mktime(23,59,59,date("m"),0,date("Y")); # last day last full month
		} else if($this->alertdata["emailinterval"] == "Weekly"){
			$this->from = mktime(0,0,0,date("m",$today),date("d",$today)-7,date("Y",$today)); # 7 days ago
		} else {
			$this->from = mktime(0,0,0,date("m",$today),date("d",$today)-1,date("Y",$today));
		}
	}
	
    /**
    * @desc This function will send the email alerts for a given profile. If $test=true, email will be sent regardless of interval and last sent timestamp
    * @returns An array with feedback from the function, i.e. emails sent or any problems
    */
    function SendAlerts($test=false) {
        global $profile, $cm, $feedback;		
        $feedback = [];
		
		# load the alerts
        $alerts = $this->GetAlerts();
        if (count($alerts) === 0) {
            $feedback[] = _NOTHING_TO_SEND;
            return;    
        }
		
		# loop through each alert
        foreach($alerts as $a) {
			# Insert the data of the alert in a public variable
			$this->alertdata = $a;
			
			# Set the From and To for the reports
			$this->SetDateRange();
			
			# Do we need to send Infogprahics?
			if(!empty($a['infographics'])){
				if($test === true){
					$this->SendAllInfographics($a['email']); 

					if (empty($cm->active)) {						
						$note = str_replace("%X%", _DATE_TO . " logaholic.com",_INFOGRAPHICS_SEND_FOR_PROCESSING);
					} else{
						$note = str_replace("%X%","",_INFOGRAPHICS_SEND_FOR_PROCESSING);
					}					
					$feedback[] = $note;
				} else {
					$report = $this->ShouldWeSendInfographic($a);
					if($report != false){
						$this->SendInfographic($a['email'],$report);
						if (empty($cm->active)) {						
							$note = str_replace("%X%", _DATE_TO . " logaholic.com",_INFOGRAPHICS_SEND_FOR_PROCESSING);
						} else{
							$note = str_replace("%X%","",_INFOGRAPHICS_SEND_FOR_PROCESSING);
						}					
						$feedback[] = $note;

						unset($a['lastsent']);
						$this->StoreAlert($a, time() );
					}
				}				
			}
			
			# Start Checking for the reports.
            # check if we are good to go, skip we we are manually testing
            if ($this->ShouldWeSend($a) === false && $test === false) {
                continue;    
            }
			
			# if we have dashboards selected, send them to a server for rendering and email delivery
			if(!empty($a["dashboards"])){
				# remove any dashboards that are no longer available
				foreach($a["dashboards"] as $k => $dcheck) {
					if (!in_array($dcheck, $this->valid_dashboards)) {
						echoWarning("Alert contains an invalid dashboard ($dcheck), skipping");
						unset($a["dashboards"][$k]);
					}
				}
				$this->SendPDFDashboards($a['email'], $a["dashboards"]);
				if (empty($cm->active)) {
					$feedback[] = "Dashboards sent to logaholic.com for processing.";
				}
				if ($test===false) {
					$lastsent = time();
					unset($a['lastsent']);
					$this->StoreAlert($a,$lastsent);				
				}
			}
			
			# if we don't have any reports to send, just continue to the next alert
			if(empty($a["reports"]) && empty($a["infographics"]) && empty($a["dashboards"]) ){
				$feedback[] = _NO_REPORT_SEND;
				continue;				
			}
			
			if(empty($a["reports"])){
				continue;
			}
			
            # set up the message
            $subject=_LOGAHOLIC_EMAIL_ALERT." [";
            $mail_contents = "<html><head>";
            $mail_contents .= "<meta http-equiv='Content-Type' content='text/html; charset=UTF-8' /><meta http-equiv='X-UA-Compatible' content='IE=edge' />";
            $mail_contents.= $this->ApplyReportStyles();
            $mail_contents.= "</head><body>";
            $mail_contents.= _BEGIN_EMAIL." <strong>$profile->confdomain</strong>:<br />\n";
            # create all the selected reports
			
            foreach ($a['reports'] as $report) {
                $subject .= constant($report).", ";
				$mail_contents.= "<h2 class='box-title'>" . constant($report) . "</h2>";
				$mail_contents.= $this->BuildReport($report);
            }
            $mail_contents.= "<br /><br />Powered by <a href=\"http://www.logaholic.com/\">Logaholic Web Analytics</a><br /><br /></body></html>";
			
            $subject = substr($subject,0,-2)."]";
            # now send it
            if ($this->HtmlEmail($a['email'],$this->sender,$subject,$mail_contents)==true) {
				$notice = str_replace("%a",$a['email'],_SENT_EMAIL);
				$notice = str_replace("%b",$subject,$notice);

				$feedback[] = $notice;
				#now update the last sent timestamp
				if ($test==false) {
					$lastsent = time();
					unset($a['lastsent']);
					$this->StoreAlert($a,$lastsent);
				}
			}
        }
        return $feedback;
    }	
	
    /**
    * @desc This function will build a report based on the label that has been passed in
    */
    function BuildReport($report) {
        global $query, $data, $showfields, $mini,$reports, $labels;
		$labels = $report;
		
        ob_start();
		if (isset($labels) && isset($reports[$labels])) {
			# there is a class file for this report, let's use it
			$r = new $reports[$labels]["ClassName"]();
			$r->IgnReIm = 1; # even if there is a problem with the date we may never ever show the reimport box in de email alerts
			$r->labels = $labels;
			$r->from = $this->from;
			$r->to = $this->to;
			$r->DisplaySimpleTable();
		}
		$contents = ob_get_clean();
        return $contents;    
    }
	
	function BuildInfographic($report){
		global $profile, $cm;		
		$daterange = date("D d M",$report->from) . " to " . date("D d M",$report->to);
		if(!empty($cm) && method_exists($cm, 'OverwriteInfographic')){
			$content = $cm->OverwriteInfographic($report);
			if(!empty($content)){
				return $content;
			}
		}

		ob_start();

		echo "<div id='printer' class='page' style='width:600px;'>";
			echo "<div style='padding:20px; background-color:#FFF;'>";
				echo "<span style='color: rgb(40, 40, 40); font-size: 24px; font-family:Arial, sans-serif;'>Logaholic ". $report->label .": {$profile->confdomain}</span>";
				echo "<br/><span style='color: #898888; font-size: 20px; font-weight: bold;'>Last 7 days from {$daterange}</span>";
			echo "</div>";			
			$report->DisplayReport();
			echo "<div style='clear:both;'></div>";
		echo "</div>";
		
		$content = ob_get_clean();
		return $content;
	}
	
	/**
    * @desc This function will build a pdf based on the dashboard that has been passed in
    */
    function BuildPDF($dash) {
		# make sure we send the previous month
		return CreatePDFContent($dash,$this->from,$this->to);
    }
	
	/**
    * @desc This function will send all available infographics at one.
	* this happens when you manually send it
    */
	function SendAllInfographics($email){
		global $reports,$cm;

		$vlabel = (empty($cm->visitor_infographic_label)) ? "_VISITOR_INFOGRAPHIC" : $cm->visitor_infographic_label;
		$clabel = (empty($cm->content_infographic_label)) ? "_CONTENT_INFOGRAPHIC" : $cm->content_infographic_label;
		$tlabel = (empty($cm->traffic_infographic_label)) ? "_TRAFFIC_INFOGRAPHIC" : $cm->traffic_infographic_label;
		
		$report = new $reports[$vlabel]["ClassName"]();
		$report->displayReportButtons = false;
		$report->displayHeader = false;
		$this->SendInfographic($email,$report);
		
		$report = new $reports[$clabel]["ClassName"]();
		$report->displayReportButtons = false;
		$report->displayHeader = false;
		$this->SendInfographic($email,$report);
		
		$report = new $reports[$tlabel]["ClassName"]();
		$report->displayReportButtons = false;
		$report->displayHeader = false;
		$this->SendInfographic($email,$report);
	}
		
	/**
    * @desc This function will send the infographic content to logaholic.com, where it gets turned into a png and emailed.
    */
	function SendInfographic($email,$report){
		global $profile, $cm;
		
		$content = $this->BuildInfographic($report);
		$encodedcontent = base64_encode($content);
		
		$etxt = str_replace('%report%', $report->label, _INFOGRAPHIC_EMAIL_TXT);
		if (!empty($cm->logout_redirect_url)) {
			$etxt = "$etxt\n".$cm->logout_redirect_url;
		} else {
			$etxt = "$etxt\n".logaholic_url()."?conf=".$profile->profilename;
		}


		$data = array('content' => $encodedcontent,
					"version" => LOGAHOLIC_VERSION_NUMBER,
					"email" => $email,
					"label" => $report->label,
					"return_url" => logaholic_url(),
					"profile" => $profile->profilename,
					"confdomain" => $profile->confdomain,
					"emailtxt" => $etxt
					);
		if (!empty($cm->infograph_url)) { 
			$url = $cm->infograph_url; 
		} else {
			$url = 'https://software.logaholic.com/pdf/infographics.php';
		}
		Post($url,$data);
		$this->send ++;
	}
	
	
	/**
    * @desc This function will send the pdf content to logaholic.com, where it gets turned into a pdf and emailed.
    */
	function SendPDFDashboard($email,$dash){
		global $profile, $cm;
		
		$content = $this->BuildPDF($dash);
		$encodedcontent = base64_encode($content);
		
		$etxt = str_replace('%report%', $dash." Dashboard", _INFOGRAPHIC_EMAIL_TXT);
		if (!empty($cm->logout_redirect_url)) {
			$etxt = "$etxt\n".$cm->logout_redirect_url;
		} else {
			$etxt = "$etxt\n".logaholic_url()."?conf=".$profile->profilename;
		}

		$data = array('content' => $encodedcontent,
					"version" => LOGAHOLIC_VERSION_NUMBER,
					"email" => $email,
					"label" => $dash,
					"return_url" => logaholic_url(),
					"profile" => $profile->profilename,
					"confdomain" => $profile->confdomain,
					"name" => $profile->confdomain.str_replace(" ","_",$dash).".pdf",
					"emailtxt" => $etxt
					);
		if (!empty($cm->pdf_emailalert_url)) { 
			$url = $cm->pdf_emailalert_url; 
		} else {
			$url = 'https://software.logaholic.com/pdf/pdf7.php';
		}
		Post($url,$data);
		$this->send ++;
	}
	
	function SendPDFDashboards($email, $dashboards) {
		foreach($dashboards as $dash) {
			$this->SendPDFDashboard($email,$dash);
		}	
	}	
    
    /**
    * @desc This function will send an html formatted email
    */
    function HtmlEmail($to,$from,$subject,$contents) {
    	global $feedback;
        $bad = false;
		$headers  = "MIME-Version: 1.0\r\n";
        $headers .= "Content-type: text/html; charset=UTF-8\r\n";
        $neatmail=trim($to);       
		ob_start();
	    if (mail($neatmail, "$subject","$contents","From: $from <$from> \n" . $headers) ===false) {
			$bad=true;
		}
		$mess= ob_get_clean();
		if($bad === true) {
			$feedback[] = _FAILED_TO_SEND;
			return false;
		}
		
		$this->send ++;
        return true;        
    }
    
    /**
    * @desc This function will list the email alerts that have been created for the selected profile
    */
    function ShowAlerts() {
        $alerts = $this->GetAlerts();
        if (count($alerts) == 0) {
            # no alerts have been defined yet
            return;    
        } 
        echo "<h3>"._ACTIVE_EMAIL_ALERTS.":</h3>";
        echo "<table id=\"alerttable\" cellspacing=\"0\"><tr><th>&nbsp;</th><th>"._EMAIL."</th><th>"._INTERVAL."</th><th>"._INFOGRAPHICS."</th><th>"._DASHBOARDS."</th><th>"._REPORTS."</th><th>"._LAST_SENT."</th></tr>";
        foreach($alerts as $a) {
        	if (!empty($a['dashboards'])) {
        		if ($this->isDashPrivate($a['dashboards'])) {
        			continue;
        		}
        	}
			$infographs = (empty($a['infographics'])) ? "off" : $a['infographics'];
            echo "<tr><td>".Button("?conf=$this->profilename&del={$a['key']}",_DELETE)."</td><td>{$a['email']}</td><td>{$a['emailinterval']}</td><td>{$infographs}</td><td>";
            
			$i=0;
			# dashboards
			$a['dashboards'] = (empty($a['dashboards'])) ? [] : $a['dashboards'];
            foreach ($a['dashboards'] as $dash) {
                if ($i > 5) { echo ", ..."; break; }
                if ($i > 0) { echo ", "; }
                echo $dash;
                $i++;    
            }            
            echo "</td><td>";
			
			$i=0;
			# reports
			$a['reports'] = (empty($a['reports'])) ? [] : $a['reports'];
            foreach ($a['reports'] as $report) {
                if ($i > 5) { echo ", ..."; break; }
                if ($i > 0) { echo ", "; }
                echo constant($report);
                $i++;    
            }            
            echo "</td><td>";
            if ($a['lastsent']==0) { echo _NEVER; } else { echo date("Y-m-d H:i:s",$a['lastsent']); }
            echo "</td></tr>\n";   
        }
        echo "</table>";            
    }

    function isDashPrivate($dash) {    	
    	global $profile, $session, $running_from_command_line;
    	$dash = (empty($dash)) ? [] : $dash;
    	foreach($profile->dashboards as $dashboarddata) {
			$dashboard_data_array = json_decode(stripslashes($dashboarddata['Value'])); # JSON decode the fetched data, so we can use it in PHP.			
			if ($running_from_command_line!=true) {
				if (!$session->isAdmin()) {
					if (in_array($dashboard_data_array->name, $dash)) {				
						if (isset($dashboard_data_array->private) && $dashboard_data_array->private=="on") {
							if ($dashboard_data_array->userid!=$session->userinfo["userid"]) {
								return true;
							}
						}
					}
				}
			}				
		}
		return false;
            
    }
    
    /**
    * @desc This function gets an array of email alerts from the database    
    */
    function GetAlerts() {
        global $profile;
        $alerts = [];
        $i = 0;
        foreach ($profile->other_settings as $key => $value) {
        	if(strpos($key,"emailalerts.") !== false && strpos($key,'INFO.') === false){
        		$alerts[$i] = json_decode($value,true);
        		$alerts[$i]['key'] = $key;
        		$i ++;
        	}
        }
        return $alerts;    
    }
    
    /**
    * @desc This function deletes an alert
    */
    function DeleteAlert($alert) {
        global $profile;
        unset($profile->other_settings[$alert]);
        # in case it is a infographic remove the additional setting
        if(!empty($profile->other_settings['INFO.'.$alert])){
        	unset($profile->other_settings['INFO.'.$alert]);
        }
        $profile->Save();
    }
    
    /**
    * @desc This function gets the email address of the first admin user, which is used as the sender of any emails
    */
    function AdminEmail() {
        global $db;
        $q = $db->Execute("select email,username from ".TBL_USERS." where isadmin = '1' order by userid limit 1");
        return $q->FetchRow();           
    }
    
    /**
    * @desc This function tells the user from which address emails will be sent and allows the user to test/send alerts
    */
    function FootNote() {
    	global $cm;
        $message = "<a class='btn btn-sm btn-default send-alerts-now' style='float:right;margin-top:15px;'>". _SEND_EMAIL_ALERTS_NOW ."</a>";
        

        $message.= str_replace("%a",$this->sender,_FOOTNOTE);
        $altemail = "noreply@".@php_uname("n");
        $message = str_replace("%b",$altemail,$message);

        //echoNotice("<p>"._EMAIL_ALERTS_EXPLAIN . "</p><p> "._EMAIL_ALERTS_EXPLAIN_2 . "</p>", "padding: 20px 10px;");
        
        if (empty($cm->active)) {
        	echoNotice("&nbsp;<br>".$message);
			echoNotice("&nbsp;<br>"."PDF reports are sent to Logaholic.com for rendering (encoded). They will be sent from suport@logaholic.com");
		}
    }
    
    /**
    * @desc This function checks to see if an alert should be sent or not, based on the interval and the last sent timestamp
    */    
    function ShouldWeSend($alert) {
        if (empty($alert['lastsent']) || $alert['lastsent']== 0) {
            return true;
        }
        if ($alert['emailinterval']=="Daily" && (time() - $alert['lastsent']) >= 86400) {
            return true;
        }
        if ($alert['emailinterval']=="Weekly" && (time() - $alert['lastsent']) >= (86400 *7)) {
            return true;
        }
        if ($alert['emailinterval']=="Monthly" && date("m",time())!= date("m",$alert['lastsent'])) {
            return true;
        }
        return false;        
    }
    
	/**
    * @desc This function checks to see if an infograhpic should be sent or not, based on the interval and the last sent timestamp
    */
	function ShouldWeSendInfographic($alert){
		global $profile, $reports, $cm;

		$setting_key = 'INFO.'.$alert['key'];

		$check = $profile->GetOtherSettings($setting_key,"");
		$check = json_decode($check,true);
		
		# Setup Array of what to save.
		$save["time"] = time();
		
		# set to the correct labels
		if(empty($cm->visitor_infographic_label)){
			$vlabel = "_VISITOR_INFOGRAPHIC";
		} else {
			$vlabel = $cm->visitor_infographic_label;
			# Correct the check report
			if($check["report"] == "_VISITOR_INFOGRAPHIC"){
				$check["report"] = $cm->visitor_infographic_label;
			}
		}

		if(empty($cm->content_infographic_label)){
			$clabel = "_CONTENT_INFOGRAPHIC";
		} else {
			$clabel = $cm->content_infographic_label;
			# Correct the check report
			if($check["report"] == "_CONTENT_INFOGRAPHIC"){
				$check["report"] = $cm->content_infographic_label;
			}
		}

		if(empty($cm->traffic_infographic_label)){
			$tlabel = "_TRAFFIC_INFOGRAPHIC";
		} else {
			$tlabel = $cm->traffic_infographic_label;
			# Correct the check report
			if($check["report"] == "_TRAFFIC_INFOGRAPHIC"){
				$check["report"] = $cm->traffic_infographic_label;
			}
		}

		if(!empty($check)){
			# set the time to check to 00:00:00 m d y
			$check["time"] = mktime(0,0,0, date("m",$check["time"]),date("d",$check["time"]),date("Y",$check["time"]) );
		}

		# Now getting to check which need to send based on timestamp and previous mail.
		# Mail Order : 
		#	1 - _VISITOR_INFOGRAPHIC => On first time || (86400 * 3) After last mail
		#	2 - _CONTENT_INFOGRAPHIC => (86400 * 2) After last mail
		#	3 - _TRAFFIC_INFOGRAPHIC => (86400 * 2) After last mail	
		
		if(empty($check)){
			$report = new $reports[$vlabel]["ClassName"]();
			$save["report"] = $vlabel;
			$profile->SetOtherSettings($setting_key,json_encode($save));
		}
		else if( $check["report"] == $tlabel && ($save["time"] - $check["time"]) >= (86400*3) ){
			$report = new $reports[$vlabel]["ClassName"]();
			$save["report"] = $vlabel;
			$profile->SetOtherSettings($setting_key,json_encode($save));
		}
		else if( $check["report"] == $vlabel && ($save["time"] - $check["time"]) >= (86400*2) ){
			$report = new $reports[$clabel]["ClassName"]();
			$save["report"] = $clabel;
			$profile->SetOtherSettings($setting_key,json_encode($save));
		}
		else if( $check["report"] == $clabel && ($save["time"] - $check["time"]) >= (86400*2) ){
			$report = new $reports[$tlabel]["ClassName"]();
			$save["report"] = $tlabel;
			$profile->SetOtherSettings($setting_key,json_encode($save));
		} else {
			$report = false;
		}
		
		if($report != false){
			$report->displayReportButtons = false;
			$report->displayHeader = false;
		}	
		return $report;
	}
	
    /**
    * @desc This function will apply email freindly styles to the report tables
    */
    function ApplyReportStyles() {
        $style="<style type=\"text/css\">
        BODY { font-family:Arial; font-size:12px; }
        .report_title { font-size: 16px; font-weight: bold; margin-top:25px; padding-left:2px; }
        .date_line { font-size:11px; padding-left:3px; }
        TABLE.report_table { border: 1px solid silver; border-collapse: collapse; width:100%; font-size:12px; }
        .report_table TH { background-color: #E0E0E0; border: 1px solid silver; text-align: left; padding:4px 4px 4px 6px; }
        .tabletotalcolor { background-color: #E0E0E0; border: 1px solid silver; text-align: left; padding:4px 4px 4px 6px; }
        .report_table TD { border: 1px solid silver; padding:6px; vertical-align: top; }        
        </style>";
        return $style;        
    }
}
?>
