<?php


/**
* calculate the input
* replace the string in: { ?/@/#/! string }  with the value of one or more potids value
*/

$potformula = preg_replace("/^\s*?$/", "\" \"", trim($match)); //if only spaces are set, replace space with " " to avoid calc errors
//$potformula = preg_replace('/<|>/', '', $potformula); //replace tags like <div>  to _div_ </div>
$potformula = htmlspecialchars($potformula);
$potformula = preg_replace("/,/", ".", $potformula); //replace , with . in case user writes a comma instead of a dot

$pattern = '/\s*\{{1}\s*([\?@!#&)]?)\s*(.*?)\s*\}{1}\s*/';
$complete = preg_replace_callback($pattern, function ($stew) {
	$potid = $this->cargo['pot'];
	$all = $stew[0];
	$spice = $stew[1];
	$searchpotid = $stew[2];
	$completeformula = '';

	switch ($spice) {
		case '@': // get the result of exactly one potid
			$thepotid = $this->cargo[$searchpotid]['output']['result'];
			if (isset($thepotid)) {
				$completeformula .= "( ".$this->cargo[$searchpotid]['output']['formula']." )";
			} else {
				$completeformula .= " 'not set: {@$searchpotid}' ";
				$this->cargo[$potid]['output']['error'] = " error:";
			}
			break;
		case '#': //sum values with matching string in input "{# string}"
		$pattern = "/.*($searchpotid).*/x";
		
			$forkey = '';
			foreach ($this->cargo as $key => $value) {
				preg_match($pattern, $key, $match); //.*(gut).*
				if ($key == $match[0]) {
					if (isset($value['output']['result'])) {
						$forkey .= " + ".$value['output']['result'];
					}
				}
			}
			$completeformula .= "( " . ltrim($forkey, '+ ') . " )";
		
			break;
		case '&': // sum results matching the pot id of the asking potid
			preg_match('/^(.\*?)(\d\*?)$/', $this->cargo['pot'], $potidarr); //fetch potid of this potid
			$searchval = $potidarr[1]; // only first part, no mumber
			$sumarr = array();
			foreach ($this->cargo as $key => $value) {
				preg_match("/.*($searchval).*/", $key, $match);

				if ($key == $match[0]) {
					if (isset($value['output']['result'])) {
						$forkey .= " + ".$value['output']['result'];
					}
				}
			}
			$completeformula .= "( " . ltrim($forkey, '+ '). " )";
			break;
		default:
			$completeformula .= $all;
			break;
	}

	return $completeformula;

}, $potformula);

$mdec = $this->cargo[$potid]['settings']['decimals'];
$calculated = $pothelper->_calculate($complete, $mdec);


$this->cargo[$potid]['output']['result'] = $calculated['result']; // set the var to use it global
$this->cargo[$potid]['output']['formula'] = $calculated['formula'];
$this->cargo[$potid]['output']['type'] = $calculated['type'];
if ($error != '') {
	$this->cargo[$potid]['output']['error'] = $calculated['error'];
}