<?php
	class Checkmail {
		
		private $config = null;
		private $mbox = null;
		private $email_list = [];
		
		function __construct($cofig) {			
			$this->config = $cofig;
		}
		
		public function openImap() {
			$this->mbox = imap_open($this->config['settings']['imap']['connection'].'INBOX', $this->config['settings']['smtp']['username'], $this->config['settings']['smtp']['password']);
		}
		
		public function closeImap() {
			imap_close($this->mbox);
			$this->mbox = null;
		}
		
		public function fetchFailedOverview() {
			
			$MC = imap_check($this->mbox);
			$result = imap_fetch_overview($this->mbox, "1:{$MC->Nmsgs}", 0);
			
			if (is_array($result)) {
				foreach ($result as $overview) {
	    			if ($this->filterSubject($overview->subject, 'Delivery Status Notification')) {
	    				$this->email_list[] = $overview->msgno;
	    			}
	    		}
			}
						
			return $this->email_list;
		}
		
		//$range = "1,2,3,4"
		public function moveMessageTo($range, $to='') {
			return imap_mail_move($this->mbox,  $range , $to);
		}
		
		public function listMailBoxes() {
			$mailboxes = imap_list($this->mbox, $this->config['settings']['imap']['connection'], '*');
			return $mailboxes;
		}
		
		public function readEmail($number) {
			return imap_qprint(imap_body($this->mbox, $number));
		}
		
		public function getSurveyUUID($mail_body='', $check_string='', $length=36) {
			$start = strpos($mail_body, $check_string)+strlen($check_string);
			
			return substr($mail_body, $start, $length);
		}
		
		private function emptyEmailList() {
			$this->email_list = [];
		}
		
		public function markDelete($number) {
			imap_delete($this->mbox, $number);
		}
		
		public function expungeDelete() {
			imap_expunge($this->mbox);
		}
		
		private function filterSubject($subject='', $filter='') {
			if (strpos($subject, $filter) !== false)
				return true;
			else
				return false;
		}
		
	}