<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminEmails extends pjAdmin
{
	public function pjActionIndex()
	{
		$this->checkLogin();
		
		if ($this->isAdmin())
		{
			if(isset($_POST['send_email']))
			{
				$err = 'AM02';
				
				$email_arr = $this->pjActionGetEmails($_POST);
				
				$pjEmail = new pjEmail();
				if ($this->option_arr['o_send_email'] == 'smtp')
				{
					$pjEmail
						->setTransport('smtp')
						->setSmtpHost($this->option_arr['o_smtp_host'])
						->setSmtpPort($this->option_arr['o_smtp_port'])
						->setSmtpUser($this->option_arr['o_smtp_user'])
						->setSmtpPass($this->option_arr['o_smtp_pass'])
						->setSender($this->option_arr['o_smtp_user'])
					;
				}
				$pjEmail->setContentType('text/html');
				
				$from_email = $this->getAdminEmail();
				
				$subject = $_POST['subject'];
				$search = array('{Email}', '{Name}');
				foreach($email_arr as $email => $name)
				{
					$replace = array($email, $name);
					$message = str_replace($search, $replace, $_POST['message']);
					
					$pjEmail
						->setTo($email)
						->setFrom($from_email)
						->setSubject($subject)
						->send($message);
					$err = 'AM01';
				}

				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminEmails&action=pjActionIndex&err=$err");
			}else{
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('tinymce.min.js', PJ_THIRD_PARTY_PATH . 'tinymce/');
				$this->appendJs('pjAdminEmails.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionGetClients()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			$response['cnt'] = 0;
			
			$email_arr = $this->pjActionGetEmails($_POST);
			
			$response['cnt'] = count($email_arr);
			
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionGetEmails($post)
	{
		$email_arr = array();
		if(isset($post['admin']))
		{
			$arr = pjUserModel::factory()
				->where('role_id', 1)
				->findAll()
				->orderBy("t1.id ASC")
				->limit(1)
				->getData();
			if(!empty($arr))
			{
				$email_arr[$arr[0]['email']] = $arr[0]['name'];
			}
		}
			
		$where_arr = array();
		if(isset($post['pending']))
		{
			$where_arr[] = "t1.status = 'pending'";
		}
		if(isset($post['confirmed']))
		{
			$where_arr[] = "t1.status = 'confirmed'";
		}
		if(isset($post['cancelled']))
		{
			$where_arr[] = "t1.status = 'cancelled'";
		}
		if(!empty($where_arr))
		{
			$reservation_arr = pjReservationModel::factory()
				->where("(".join(" OR ", $where_arr).")")
				->findAll()
				->getData();
			
			foreach($reservation_arr as $k => $v)
			{
				if(!array_key_exists($v['c_email'], $email_arr))
				{
					$email_arr[$v['c_email']] = $v['c_name'];
				}
			}
		}
		return $email_arr;
	}
}
?>