<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminEnquiries extends pjAdmin
{
	public function pjActionCreate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isOwner() || $this->isEditor())
		{
			if (isset($_POST['enquiry_create']))
			{
				$data = array();
				$data['date_from'] = pjUtil::formatDate($_POST['date_from'], $this->option_arr['o_date_format']);
				$data['date_to'] = pjUtil::formatDate($_POST['date_to'], $this->option_arr['o_date_format']);
				
				$pjEnquiryModel = pjEnquiryModel::factory();
				$post = array_merge($_POST, $data);

				if (!$pjEnquiryModel->validates($post))
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminEnquiries&action=pjActionIndex&err=AE04");
				}

				$insert_id = $pjEnquiryModel->setAttributes($post)->insert()->getInsertId();
				if ($insert_id !== false && (int) $insert_id > 0)
				{
					if (isset($_POST['i18n']))
					{
						pjMultiLangModel::factory()->saveMultiLang($_POST['i18n'], $insert_id, 'pjEnquiry');
					}
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminEnquiries&action=pjActionIndex&err=AE03");
				} else {
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminEnquiries&action=pjActionIndex&err=AE04");
				}
			}
			
			$pjListingModel = pjListingModel::factory();
			if ($this->isOwner())
			{
				$pjListingModel->where('t1.owner_id', $this->getUserId());
			}
			$listing_arr = $pjListingModel
				->select('t1.id, t1.listing_refid, t2.content AS title')
				->join('pjMultiLang', "t2.model='pjListing' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
				->orderBy('title ASC')
				->findAll()->getData();
			
			$listing_arr = pjSanitize::clean($listing_arr);
			$this->set('listing_arr', $listing_arr);

			
			$this->appendJs('chosen.jquery.min.js', PJ_THIRD_PARTY_PATH . 'harvest/chosen/');
			$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . 'harvest/chosen/');

			$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
			$this->appendJs('pjAdminEnquiries.js');
		} else {
			$this->set('status', 2);
		}
	}

	public function pjActionDeleteEnquiry()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			if (pjEnquiryModel::factory()->setAttributes(array('id' => $_GET['id']))->erase()->getAffectedRows() == 1)
			{
				pjMultiLangModel::factory()->where('model', 'pjEnquiry')->where('foreign_id', $_GET['id'])->eraseAll();
				$response['code'] = 200;
			} else {
				$response['code'] = 100;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionDeleteEnquiryBulk()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				pjEnquiryModel::factory()->whereIn('id', $_POST['record'])->eraseAll();
				pjMultiLangModel::factory()->where('model', 'pjEnquiry')->whereIn('foreign_id', $_POST['record'])->eraseAll();
			}
		}
		exit;
	}
	
	public function pjActionExportEnquiry()
	{
		$this->checkLogin();
		
		if (isset($_POST['record']) && is_array($_POST['record']))
		{
			$arr = pjEnquiryModel::factory()->whereIn('id', $_POST['record'])->findAll()->getData();
			$csv = new pjCSV();
			$csv
				->setHeader(true)
				->setName("Enquiries-".time().".csv")
				->process($arr)
				->download();
		}
		exit;
	}
	
	public function pjActionStatusEnquiry()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0 && isset($_GET['status']) && in_array($_GET['status'], array('Confirmed', 'New')))
			{
				pjEnquiryModel::factory()->whereIn('id', $_POST['record'])->modifyAll(array('status' => $_GET['status']));
			}
		}
		exit;
	}
	
	public function pjActionGetMessage()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$listing_arr = pjListingModel::factory()
				->select("t2.content AS confirm_tokens, t3.content AS confirm_subject")
				->join('pjMultiLang', "t2.model='pjListing' AND t2.foreign_id=t1.id AND t2.locale='".$this->getLocaleId()."' AND t2.field='confirm_tokens'", 'inner')
				->join('pjMultiLang', "t3.model='pjListing' AND t3.foreign_id=t1.id AND t3.locale='".$this->getLocaleId()."' AND t3.field='confirm_subject'", 'inner')
				->find($_POST['listing_id'])->getData();

			$tokens = pjAppController::getTokens($_POST, $this->option_arr);

			$response = array(
				'subject' => str_replace($tokens['search'], $tokens['replace'], @$listing_arr['confirm_subject']),
				'body' => str_replace($tokens['search'], $tokens['replace'], @$listing_arr['confirm_tokens'])
			);
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionGetEnquiry()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjEnquiryModel = pjEnquiryModel::factory()->join('pjListing', 't2.id=t1.listing_id', 'inner');
			
			if (isset($_GET['listing_id']) && (int) $_GET['listing_id'] > 0)
			{
				$pjEnquiryModel->where('t1.listing_id', $_GET['listing_id']);
			}
				
			if (isset($_GET['status']) && !empty($_GET['status']))
			{
				$pjEnquiryModel->where('t1.status', $_GET['status']);
			}
			
			if (isset($_GET['q']) && !empty($_GET['q']))
			{
				$q = $pjEnquiryModel->escapeString($_GET['q']);
				$q = str_replace(array('%', '_'), array('\%', '\_'), trim($q));
				$pjEnquiryModel->where("(t1.name LIKE '%$q%' OR t1.email LIKE '%$q%' OR t1.phone LIKE '%$q%' OR t1.notes LIKE '%$q%')");
			}
			
			if ($this->isOwner())
			{
				$pjEnquiryModel->where('t2.owner_id', $this->getUserId());
			}
			
			$column = 'created';
			$direction = 'DESC';
			if (isset($_GET['direction']) && isset($_GET['column']) && in_array(strtoupper($_GET['direction']), array('ASC', 'DESC')))
			{
				$column = $_GET['column'];
				$direction = strtoupper($_GET['direction']);
			}

			$total = $pjEnquiryModel->findCount()->getData();
			$rowCount = isset($_GET['rowCount']) && (int) $_GET['rowCount'] > 0 ? (int) $_GET['rowCount'] : 10;
			$pages = ceil($total / $rowCount);
			$page = isset($_GET['page']) && (int) $_GET['page'] > 0 ? intval($_GET['page']) : 1;
			$offset = ((int) $page - 1) * $rowCount;
			if ($page > $pages)
			{
				$page = $pages;
			}

			$data = $pjEnquiryModel->select("t1.id, t1.listing_id, t1.date_from, t1.date_to, t1.status, t1.name, t1.phone,
				DATE_FORMAT(t1.created, '%Y-%m-%d') AS `created`, t2.listing_refid, t3.content AS `listing_title`")
				->join('pjMultiLang', sprintf("t3.model='pjListing' AND t3.foreign_id=t1.listing_id AND t3.field='title' AND t3.locale='%u'", $this->getLocaleId()), 'left outer')
				->orderBy("$column $direction")->limit($rowCount, $offset)->findAll()->getData();
				
			foreach ($data as $k => $v)
			{
				$data[$k]['date_from'] = pjUtil::formatDate($v['date_from'], 'Y-m-d', $this->option_arr['o_date_format']);
				$data[$k]['date_to'] = pjUtil::formatDate($v['date_to'], 'Y-m-d', $this->option_arr['o_date_format']);
			}

			$data = pjSanitize::clean($data);
			pjAppController::jsonResponse(compact('data', 'total', 'pages', 'page', 'rowCount', 'column', 'direction'));
		}
		exit;
	}
	
	public function pjActionIndex()
	{
		$this->checkLogin();
			
		if ($this->isAdmin() || $this->isOwner() || $this->isEditor())
		{
			$pjListingModel = pjListingModel::factory()
				->select('t1.id, t1.listing_refid, t2.content AS title')
				->join('pjMultiLang', "t2.model='pjListing' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
				->orderBy('title ASC, t1.listing_refid ASC');
			if ($this->isOwner())
			{
				$pjListingModel->where('t1.owner_id', $this->getUserId());
			}
			$listing_arr = $pjListingModel->findAll()->getData();
			$listing_arr = pjSanitize::clean($listing_arr);
			$this->set('listing_arr', $listing_arr);

			$this->appendJs('chosen.jquery.min.js', PJ_THIRD_PARTY_PATH . 'harvest/chosen/');
			$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . 'harvest/chosen/');
			
			$this->appendJs('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
			$this->appendJs('pjAdminEnquiries.js');
			$this->appendJs('index.php?controller=pjAdmin&action=pjActionMessages', PJ_INSTALL_URL, true);
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionSaveEnquiry()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjEnquiryModel = pjEnquiryModel::factory();
			
			$enquiry = $pjEnquiryModel
				->select('t1.*, t2.owner_id')
				->join('pjListing', 't2.id=t1.listing_id')
				->find($_GET['id'])->getData();
			if (in_array($_POST['column'], array('date_from', 'date_to')))
			{
				$_POST['value'] = pjUtil::formatDate($_POST['value'], $this->option_arr['o_date_format']);
			}
			$pjEnquiryModel->reset()->set('id', $_GET['id'])->modify(array($_POST['column'] => $_POST['value']));
		}
		exit;
	}
	
	public function pjActionSendMessage()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$Email = new pjEmail();
			pjAppController::setFields($this->getLocaleId());
			$Email
				->setTo($_POST['email'])
				->setFrom($_POST['email'])
				->setSubject($_POST['subject'])
			;
			
			if ($this->option_arr['o_send_email'] == 'smtp')
			{
				$Email
					->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'])
				;
			}
			
			$Email->send($_POST['message']);
		}
		exit;
	}
		
	public function pjActionUpdate()
	{
		$this->checkLogin();

		if ($this->isAdmin() || $this->isOwner() || $this->isEditor())
		{
			$pjEnquiryModel = pjEnquiryModel::factory();

			$enquiry = $pjEnquiryModel
				->select("t1.*")
				->join('pjListing', 't2.id=t1.listing_id')
				->find($_REQUEST['id'])->getData();

			if (empty($enquiry) || count($enquiry) == 0)
			{
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminEnquiries&action=pjActionIndex&err=AE08");
			}
			$enquiry['i18n'] = pjMultiLangModel::factory()->getMultiLang($enquiry['id'], 'pjEnquiry');
			
			$property = pjListingModel::factory()->find($enquiry['listing_id'])->getData();
			
			if (empty($property) || count($property) == 0)
			{
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminEnquiries&action=pjActionIndex&err=AE09");
			}
			
			if ($this->isOwner())
			{
				if ($property['owner_id'] != $this->getUserId())
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminEnquiries&action=pjActionIndex&err=AR10");
				}
			}
			
			if (isset($_POST['enquiry_update']))
			{
				$data = array();
				$data['date_from'] = pjUtil::formatDate($_POST['date_from'], $this->option_arr['o_date_format']);
				$data['date_to'] = pjUtil::formatDate($_POST['date_to'], $this->option_arr['o_date_format']);
				$post = array_merge($_POST, $data);
				
				if (!$pjEnquiryModel->validates($post))
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminEnquiries&action=pjActionIndex&err=AE02");
				}
				$pjEnquiryModel->reset()->set('id', $_POST['id'])->modify($post);
				
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminEnquiries&action=pjActionIndex&err=AE01");
			} else {
				$this->set('arr', $enquiry);
			}
			
			$pjListingModel = pjListingModel::factory();
			if ($this->isOwner())
			{
				$pjListingModel->where('t1.owner_id', $this->getUserId());
			}
			$this->set('listing_arr', $pjListingModel
				->select('t1.id, t1.listing_refid, t2.content AS title')
				->join('pjMultiLang', "t2.model='pjListing' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
				->orderBy('title ASC')
				->findAll()->getData()
			);
			
			
			$this->appendJs('chosen.jquery.min.js', PJ_THIRD_PARTY_PATH . 'harvest/chosen/');
			$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . 'harvest/chosen/');
			$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
			$this->appendJs('pjAdminEnquiries.js');
			
		} else {
			$this->set('status', 2);
		}
	}
}
?>