<?php
	class Notification {
		
		private $ctrl;
		private $config;
		private $mail;
		private $db;
		private $sms;
		private $wa;
		
		public $fromName;
		public $fromAddress;
		public $smsAuth;
		private $skebby;
		
		function __construct($ctrl=null, $SMTPDebug=0) {
			global $db, $mailer, $config; //App/boostrap.php
			$this->mail = $mailer; 
			$this->ctrl = $ctrl;
			$this->config = $config; 
			$this->db = $db;
			$this->smsAuth = null;
			
			$this->mail->SMTPDebug = $SMTPDebug;
			$this->mail->isSMTP();
			//$mail->mail->CharSet = 'UTF-8';
			$this->mail->Host = $this->config['settings']['smtp']['host'];
			$this->mail->SMTPAuth = true;
			$this->mail->Username = $this->config['settings']['smtp']['username'];
			$this->mail->Password = $this->config['settings']['smtp']['password'];
			$this->mail->SMTPSecure = $this->config['settings']['smtp']['secure'];
			$this->mail->Port = $this->config['settings']['smtp']['port'];
			$this->mail->isHTML(true);
			
			$this->fromAddress = $this->config['settings']['smtp']['from-address'];
			$this->fromName = $this->config['settings']['smtp']['from-name'];
		}
		
		public function sendEmail($to='', $subject='', $body='', $mailID='', $from=[], $attachs=[]) {
			
			$fromName = $this->fromName;
			$fromAddress = $this->fromAddress;
			
			if (!empty($from)) {
				if (isset($from['fromAddress']) && isset($from['fromName'])) {
					$fromName = $from['fromName'];
					$fromAddress = $from['fromAddress'];
				}
			}
			
			$this->mail->setFrom($fromAddress, $fromName);
			$this->mail->addAddress($to);
			
			if (is_array($attachs) && !empty($attachs)) {
				foreach($attachs as $attach) {
					$this->mail->addAttachment($attach['path'], $attach['name']);
				}
			}
			
			$this->mail->Subject = $subject;
			$this->mail->Body    = $body;
			$this->mail->AltBody = $this->setHtmlToPlainText($body);
			
			$mailResult = 0;
			$mailErrorInfo = '';
			if ($this->mail->send()) {
				$mailResult = 1;
			} else {
				$mailErrorInfo = $this->mail->ErrorInfo;
			}
			
			
			$this->logEmail($mailID, $fromAddress, $to, $subject, $body, $mailResult, $mailErrorInfo);
			
			$this->mail->clearAddresses();
			$this->mail->clearAttachments();
		}
		
		public function loginSMS() {
			$endpoint = $this->config['settings']['skebby']['endpoint'];
			$username = $this->config['settings']['skebby']['username'];
			$password = $this->config['settings']['skebby']['password'];
			$sender = $this->config['settings']['skebby']['sender'];
			
			$this->skebby = new Skebby($username, $password, $endpoint, $sender);
			$this->smsAuth = $this->skebby->login();
			return $this->smsAuth;
		}
		
		public function sendSMS($message, $recipients=[]) {
			$result = $this->skebby->sendSMS($message, $recipients);
			$this->logSMS($message, $recipients, $result);
		}
		
		public function receiveSMS($idSim='', $limit=100, $auth=[]) {
			$result = $this->skebby->receiveSMS($idSim, $limit, $auth);
			return $result;
		}
		
		public function setNotificationAsSent($queueId=0) {
			return $this->db->where('id', $queueId)->update('requests_messages_queue', ['sent_status'=>1, 'sent_at'=>date('Y-m-d H:i:s')]);
		}
		
		public function setSurveyNotificationAsSent($queueId=0) {
			return $this->db->where('id', $queueId)->update('survey_queue', ['msg_sent'=>1, 'msg_sent_date'=>date('Y-m-d H:i:s')]);
		}
		
		private function setHtmlToPlainText($html='') {
			$breaks = array("<br />","<br>","<br/>");
			$html = str_ireplace($breaks, "\r\n", $html);
			
			return strip_tags($html);
		}
		
		private function logSMS($msg='', $recipients=[], $result=[]) {
			$id = uniqid();
			$user = [];
			
			if (empty($recipients)) {
				return false;
			} else {
				
				$recipients = !is_array($recipients) ? [$recipients] : $recipients;
				
				foreach($recipients as $recipient) {
					$number = str_replace('+', '', $recipient);
					$user = $this->db->where('mobile_number', $number)->getOne('users', 'id');
					$this->db->insert('log_notifications', [
						'id' => $id,
						'user_id' => isset($user['id']) ? $user['id'] : -1,
						'notif_type' => 'sms',
						'phone_to' => $recipient,
						'phone_msg' => $msg,
						'request_result' => isset($result['result']) && $result['result'] == 'OK' ? 1 : 0,
						'request_error_info' => isset($result['result']) && $result['result'] == 'ERR' ? json_encode($result) : null,
						'created_at' => date('Y-m-d H:i:s')
					]);
				}
				
			}
			
			return $id;
		}
		
		private function logEmail($mailId='', $from='', $to='', $subject='', $body='', $result=0, $errorInfo='') {
			$user = $this->db->where('email', trim($to))->getOne('users', 'id');
			$this->db->insert('log_notifications', [
				'id' => $mailId,
				'user_id' => isset($user['id']) ? $user['id'] : -1,
				'notif_type' => 'email',
				'mail_from' => $from,
				'mail_to' => $to,
				'mail_subject' => $subject,
				'mail_body' => $body,
				'request_result' => $result,
				'request_error_info' => $errorInfo,
				'created_at' => date('Y-m-d H:i:s')
			]);
			
			return $mailId;
		}
	}