<?php
require_once 'app/class-alert-manager.php';
require_once 'app/class-lov-manager.php';
require_once 'includes/PHPMailer/PHPMailerAutoload.php';

/**
 * Alerts Context
 *
 * Context for user alerts managment
 * 
 * @author tmouzinho - Advantis Solutions
 * @version 1.0.1
 * @package Backend\Alerts
 */
class context_alerts extends context {
	public $contextname = "alerts";
	
	/**
	 * Constructor & Authorization
	 */
	function context_alerts() {
		//main::check_auth_session ();
	}
	
	/**
	 * default action
	 * shows live alerts
	 */
	function index() {
		$this->live ();
	}
	
	/**
	 * Shows live alerts for session user
	 */
	function live() {
		$em = new AlertManager ();
		$alert_list = $em->get_user_live_alerts ();
		
		$lovm = new LovManager ();
		$list_contexts = $lovm->getLov_AlertContexts ();
		
		$simpleListContexts = array ();
		foreach ( $list_contexts as $lc ) {
			$simpleListContexts [$lc->code] = $lc->descriptioncode;
		}
		
		$list_alertStatus = $lovm->getLov_AlertStatus ();
		
		$this->screen ( "/alerts/live", array (
				'page' => 'live',
				'list' => $alert_list,
				'contexts' => $simpleListContexts,
				'status' => $list_alertStatus 
		) );
	}
	
	/**
	 * Shows archived alerts for session user
	 */
	function history() {
		$em = new AlertManager ();
		$alert_list = $em->get_user_history_alerts ();
		
		$lovm = new LovManager ();
		$list_contexts = $lovm->getLov_AlertContexts ();
		
		$simpleListContexts = array ();
		foreach ( $list_contexts as $lc ) {
			$simpleListContexts [$lc->code] = $lc->descriptioncode;
		}
		
		$list_alertStatus = $lovm->getLov_AlertStatus ();
		$simpleListStatus = array ();
		foreach ( $list_alertStatus as $ls ) {
			$simpleListStatus [$ls->id] = $ls->descriptioncode;
		}
		$this->screen ( "/alerts/history", array (
				'page' => 'history',
				'list' => $alert_list,
				'contexts' => $simpleListContexts,
				'status' => $simpleListStatus 
		) );
	}
	
	/**
	 * Saves alert status editing via POST
	 */
	function save() {
		try {
			
			$needrollback = false;
			Transaction::beginTransaction ();
			
			foreach ( $_POST as $key => $value ) {
				
				$pieces = explode ( "_", $key );
				
				if ($pieces [0] == "alertstatus") {
					
					$id = $pieces [1];
					
					if ($_POST ['changed_' . $id]) {
						
						$obj = new Entity ( "alerts" );
						
						$obj->id = $id;
						
						$obj->statuscodeid = $value;
						
						$obj->save ();
					}
				}
			}
			
			if ($needrollback) {
				Transaction::rollback ();
			} else {
				Transaction::commit ();
			}
		} catch ( Exception $exp ) {
			Transaction::rollback ();
			dump_errorlog ( 'Alerts', 'savealerts', $exp->getMessage () );
		}
		
		$this->live ();
	}
	
	function sendEmails() {
		
		$list = array();
		
		$em = new EntityManager ( "email_alertlist" );
		
		$list = $em->load();
		
		
		foreach ($list as $item ) {
			
			$mail = new PHPMailer;
			
			//$mail->SMTPDebug = 3;                               // Enable verbose debug output
			
			$mail->isSMTP();                                      // Set mailer to use SMTP
			$mail->Host = __SMTP_SERVER;  // Specify main and backup SMTP servers
			$mail->SMTPAuth = __SMTP_USE_AUTH;// Enable SMTP authentication     
			if (__SMTP_USE_AUTH) {
			$mail->Username = __SMTP_USER;                 // SMTP username
			$mail->Password = __SMTP_PASS;                           // SMTP password
			}
			//$mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
			$mail->Port = __SMTP_PORT;                             // TCP port to connect to
			
			$mail->setFrom(__SMTP_FROM_EMAIL, __SMTP_FROM_NAME);
			$mail->addAddress($item->email, '');     // Add a recipient
			
			$mail->addReplyTo(__SMTP_REPLY_EMAIL, __SMTP_REPLY_NAME);
			//$mail->addCC('cc@example.com');
			//$mail->addBCC('bcc@example.com');
			
			//$mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
			
			//$mail->isHTML(true);                                  // Set email format to HTML
			
			$mail->Subject = $item->subject;
			
			$message = html_entity_decode($item->alerttype_description);
			$message = str_replace("[contextdesc]", $item->alert_context,$message);
			
			$mail->Body    = $message;
			
			$mail->AltBody = $message;
			
			if(!$mail->send()) {
				echo 'Message could not be sent.';
				echo 'Mailer Error: ' . $mail->ErrorInfo;
				
			} else {
				
				echo 'Message has been sent<br>';
				
				$ae = new Entity ("alerts",$item->alert_id );
				
				$ae->sendmaildate = date("Y-m-d H:i:s");
				
				$ae->save();
			}
		}
		
		exit();
	}
}

?>