<?php

class Tac_AnyApi_ControllerAdmin_AnyApi extends XenForo_ControllerAdmin_Abstract
{
	protected function _preDispatch($action)
	{
		$this->assertAdminPermission('viewLogs');
	}

	public function actionLogic()
	{
		
		
		$apiStngs = $this->_getApiSettingsModel()->getApiSettings();

		$apiNames = array
		(
			'api1', 'api2', 'api3', 'api4', 'api5', 'api6', 'api7', 'api8',  'api9', 'api10'
		); 	
		
		$apis = array();
		
		foreach ($apiNames as $key=>$apiName)
		{
			$apis[$apiName] = array
				(
					'id' => $apiStngs[$key+1]['id'], 
					'name' => $apiStngs[$key+1]['name'],
					'url' => html_entity_decode($apiStngs[$key+1]['url']), 
					'key' => $apiStngs[$key+1]['key'], 
					'data_type' => $apiStngs[$key+1]['data_type'], 
					'rules' => unserialize($apiStngs[$key+1]['rules']),
					'logic_set' => $apiStngs[$key+1]['logic_set'],
					'api_active' => $apiStngs[$key+1]['api_active'],
				);
		}	
		
			$options = XenForo_Application::get('options');
			
			$viewParams = array(
				'no_of_apis' => $options->numberOfApis,
				'apis' => $apis		
			);
			
			
		return $this->responseView('XenForo_ViewAdmin_Log_ServerError', 'anyapi_option_index', $viewParams);
	}

	
	public function actionSave()	
	{
		$this->_assertPostOnly();
		// save each of the apis settings (10 apis in total)
		
		for ($i = 1; $i <= 10; $i++) 
		{
			$this->saveApi($i);	
		}

		

		return $this->responseRedirect(
			XenForo_ControllerResponse_Redirect::SUCCESS,
			XenForo_Link::buildAdminLink('anyapi/logic')
			);
	}
	
	
	
	public function saveApi($id)
	{	
		$apiNo = 'api_'.$id;
		
		
		
		$apiRules = $this->_input->filter(array(
			$apiNo.'_rule_1'	=> XenForo_Input::STRING,				$apiNo.'_rule_2'   	=> XenForo_Input::STRING,
			$apiNo.'_rule_3'   	=> XenForo_Input::STRING,				$apiNo.'_rule_4'   	=> XenForo_Input::STRING,
			$apiNo.'_rule_5' 	=> XenForo_Input::STRING,				$apiNo.'_rule_6'	=> XenForo_Input::STRING,
			$apiNo.'_rule_7'   	=> XenForo_Input::STRING,				$apiNo.'_rule_8'   	=> XenForo_Input::STRING,
			$apiNo.'_rule_9'   	=> XenForo_Input::STRING,				$apiNo.'_rule_10' 	=> XenForo_Input::STRING,
		//	$apiNo.'_rule_11'	=> XenForo_Input::STRING,				$apiNo.'_rule_12'   	=> XenForo_Input::STRING,
		//	$apiNo.'_rule_13'   	=> XenForo_Input::STRING, 			$apiNo.'_rule_14'   	=> XenForo_Input::STRING,
		//	$apiNo.'_rule_15' 	=> XenForo_Input::STRING,
		));
		
		$apiRulesNoIdx = array(
			1 => $apiRules[$apiNo.'_rule_1'], 			2 => $apiRules[$apiNo.'_rule_2'],
			3 => $apiRules[$apiNo.'_rule_3'], 			4 => $apiRules[$apiNo.'_rule_4'],
			5 => $apiRules[$apiNo.'_rule_5'], 			6 => $apiRules[$apiNo.'_rule_6'],
			7 => $apiRules[$apiNo.'_rule_7'], 			8 => $apiRules[$apiNo.'_rule_8'],
			9 => $apiRules[$apiNo.'_rule_9'], 			10 => $apiRules[$apiNo.'_rule_10'],
		//	11 => $apiRules[$apiNo.'_rule_11'], 		12 => $apiRules[$apiNo.'_rule_12'],
		//	13 => $apiRules[$apiNo.'_rule_13'], 		14 => $apiRules[$apiNo.'_rule_14'],
		//	15 => $apiRules[$apiNo.'_rule_15'],
		);
		
		$apiInput = $this->_input->filter(array(
			$apiNo.'_name'			=> XenForo_Input::STRING,
			$apiNo.'_url'       	=> XenForo_Input::STRING,
			$apiNo.'_key'      		=> XenForo_Input::STRING,
			$apiNo.'_data_type'   	=> XenForo_Input::STRING,
			$apiNo.'_logic_set' 	=> XenForo_Input::STRING,
			$apiNo.'_api_active' 	=> XenForo_Input::UINT,
		));

		$apiInput[$apiNo.'_rules'] = serialize($apiRulesNoIdx);

		$apiSettings = array(
			'id' => $id,					
			'name' => $apiInput[$apiNo.'_name'], 						
			'url' => $apiInput[$apiNo.'_url'], 						
			'key' => $apiInput[$apiNo.'_key'], 						
			'data_type' => $apiInput[$apiNo.'_data_type'], 				
			'rules' => $apiInput[$apiNo.'_rules'],				
			'logic_set'  => $apiInput[$apiNo.'_logic_set'],	
			'api_active' => $apiInput[$apiNo.'_api_active'],		
		);

		$writer = XenForo_DataWriter::create('Tac_AnyApi_DataWriter_ApiSettings');
		$writer->setExistingData($id);
		$writer->bulkSet($apiSettings);
		$writer->save();

		
	}
	
	

	
	
	
	
	
	
