<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminRequests extends pjAdmin
{
	public function pjActionCreate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor())
		{
			if (isset($_POST['request_create']))
			{
				$data = array();
				
				$call_timezone = $_POST['timezone'];
				$script_timezone = $this->option_arr['o_timezone'];
				
				$datetime_arr = pjUtil::convertDateTime($_POST['besttime'], $this->option_arr['o_date_format'], $this->option_arr['o_time_format']);
				if($datetime_arr != false)
				{
					$best_ts = $datetime_arr['ts'];
					if($call_timezone > $script_timezone)
					{
						$best_ts = $best_ts - ($call_timezone - $script_timezone);
					}else if($call_timezone < $script_timezone){
						$best_ts = $best_ts + ($script_timezone - $call_timezone);
					}
					$data['besttime'] = $datetime_arr['iso_date_time'];
					if($best_ts <= time())
					{
						$data['actual_besttime'] = date('Y-m-d H:i:s', $best_ts + 24*60*60);
					}else{
						$data['actual_besttime'] = date('Y-m-d H:i:s', $best_ts);
					}
				}else{
					$data['besttime'] = ':NULL';
					$data['actual_besttime'] = ':NULL';
				}
				$data['created'] =  date('Y-m-d H:i:s', time());
				$data['ip'] = pjUtil::getClientIp();
				
				$id = pjRequestModel::factory(array_merge($_POST, $data))->insert()->getInsertId();
				if ($id !== false && (int) $id > 0)
				{
					$err = 'ARQ03';
				} else {
					$err = 'ARQ04';
				}
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminRequests&action=pjActionIndex&err=$err");
			} else {
				
				$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();
				$reason_arr = pjReasonModel::factory()
					->select("t1.*")
					->where('t1.status', 'T')
					->orderBy("t1.reason ASC")
					->findAll()
					->getData();
				
				$o_arr = $this->models['Option']
					->where('t1.foreign_id', $this->getForeignId())
					->where('`key`', 'o_timezone')
					->orderBy('t1.key ASC')
					->findAll()
					->getData();
				
				$this->set('country_arr', $country_arr);
				$this->set('reason_arr', $reason_arr);
				$this->set('timezone_arr', $o_arr[0]);
				
				$this->appendJs('jquery-ui-timepicker-addon.js', PJ_THIRD_PARTY_PATH . 'timepicker/');
				$this->appendCss('jquery-ui-timepicker-addon.css', PJ_THIRD_PARTY_PATH . 'timepicker/');
				$this->appendJs('chosen.jquery.js', PJ_THIRD_PARTY_PATH . 'chosen/');
				$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . 'chosen/');
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('pjAdminRequests.js');
			}
		} else {
			$this->set('status', 2);
		}
	}

	public function pjActionDeleteRequest()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			if (pjRequestModel::factory()->setAttributes(array('id' => $_GET['id']))->erase()->getAffectedRows() == 1)
			{
				$response['code'] = 200;
			} else {
				$response['code'] = 100;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionDeleteRequestBulk()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				pjRequestModel::factory()->whereIn('id', $_POST['record'])->eraseAll();
			}
		}
		exit;
	}
	
	public function pjActionExportRequest()
	{
		$this->checkLogin();
	
		if (isset($_POST['record']) && is_array($_POST['record']))
		{
			$arr = pjRequestModel::factory()
				->select('t1.*, t2.reason')
				->join('pjReason', 't2.id=t1.reason_id', 'left')
				->whereIn('t1.id', $_POST['record'])
				->findAll()
				->getData();
			$csv = new pjCSV();
			$csv
				->setHeader(true)
				->setName("Request-".time().".csv")
				->process($arr)
				->download();
		}
		exit;
	}
	
	public function pjActionGetRequest()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjRequestModel = pjRequestModel::factory()
				->join('pjReason', 't1.reason_id=t2.id', 'left');
			
			if (isset($_GET['q']) && !empty($_GET['q']))
			{
				$q = pjObject::escapeString($_GET['q']);
				$pjRequestModel->where('t1.name LIKE', "%$q%");
				$pjRequestModel->orWhere('t1.email LIKE', "%$q%");
				$pjRequestModel->orWhere('t1.phone LIKE', "%$q%");
				$pjRequestModel->orWhere('t2.reason LIKE', "%$q%");
			}

			if (isset($_GET['status']) && !empty($_GET['status']) && in_array($_GET['status'], array('T', 'F')))
			{
				$pjRequestModel->where('t1.status', $_GET['status']);
			}
			
			$column = 'created';
			$direction = 'ASC';
			if (isset($_GET['direction']) && isset($_GET['column']) && in_array(strtoupper($_GET['direction']), array('ASC', 'DESC')))
			{
				$column = $_GET['column'];
				$direction = strtoupper($_GET['direction']);
			}

			$total = $pjRequestModel->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 = $pjRequestModel
				->select('t1.*, t2.reason')
				->orderBy("$column $direction")
				->limit($rowCount, $offset)
				->findAll()
				->getData();
			
			foreach($data as $k => $v)
			{
				$v['created'] = date($this->option_arr['o_date_format'], strtotime($v['created'])) . ', ' . date($this->option_arr['o_time_format'], strtotime($v['created']));
				if(!empty($v['actual_besttime']))
				{
					$v['actual_besttime'] = date($this->option_arr['o_date_format'], strtotime($v['actual_besttime'])) . ', ' . date($this->option_arr['o_time_format'], strtotime($v['actual_besttime']));
				}
				
				$data[$k] = $v;
			}
			pjAppController::jsonResponse(compact('data', 'total', 'pages', 'page', 'rowCount', 'column', 'direction'));
		}
		exit;
	}
	
	public function pjActionIndex()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor())
		{
			$this->appendJs('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
			$this->appendJs('pjAdminRequests.js');
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionSaveRequest()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			pjRequestModel::factory()->where('id', $_GET['id'])->limit(1)->modifyAll(array($_POST['column'] => $_POST['value']));
		}
		exit;
	}
	
	public function pjActionUpdate()
	{
		$this->checkLogin();

		if ($this->isAdmin() || $this->isEditor())
		{
			if (isset($_POST['request_update']))
			{
				$data = array();
				$call_timezone = $_POST['timezone'];
				$script_timezone = $this->option_arr['o_timezone'];
				$datetime_arr = pjUtil::convertDateTime($_POST['besttime'], $this->option_arr['o_date_format'], $this->option_arr['o_time_format']);
				if($datetime_arr != false)
				{
					$best_ts = $datetime_arr['ts'];
					if($call_timezone > $script_timezone)
					{
						$best_ts = $best_ts - ($call_timezone - $script_timezone);
					}else if($call_timezone < $script_timezone){
						$best_ts = $best_ts + ($script_timezone - $call_timezone);
					}
					$data['besttime'] = $datetime_arr['iso_date_time'];
					if($best_ts <= time())
					{
						$data['actual_besttime'] = date('Y-m-d H:i:s', $best_ts + 24*60*60);
					}else{
						$data['actual_besttime'] = date('Y-m-d H:i:s', $best_ts);
					}
				}else{
					$data['besttime'] = ':NULL';
					$data['actual_besttime'] = ':NULL';
				}
				$data['modified'] =  date('Y-m-d H:i:s', time());
				$data['ip'] = pjUtil::getClientIp();
				
				pjRequestModel::factory()->where('id', $_POST['id'])->limit(1)->modifyAll(array_merge($_POST, $data));
				
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminRequests&action=pjActionIndex&err=ARQ01");
				
			} else {
				$arr = pjRequestModel::factory()->find($_GET['id'])->getData();
				if (count($arr) === 0)
				{
					pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminRequests&action=pjActionIndex&err=ARQ08");
				}
				
				$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();
				$reason_arr = pjReasonModel::factory()
					->select("t1.*")
					->where('t1.status', 'T')
					->orderBy("t1.reason ASC")
					->findAll()
					->getData();
				
				$o_arr = $this->models['Option']
					->where('t1.foreign_id', $this->getForeignId())
					->where('`key`', 'o_timezone')
					->orderBy('t1.key ASC')
					->findAll()
					->getData();
				
				$this->set('country_arr', $country_arr);
				$this->set('reason_arr', $reason_arr);
				$this->set('timezone_arr', $o_arr[0]);
				$this->set('arr', $arr);
				
				$this->appendJs('jquery-ui-timepicker-addon.js', PJ_THIRD_PARTY_PATH . 'timepicker/');
				$this->appendCss('jquery-ui-timepicker-addon.css', PJ_THIRD_PARTY_PATH . 'timepicker/');
				$this->appendJs('chosen.jquery.js', PJ_THIRD_PARTY_PATH . 'chosen/');
				$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . 'chosen/');
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('pjAdminRequests.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionFeed()
	{
		$this->checkLogin();
	
		if ($this->isAdmin()|| $this->isEditor())
		{
			if(isset($_POST['request_feed']))
			{
				$pjPasswordModel = pjPasswordModel::factory();
				$password = md5($_POST['password'].PJ_SALT);
				$arr = $pjPasswordModel
					->where("t1.password", $password)
					->limit(1)
					->findAll()
					->getData();
				if (count($arr) != 1)
				{
					$pjPasswordModel->setAttributes(array('password' => $password))->insert();
				}
				$this->set('password', $password);
			}
	
			$reason_arr = pjReasonModel::factory()
				->where('t1.status', 'T')
				->orderBy("`reason` ASC")
				->findAll()
				->getData();
				
			$this->set('reason_arr', $reason_arr);
				
			$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
			$this->appendJs('pjAdminRequests.js');
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionExportFeed()
	{
		$this->setLayout('pjActionEmpty');
		$access = true;
		if(isset($_GET['p']))
		{
			$pjPasswordModel = pjPasswordModel::factory();
			$arr = $pjPasswordModel
				->where('t1.password', $_GET['p'])
				->limit(1)
				->findAll()
				->getData();
			if (count($arr) != 1)
			{
				$access = false;
			}
		}else{
			$access = false;
		}
		
		if($access == true)
		{
			$arr = $this->pjGetFeedData($_GET);
				
			if(!empty($arr))
			{
				if($_GET['format'] == 'xml')
				{
					$xml = new pjXML();
					echo $xml
						->setEncoding('UTF-8')
						->process($arr)
						->getData();
	
				}
				if($_GET['format'] == 'csv')
				{
					$csv = new pjCSV();
					echo $csv
						->setHeader(true)
						->process($arr)
						->getData();
				}
				if($_GET['format'] == 'ical')
				{
					$ical = new pjICal();
					echo $ical
						->setProdID('Callback Widget')
						->setSummary('reason')
						->setCName('name')
						->setDateFrom('actual_besttime')
						->setDateTo('actual_besttime')
						->setTimezone(pjUtil::getTimezoneName($this->option_arr['o_timezone']))
						->process($arr)
						->getData();
						
				}
			}
		}else{
			__('lblNoAccessToFeed');
		}
		exit;
	}
	
	public function pjGetFeedData($get)
	{
		$arr = array();
		$status = true;
		$period = '';
		if(isset($get['period']))
		{
			if(!ctype_digit($get['period']))
			{
				$status = false;
			}else{
				$period = $get['period'];
			}
		}else{
			$status = false;
		}
		if(isset($get['type']))
		{
			if(!ctype_digit($get['type']))
			{
				$status = false;
			}else{
				$type = $get['type'];
			}
		}else{
			$status = false;
		}
		
		if($status == true && $type != '' && $period != '')
		{
			$pjRequestModel = pjRequestModel::factory();
			
			$column = 'created';
			$direction = 'DESC';
			if($type == '1')
			{
				$column = '`actual_besttime`';
				$direction = 'ASC';
					
				$where_str = pjUtil::getComingWhere($period, $this->option_arr['o_week_start']);
				if($where_str != '')
				{
					$pjRequestModel->where($where_str);
				}
			}else{
				$column = 'created';
				$direction = 'DESC';
				$where_str = pjUtil::getMadeWhere($period, $this->option_arr['o_week_start']);
				if($where_str != '')
				{
					$pjRequestModel->where($where_str);
				}
			}
			if(isset($get['reason_id']))
			{
				$pjRequestModel->where('t1.reason_id', $get['reason_id']);
			}
			$arr= $pjRequestModel
				->select('t1.*,t2.reason')
				->join('pjReason', "t1.reason_id=t2.id", 'left')
				->orderBy("$column $direction")
				->findAll()
				->getData();
		}
		return $arr;
	}
}
?>