<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminEnquiries extends pjAdmin
{
	public function pjActionCreate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin())
		{
			if (isset($_POST['enquiry_create']))
			{
				$pjEnquiryModel = pjEnquiryModel::factory();
				
				$client_id = $_POST['client_id'];
				if($client_id == '')
				{
					$client_data = array();
					$client_data['c_title'] = $_POST['c_title'];
					$client_data['c_name'] = $_POST['c_name'];
					$client_data['c_phone'] = $_POST['c_phone'];
					$client_data['c_email'] = $_POST['c_email'];
					
					$client_data['status'] = 'T';
					$client_data['created'] = date('Y-m-d H:i:s');
					$client_data['c_password'] = 'pass';
					$client_id = pjClientModel::factory()->setAttributes($client_data)->insert()->getInsertId();
				}
				$enquiry_data = array();
				$enquiry_data['uuid'] = time();
				$enquiry_data['ip'] = pjUtil::getClientIp();
				$enquiry_data['client_id'] = $client_id;
				$enquiry_data['created'] = date('Y-m-d H:i:s');
				$enquiry_data['date'] =  pjUtil::formatDate($_POST['date'], $this->option_arr['o_date_format']);
				$enquiry_data['c_notes'] = isset($_POST['c_notes']) ? $_POST['c_notes'] : ':NULL';
				$enquiry_data['c_address'] = isset($_POST['c_address']) ? $_POST['c_address'] : ':NULL';
				$enquiry_data['c_city'] = isset($_POST['c_city']) ? $_POST['c_city'] : ':NULL';
				$enquiry_data['c_state'] = isset($_POST['c_state']) ? $_POST['c_state'] : ':NULL';
				$enquiry_data['c_zip'] = isset($_POST['c_zip']) ? $_POST['c_zip'] : ':NULL';
				$enquiry_data['c_country'] = isset($_POST['c_country']) ? $_POST['c_country'] : ':NULL';
				
				$payment = ':NULL';
				if(isset($_POST['payment_method']))
				{
					$payment = $_POST['payment_method'];
					if($payment != 'creditcard')
					{
						$enquiry_data['cc_exp_month'] = '';
						$enquiry_data['cc_exp_year'] = '';
					}else{
						$enquiry_data['cc_type'] = $_POST['cc_type'];
						$enquiry_data['cc_num'] = $_POST['cc_num'];
						$enquiry_data['cc_exp_month'] = $_POST['cc_exp_month'];
						$enquiry_data['cc_exp_year'] = $_POST['cc_exp_year'];
						$enquiry_data['cc_code'] = $_POST['cc_code'];
					}
				}
				unset($_POST['client_id']);
				
				$id = $pjEnquiryModel->setAttributes(array_merge($_POST, $enquiry_data))->insert()->getInsertId();
				if ($id !== false && (int) $id > 0)
				{
					$pjEnquiryExtraModel = pjEnquiryExtraModel::factory();
					if(isset($_POST['extra_id']) && is_array($_POST['extra_id']))
					{
						foreach($_POST['extra_id'] as $extra_id => $on)
						{
							$extra_data = array();
							$extra_data['enquiry_id'] = $id;
							$extra_data['extra_id'] = $extra_id;
							$pjEnquiryExtraModel->reset()->setAttributes($extra_data)->insert();
						}
					}
					$err = 'AEQ03';
				} else {
					$err = 'AEQ04';
				}
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminEnquiries&action=pjActionIndex&err=$err");
			} else {
				$service_arr = pjServiceModel::factory()->find($this->getServiceId())->getData();
				
				$extra_arr = pjExtraModel::factory()
					->select('t1.*, t2.content AS name')
					->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjExtra' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'name'", 'left')
					->where('t1.service_id', $this->getServiceId())
					->findAll()
					->getData();

				$country_arr = pjCountryModel::factory()
					->select('t1.id, t2.content AS country_title')
					->join('pjMultiLang', "t2.model='pjCountry' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->orderBy('`country_title` ASC')
					->findAll()
					->getData();
				
				$client_arr = pjClientModel::factory()->orderBy('`c_name` ASC')->findAll()->getData();
				
				if(isset($_GET['id']))
				{
					$arr = pjEnquiryModel::factory()->find($_GET['id'])->getData();
					$enquiry_extra_id = pjEnquiryExtraModel::factory()->where('t1.enquiry_id', $arr['id'])->findAll()->getDataPair(null, 'extra_id');
					$this->set('arr', $arr);
					$this->set('enquiry_extra_id', $enquiry_extra_id);
				}
				
				$this->set('service_arr', $service_arr);
				$this->set('extra_arr', $extra_arr);
				$this->set('country_arr', $country_arr);
				$this->set('client_arr', $client_arr);
				
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('chosen.jquery.js', PJ_THIRD_PARTY_PATH . 'chosen/');
				$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . 'chosen/');
				$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)
			{
				pjEnquiryExtraModel::factory()->where('enquiry_id', $_GET['id'])->eraseAll();
				pjEnquiryPaymentModel::factory()->where('enquiry_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();
				pjEnquiryExtraModel::factory()->whereIn('enquiry_id', $_POST['record'])->eraseAll();
				pjEnquiryPaymentModel::factory()->whereIn('enquiry_id', $_POST['record'])->eraseAll();
			}
		}
		exit;
	}
	
	public function pjActionGetEnquiry()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjEnquiryModel = pjEnquiryModel::factory()->join('pjClient', "t2.id = t1.client_id", 'left');
			
			if (isset($_GET['q']) && !empty($_GET['q']))
			{
				$q = pjObject::escapeString($_GET['q']);
				$pjEnquiryModel->where("(t2.c_name LIKE '%$q%' OR t2.c_email LIKE '%$q%' OR t2.c_phone LIKE '%$q%')");
			}
			if (isset($_GET['status']) && !empty($_GET['status']) && in_array($_GET['status'], array('pending', 'confirmed', 'cancelled')))
			{
				$pjEnquiryModel->where('t1.status', $_GET['status']);
			}
			if (isset($_GET['client_id']) && (int)$_GET['client_id'] > 0)
			{
				$pjEnquiryModel->where('t1.client_id', $_GET['client_id']);
			}
			$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'] : 20;
			$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.*, t2.c_name, t2.c_email, t2.c_phone')
				->orderBy("$column $direction")
				->limit($rowCount, $offset)
				->findAll()
				->getData();

			$when_options =  __('when_options', true);
			$how_often = __('how_often', true);
			
			foreach($data as $k => $v)
			{
				$date_time_arr = array();
				$date_time_arr[] = date($this->option_arr['o_date_format'], strtotime($v['date']));
				$date_time_arr[] = $when_options[$v['when']];
				$date_time_arr[] = $how_often[$v['how_often']];
				$v['date'] = join("&nbsp;|&nbsp;", $date_time_arr);
				$v['total'] = pjUtil::formatCurrencySign($v['total'], $this->option_arr['o_currency']);
				$data[$k] = $v;
			}		
			
			pjAppController::jsonResponse(compact('data', 'total', 'pages', 'page', 'rowCount', 'column', 'direction'));
		}
		exit;
	}
		
	public function pjActionIndex()
	{
		$this->checkLogin();
		
		if ($this->isAdmin())
		{
			$this->appendJs('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
			$this->appendJs('pjAdminEnquiries.js');
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionSaveEnquiry()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjEnquiryModel = pjEnquiryModel::factory();
			if (!in_array($_POST['column'], $pjEnquiryModel->getI18n()))
			{
				$pjEnquiryModel->where('id', $_GET['id'])->limit(1)->modifyAll(array($_POST['column'] => $_POST['value']));
			} else {
				pjMultiLangModel::factory()->updateMultiLang(array($this->getLocaleId() => array($_POST['column'] => $_POST['value'])), $_GET['id'], 'pjEnquiry', 'data');
			}
		}
		exit;
	}
	
	public function pjActionUpdate()
	{
		$this->checkLogin();

		if ($this->isAdmin())
		{
			if (isset($_POST['enquiry_update']))
			{
				$pjEnquiryModel = pjEnquiryModel::factory();
								
				$err = 'AEQ01';
				
				$arr = $pjEnquiryModel->find($_POST['id'])->getData();
				if (empty($arr))
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminBooths&action=pjActionIndex&err=AEQ08");
				}
				
				$client_id = $_POST['client_id'];
				if($client_id == '')
				{
					$client_data = array();
					$client_data['c_title'] = $_POST['c_title'];
					$client_data['c_name'] = $_POST['c_name'];
					$client_data['c_phone'] = $_POST['c_phone'];
					$client_data['c_email'] = $_POST['c_email'];
						
					$client_data['status'] = 'T';
					$client_data['created'] = date('Y-m-d H:i:s');
					$client_data['c_password'] = 'pass';
					$client_id = pjClientModel::factory()->setAttributes($client_data)->insert()->getInsertId();
				}
				
				$enquiry_data = array();
				$enquiry_data['client_id'] = $client_id;
				$enquiry_data['date'] =  pjUtil::formatDate($_POST['date'], $this->option_arr['o_date_format']);
				$enquiry_data['c_notes'] = isset($_POST['c_notes']) ? $_POST['c_notes'] : ':NULL';
				$enquiry_data['c_address'] = isset($_POST['c_address']) ? $_POST['c_address'] : ':NULL';
				$enquiry_data['c_city'] = isset($_POST['c_city']) ? $_POST['c_city'] : ':NULL';
				$enquiry_data['c_state'] = isset($_POST['c_state']) ? $_POST['c_state'] : ':NULL';
				$enquiry_data['c_zip'] = isset($_POST['c_zip']) ? $_POST['c_zip'] : ':NULL';
				$enquiry_data['c_country'] = isset($_POST['c_country']) ? $_POST['c_country'] : ':NULL';
				
				$payment = ':NULL';
				if(isset($_POST['payment_method']))
				{
					$payment = $_POST['payment_method'];
					if($payment != 'creditcard')
					{
						$enquiry_data['cc_exp_month'] = '';
						$enquiry_data['cc_exp_year'] = '';
					}else{
						$enquiry_data['cc_type'] = $_POST['cc_type'];
						$enquiry_data['cc_num'] = $_POST['cc_num'];
						$enquiry_data['cc_exp_month'] = $_POST['cc_exp_month'];
						$enquiry_data['cc_exp_year'] = $_POST['cc_exp_year'];
						$enquiry_data['cc_code'] = $_POST['cc_code'];
					}
				}
				unset($_POST['client_id']);
				
				pjEnquiryModel::factory()->where('id', $_POST['id'])->limit(1)->modifyAll(array_merge($_POST, $enquiry_data));
				if (isset($_POST['i18n']))
				{
					pjMultiLangModel::factory()->updateMultiLang($_POST['i18n'], $_POST['id'], 'pjEnquiry', 'data');
				}
				
				$pjEnquiryExtraModel = pjEnquiryExtraModel::factory();
				$pjEnquiryExtraModel->where('enquiry_id', $_POST['id'])->eraseAll();
				if(isset($_POST['extra_id']) && is_array($_POST['extra_id']))
				{
					foreach($_POST['extra_id'] as $extra_id => $on)
					{
						$extra_data = array();
						$extra_data['enquiry_id'] = $_POST['id'];
						$extra_data['extra_id'] = $extra_id;
						$pjEnquiryExtraModel->reset()->setAttributes($extra_data)->insert();
					}
				}
				
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminEnquiries&action=pjActionIndex&err=$err");
				
			} else {
				$arr = pjEnquiryModel::factory()->find($_GET['id'])->getData();
				if(count($arr) <= 0)
				{
					pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminEnquiries&action=pjActionIndex&err=AEQ08");
				}
				$service_arr = pjServiceModel::factory()->find($this->getServiceId())->getData();
				
				$extra_arr = pjExtraModel::factory()
					->select('t1.*, t2.content AS name')
					->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjExtra' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'name'", 'left')
					->where('t1.service_id', $this->getServiceId())
					->findAll()
					->getData();
				
				$country_arr = pjCountryModel::factory()
					->select('t1.id, t2.content AS country_title')
					->join('pjMultiLang', "t2.model='pjCountry' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->orderBy('`country_title` ASC')
					->findAll()
					->getData();
				
				$enquiry_table = pjEnquiryModel::factory()->getTable();
				$client_arr = pjClientModel::factory()
					->select("t1.*, (SELECT COUNT(`TE`.`id`) FROM `".$enquiry_table."` AS `TE` WHERE `TE`.`client_id`=t1.id) AS cnt_enquiries,
								(SELECT `TE1`.`created` FROM `".$enquiry_table."` AS `TE1` WHERE `TE1`.`client_id`=t1.id ORDER BY `TE1`.created ASC LIMIT 1) AS first")
					->orderBy('`c_name` ASC')
					->findAll()
					->getData();
				$enquiry_extra_id = pjEnquiryExtraModel::factory()->where('t1.enquiry_id', $arr['id'])->findAll()->getDataPair(null, 'extra_id');
				
				$this->set('service_arr', $service_arr);
				$this->set('extra_arr', $extra_arr);
				$this->set('country_arr', $country_arr);

				$this->set('arr', $arr);
				$this->set('client_arr', $client_arr);
				$this->set('enquiry_extra_id', $enquiry_extra_id);
				
				$this->appendJs('tinymce.min.js', PJ_THIRD_PARTY_PATH . 'tinymce/');
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('chosen.jquery.js', PJ_THIRD_PARTY_PATH . 'chosen/');
				$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . 'chosen/');
				$this->appendJs('pjAdminEnquiries.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionConfirmation()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['send_confirm']) && !empty($_POST['to']) && !empty($_POST['from']) &&
					!empty($_POST['subject']) && !empty($_POST['message']))
			{
				$Email = new pjEmail();
				$Email->setContentType('text/html');
				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'])
						->setSender($this->option_arr['o_smtp_user']);
				}
	
				$subject = $_POST['subject'];
				$message = $_POST['message'];
				if (get_magic_quotes_gpc())
				{
					$subject = stripslashes($_POST['subject']);
					$message = stripslashes($_POST['message']);
				}
	
				$r = $Email
					->setTo($_POST['to'])
					->setFrom($_POST['from'])
					->setSubject($subject)
					->send($message);
					
				if ($r)
				{
					pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Email has been sent.'));
				}
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Email failed to send.'));
			}
	
			if (isset($_GET['enquiry_id']) && (int) $_GET['enquiry_id'] > 0)
			{
				$pjMultiLangModel = pjMultiLangModel::factory();
				$lang_message = $pjMultiLangModel->reset()->select('t1.*')
					->where('t1.model','pjOption')
					->where('t1.locale', $this->getLocaleId())
					->where('t1.field', 'o_email_confirmation_message')
					->limit(0, 1)
					->findAll()->getData();
				$lang_subject = $pjMultiLangModel->reset()->select('t1.*')
					->where('t1.model','pjOption')
					->where('t1.locale', $this->getLocaleId())
					->where('t1.field', 'o_email_confirmation_subject')
					->limit(0, 1)
					->findAll()->getData();
	
				if (count($lang_message) === 1 && count($lang_subject) === 1)
				{
					$enquiry_arr = pjEnquiryModel::factory()->find($_GET['enquiry_id'])->getData();
					$client_arr = pjClientModel::factory()->find($enquiry_arr['client_id'])->getData();
					$tokens = pjAppController::getTokens($_GET['enquiry_id'], $this->option_arr, PJ_SALT, $this->getLocaleId());
						
					$subject_client = str_replace($tokens['search'], $tokens['replace'], $lang_subject[0]['content']);
					$message_client = str_replace($tokens['search'], $tokens['replace'], $lang_message[0]['content']);
	
					$this->set('arr', array(
							'to' => $client_arr['c_email'],
							'from' => $this->getAdminEmail(),
							'message' => $message_client,
							'subject' => $subject_client
					));
				}
			} else {
				exit;
			}
		}
	}
	
	public function pjActionPrint()
	{
		$this->setLayout('pjActionPrint');
	
		if (isset($_GET['id']) && (int) $_GET['id'] > 0)
		{
			$pjMultiLangModel = pjMultiLangModel::factory();
			$lang_message = $pjMultiLangModel->reset()->select('t1.*')
				->where('t1.model','pjOption')
				->where('t1.locale', $this->getLocaleId())
				->where('t1.field', 'o_print_template')
				->limit(0, 1)
				->findAll()->getData();
			
			$content = '';
			if (count($lang_message) === 1)
			{
				$tokens = pjAppController::getTokens($_GET['id'], $this->option_arr, PJ_SALT, $this->getLocaleId());
		
				$content = str_replace($tokens['search'], $tokens['replace'], $lang_message[0]['content']);
			}
			$this->set('content', $content);
		}
	}
}
?>