	public function actionLogs()
	{
		$id = $this->_input->filterSingle('id', XenForo_Input::UINT);
		if ($id)
		{
			
			
			$entry = $this->_getAnyApiLogModel()->getLogById($id);
			if (!$entry)
			{
				return $this->responseError(new XenForo_Phrase('sf_requested_log_entry_not_found'), 404);
			}

			$entry['ip_address'] = long2ip($entry['ip_address']);			
			
			// put rules into a nice format
			$rules = unserialize($entry['rules']);

			$evaluated_logic = (
				$entry['is_blocked'] == 1 ? $entry['logic_set_bool']." = true // registration blocked" : $entry['logic_set_bool']." = false // registration not blocked" 
			);
			
			$viewParams = array(
				'entry' => $entry,
				'rules' => $rules,
				'evaluated_logic' => $evaluated_logic,
			);
			
			
			return $this->responseView('XenForo_ViewAdmin_Log_ServerErrorView', 'log_anyapi_view', $viewParams);
			
		}
		else
		{
			$username = $this->_input->filterSingle('username', XenForo_Input::STRING);	
			$email = $this->_input->filterSingle('email', XenForo_Input::STRING);	
			$filter = $this->_input->filterSingle('filter', XenForo_Input::STRING);	
			
			$page = $this->_input->filterSingle('page', XenForo_Input::UINT);
			$perPage = 20;
			$entries = $this->_getAnyApiLogModel()->getLogs(array(
					'page' => $page,
					'perPage' => $perPage,
					'username' => urlencode($username),
					'email' => urlencode($email),
					'filter' => $filter,
				));
				
			foreach($entries as $key => $entry){
				$entries[$key]['ip_address'] = long2ip($entry['ip_address']);
				$entries[$key]['email'] = urldecode($entry['email']); 
				$entries[$key]['username'] = urldecode($entry['username']);
				
			}
			
			$options = XenForo_Application::get('options');
			$totalItems = $this->_getAnyApiLogModel()->countLogs($username, $email, $filter);
			
			
			
// needed for fbhp_page_nav			
			
			
			$pageTotal = ceil($totalItems / $perPage);
			$currentPage = min(max($page, 1), $pageTotal);
			// number of pages either side of the current page
			$range = 2;
			$scrollSize = 1 + 2 * $range;
			$scrollThreshold = $scrollSize + 2;
	
			if ($pageTotal >$scrollThreshold)
			{
				$startPage = max(2, $currentPage - $range);
				$endPage = min($pageTotal, $startPage + $scrollSize);
	
				$extraPages = $scrollSize - ($endPage - $startPage);
				if ($extraPages > 0)
				{
					$startPage -= $extraPages;
				}
			}
			else
			{
				$startPage = 2;
				$endPage = $pageTotal;
			}
	
			if ($endPage > $startPage)
			{
				$endPage--;
				$pages = range($startPage, $endPage);
			}
			else
			{
				$pages = array();
			}
			
			
			
			
// end fbhp_page_nav
			
			
			
			
						
			
			
			$viewParams = array(
				'second_api_name' => $options->secondApiName,
				'third_api_name' => $options->thirdApiName,
				
				'pageTotal' => $pageTotal,
				'entries' => $entries,
				'page' => $page,
				'perPage' => $perPage,
				'regTime' => $options->fbhp_min_reg_time,
				'total' => $totalItems,
				'username' => $username,
				'email' => $email,
				'filter' => $filter,
				
				'currentPage' => $currentPage,
				'pages' => $pages,
				'range' => $range,
				'scrollThreshold' => $scrollThreshold,
				'startPage' => $startPage,
				'endPage' => $endPage,
				'prevPage' => ($currentPage > 1 ? ($currentPage - 1) : false),
				'nextPage' => ($currentPage < $pageTotal ? ($currentPage + 1) : false),
				'pageNumberSentinel' => XenForo_Application::$integerSentinel,
				'maxDigits' => strlen($pageTotal),
				
				'linkType' => 'anyapi/logs',
				'linkData' => false,
				'linkParams' => array('username' => $username, 'email' => $email, 'filter' => $filter),
				
				
			);
			
			
			return $this->responseView('XenForo_ViewAdmin_Log_ServerError', 'anyapi_log', $viewParams);
		}
		
		
	}	
		
		
	
	
	
	
	
