<?php

// The cient side models will be called on registration page load
// these will update the table for the given session id
// only one update will be allowed to reduce manipulation (that update on which the registration page 1st loads)

class Tac_FoolBotHoneyPot_Model_ClientSide extends XenForo_Model
{

	public function getClientSideById($id)
	{
		return $this->_getDb()->fetchRow('
			SELECT *
			FROM sf_foolbothoneypot_clientside_detection 
			WHERE id = ?
		', $id);
	}
	
	public function getJSUuid()
	{
		$session_id = XenForo_Application::get('session')->getSessionId();
		
		return $this->_getDb()->fetchRow('
			SELECT number, uuid
			FROM sf_foolbothoneypot_uuids
			WHERE session_id = ?
			AND number = 71
			', $session_id);	
	}
	
	
	
	public function setClientSideStart()
	{
		// 1st detect that it doesn't already exist
		$clientSide = $this->getClientSide();
		
		if(!$clientSide){
			$timerWriter = XenForo_DataWriter::create('Tac_FoolBotHoneyPot_DataWriter_ClientSide');
			$timerWriter->set('session_id', XenForo_Application::get('session')->getSessionId());
			$timerWriter->set('javascript_on', 0);
			$timerWriter->set('updated', 0);
			$timerWriter->set('time_stamp', time());
			$timerWriter->save();
		}	
	}
	
	public function getClientSide()
	{
		$session_id = XenForo_Application::get('session')->getSessionId();
		
		return $this->_getDb()->fetchRow('
			SELECT *
			FROM sf_foolbothoneypot_clientside_detection 
			WHERE session_id = ?		
		', $session_id);
	}
	
	public function updateClientSide($plugins = "", $uuid = "")
	{
		// 1st get the ClientSide data for this session 
		// It must 1st exist, if it exists and has not yet been updated, update it
		
		$clientSide = $this->getClientSide();
		
		if($clientSide && $clientSide['updated'] == 0) 
		{
			
			// check the correct javasctipt uuid was sent for this session
			$correct_uuid = $this->getJSUuid();			
			$is_correct_uuid = ($uuid == $correct_uuid['uuid']? 1 : 0);
			$clientWriter = XenForo_DataWriter::create('Tac_FoolBotHoneyPot_DataWriter_ClientSide');
			$clientWriter->setExistingData($clientSide['id']);
			$clientWriter->set('session_id', XenForo_Application::get('session')->getSessionId());
			$clientWriter->set('time_stamp', time());
			$clientWriter->set('javascript_on', 1);
			$clientWriter->set('detected_plugins', $plugins);
			$clientWriter->set('uuid', $uuid);
			$clientWriter->set('correct_uuid', $is_correct_uuid);
			$clientWriter->set('updated', 1);
			$clientWriter->save();
		}
	}
	
	public function deleteOldClientSide()
	{
		// delete ClientSide older than an 2 Hours (avoid daylight saving issues)
		$twoHrAgo = time()-(60*120);
		$db = $this->_getDb();
		$db->delete('sf_foolbothoneypot_clientside_detection', 'time_stamp < ' . $db->quote($twoHrAgo));
	}
	

	
	public function getClientSideForm()
	{
	
		// params for dynamically generated form
		return 	" ";

		
		
		
	}
	
	
}