<?php

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

//$potformula = preg_replace('/<|>/', '_', $match); //replace tags like <div>  to _div_ 
$potformula = htmlspecialchars($match);

$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}"
			$forkey = '';
			foreach ($this->cargo as $key => $value) {
				preg_match("/.*($searchpotid).*/x", $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);

// print("<pre>  completeformula:  ".print_r($complete, true)."</pre>");

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