	public function actionDelete()
	{
		$id = $this->_input->filterSingle('id', XenForo_Input::UINT);
		$entry = $this->_getAnyApiLogModel()->getLogById($id);
		if (!$entry)
		{
			return $this->responseError(new XenForo_Phrase('sf_requested_log_entry_not_found'), 404);
		}

		if ($this->isConfirmedPost())
		{
			$this->_getAnyApiLogModel()->deleteLog($id);

			return $this->responseRedirect(
				XenForo_ControllerResponse_Redirect::SUCCESS,
				XenForo_Link::buildAdminLink('anyapi/logs')
			);
		}
		else
		{
			$viewParams = array(
				'entry' => $entry
			);
			return $this->responseView('XenForo_ViewAdmin_Log_ServerErrorDelete', 'log_anyapi_delete', $viewParams);
		}
	}

	public function actionClear()
	{
		if ($this->isConfirmedPost())
		{
			$this->_getAnyApiLogModel()->clearLog();

			return $this->responseRedirect(
				XenForo_ControllerResponse_Redirect::SUCCESS,
				XenForo_Link::buildAdminLink('anyapi/logs')
			);
		}
		else
		{
			$viewParams = array();
			return $this->responseView('XenForo_ViewAdmin_Log_ServerErrorDelete', 'anyapi_log_clear', $viewParams);
		}
	}

	
	
	
	
	
	
		
		
	protected function _getAnyApiLogModel()
	{
		return $this->getModelFromCache('Tac_AnyApi_Model_Log');
	}	
		
				
	protected function _getApiSettingsModel()
	{
		return $this->getModelFromCache('Tac_AnyApi_Model_ApiSettings');
	}	

	
	
}