<?php
class BusinessLogicProcessor
{

	public static function getInstance()
	{
		return new BusinessLogicProcessor(MySqliWrapper::getInstance(), BusinessLogicFactory::getInstance());
	}
	private $mysqli;
	private $businessLogicFactory;

	private function __construct(MySqliWrapper $mysqli, BusinessLogicFactory $businessLogicFactory)
	{
		$this->mysqli = $mysqli;
		$this->businessLogicFactory = $businessLogicFactory;
	}

	public function processLoad($pageId)
	{
		$data = array();
		$rulesetArray = $this->getLoadingRuleset($pageId);
		foreach ($rulesetArray as $rule)
		{
			$result = $rule->process();
			if(is_array($result))
			{
				
				$data = array_merge($data, $result);
			}
		}
		return $data;
	}
	
	// This is just a quick hack; there will be no distinction between ajax and
	// "normal" submit
	public function processAjaxSubmit($pageId)
	{
		$coregList = explode(",", $_POST['coregs']);
		if(!isset($_POST['coregs']) || empty($_POST['coregs'])) {
			return array("next" => 15);
		}
		
		if(in_array('13005', $coregList))
		{ // man
			if(count($coregList) >= 2)
			{
				return array("next" => 14);
			}
			return array("next" => 12);
		}
		if(in_array('13006', $coregList))
		{ // woman
			if(count($coregList) >= 2)
			{
				return array("next" => 14);
			}
			return array("next" => 13);
		}
		
		return array("next" => 2, "redirect" => true);
	}

	public function processSubmit($pageId)
	{
		$data = array();
		$rulesetArray = $this->getSubmittingRuleset($pageId);
		foreach ($rulesetArray as $rule)
		{
			$result = $rule->process();
			if(is_array($result))
			{
				$data = array_merge($data, $result);
			}
		}
		
		return $data;
	}

	private function getLoadingRuleset($pageId)
	{
		$sql = sprintf("SELECT `logic_id` FROM `page_instructions` WHERE `page_id` = %s AND `on_submit` = 0 ORDER BY `order`", $pageId);
		$result = $this->mysqli->get($sql);
		$rules = array();
		foreach ($result as $row)
		{
			$rules[] = $this->businessLogicFactory->createRule($row['logic_id']);
		}
		return $rules;
	}

	private function getSubmittingRuleset($pageId)
	{
		$sql = sprintf("SELECT `logic_id` FROM `page_instructions` WHERE `page_id` = %s AND `on_submit` = 1 ORDER BY `order`", $pageId);
		$result = $this->mysqli->get($sql);
		$rules = array();
		foreach ($result as $row)
		{
			$rules[] = $this->businessLogicFactory->createRule($row['logic_id']);
		}
		return $rules;
	}
}