<?php

/**
 * Genera una porzione di codice html a partire da una stringa nei seguenti formati:
 * campo <input> generico:
 * {[ "type": "text", "required": 1, "class": "", "value": "$idintervento$", "extra": "" ]}
 *
 * campo di testo normale e non modificabile
 * {[ "type": "span", "value": "$testo$" ]}
 *
 * <select>
 * {[ "type": "select", "required": 1, "class": "", "values": "query='SELECT id, descrizione FROM co_contratti WHERE idanagrafica=$idanagrafica$"', "value": "$idcontratto$", "extra": "" ]}
 *
 * Il parametro $records contiene il risultato della query di selezione record per fare i vari replace delle variabili racchiuse tra $$ nel template
 */
function build_html_element($str) {
	global $dbo;
	global $docroot;
	global $records;
	global $modules_info;
	global $id_record;

	preg_match('"value(.+?)\] \}"', $str, $script_value);
	if(count($script_value) != 0) {
		$script_value = $script_value[0];
		$str = str_replace($script_value, 'value": "', $str);
	}
	else unset($script_value);

	$str = str_replace("{[", "{", $str);
	$str = str_replace("]}", "}", $str);

	$json = json_decode($str, true);

	// Conversione variabili con campi di database
	foreach ($json as $name => $value) {
		if ($value == "") unset($json[$name]);
		// Sostituzione delle variabili $nome$ col relativo valore da database
		else if (preg_match_all('/\$([a-z0-9\_]+)\$/i', $json[$name], $m)) {
			for($i = 0; $i < sizeof($m[0]); $i ++) {
				$json[$name] = str_replace($m[0][$i], $records[0][$m[1][$i]], $json[$name]);
			}
		}
	}
	
	$attributi = array();
	array_push($attributi, "class");

	$valori = array();
	$valori["class"] = array();
	array_push($valori["class"], "form-control");

	if(isset($json["class"]) && $json["class"] != ""){
		$classes = explode(" ", $json["class"]);
		foreach ($classes as $class) {
			if ($class != "") array_push($valori["class"], $class);
		}
	}

	// Attributi particolari
	if (isset($json['disabled']) && $json['disabled'] == 1) array_push($attributi, "disabled");
	if (isset($json['readonly']) && $json['readonly'] == 1) array_push($attributi, "readonly");
	if (isset($json['required']) && $json['required'] == 1) array_push($attributi, "required");
	if (isset($json['maxlength']) && $json['maxlength'] != '') {
		array_push($attributi, "maxlength");
		$valori["maxlength"] = $json['maxlength'];
	}

	$value = (isset($json['value'])) ? $json['value'] : "";
	$element_id = (isset($json['id']) && $json['id'] != '') ? $json['id'] : str_replace(array("[","]"), "", $json['name']);

	// Rimuove caratteri indesiderati relativi al nome
	array_push($attributi, 'id');
	$valori["id"] = $element_id;
	array_push($attributi, 'name');
	$valori["name"] = $json['name'];

	// Label
	if (in_array("required", $attributi)) $json['label'] .= "*";

	$html = '
	<div class="form-group">';
	
	if (! isset($json['no-label']) || $json['no-label'] == 0){
		$html .= '
		<label for="' . $element_id . '">';
		if(isset($json['help']) && $json['help'] != "") $html .= '<span class="tip" title="'.$json['help'].'">';
		$html .=  $json['label'];
		if(isset($json['help']) && $json['help'] != "") $html .= '</span>';
		$html .= '</label>';
	}

	if (isset($json['icon-before']) || isset($json['icon-after'])) $html .= '
		<div class="input-group">';

	if (isset($json['icon-before'])) $html .= '
			<span class="input-group-addon">' . $json['icon-before'] . '</span>';

	switch ($json['type']) {
		case 'text' :
		case 'date' :
		case 'password' :
			if ($json['type'] == 'date') {
				array_push($attributi, "data-inputmask");
				$valori["data-inputmask"] = "'alias': 'dd/mm/yyyy'";
				array_push($valori["class"], "datepicker");

				if ($value == "0000-00-00 00:00:00" || $value == "0000-00-00") $value = "";
				else $value = date("d/m/Y", strtotime($value));

				if ($value == "01/01/1970") $value = "";
			}

			$tipo = ($json['type'] == 'password') ? $json['type'] : $tipo = 'text';
			array_push($attributi, 'type');
			$valori["type"] = $tipo;

			$html .= '
			<input |attr|>';
			break;

		case 'select' :
			$values = isset($json['values']) ? $json['values'] : "";

			if (isset($json['multiple']) && $json['multiple'] == 1) array_push($attributi, "multiple");

			if (isset($json['ajax-source']) && $json['ajax-source'] != "") {
				array_push($valori["class"], "superselectajax");
				array_push($attributi, "data-source");
				$valori["data-source"] = $json['ajax-source'];
			}
			else
				array_push($valori["class"], "superselect");

			$placeholder = isset($json['placeholder']) ? $json['placeholder'] : "- Seleziona un'opzione -";
			if (strpos($value, "Seleziona") !== false) {
				$placeholder = $value;
				$value = "";
			}

			$html .= '
			<select |attr|>';

			if (isset($json['ajax-source']) && $json['ajax-source'] != "" && $value != "") {
				$id_elemento = $value;
				$op = $json['ajax-source'];

				ob_start();
				include ($docroot . "/ajax_select2.php");
				$text = ob_get_clean();

				//Per debug, abilitare
				//echo $text;
				
				$array = json_decode($text);

				unset($id_elemento);
				unset($op);

				foreach ($array as $el) {
					$el = ( array ) $el;
					if (isset($el['children'])) {
						foreach ($el['children'] as $child) {
							$child = ( array ) $child;

							$sub_attr = array();
							if (in_array($child['id'], explode(',', $value)) || ($child['id'] == $value)) array_push($sub_attr, 'selected="true"');
							if ($child['_bgcolor_'] != '') array_push($sub_attr, 'style="background:' . $child['_bgcolor_'] . '; color:' . color_inverse($child['_bgcolor_']) . ';"');

							// Leggo ulteriori campi oltre a id e descrizione per inserirli nell'option nella forma "data-nomecampo1", "data-nomecampo2", ecc
							foreach ($child as $k => $v) {
								if ($k != 'id' && $k != 'text') array_push($sub_attr, 'data-' . $k . '="' . $v . '"');
							}

							$html .= '
				<option value="' . $child['id'] . '" ' . implode(" ", $sub_attr) . '>' . $child['text'] . '</option>';
						}
					}
					else {

						$sub_attr = array();
						if (in_array($el['id'], explode(',', $value)) || ($el['id'] == $value)) array_push($sub_attr, 'selected="true"');
						if ($el['_bgcolor_'] != '') array_push($sub_attr, 'style="background:' . $el['_bgcolor_'] . '; color:' . color_inverse($el['_bgcolor_']) . ';"');

						// Leggo ulteriori campi oltre a id e descrizione per inserirli nell'option nella forma "data-nomecampo1", "data-nomecampo2", ecc
						foreach ($el as $k => $v) {
							if ($k != 'id' && $k != 'text') array_push($sub_attr, 'data-' . $k . '="' . $v . '"');
						}

						$html .= '
				<option value="' . $el['id'] . '" ' . implode(" ", $sub_attr) . '>' . $el['text'] . '</option>';
					}
				}
			}
			// Generazione <select> da query
			else if (preg_match_all("/^query=(.+?)$/", $values, $m)) {
				$q = $m[1][0];
				$q = str_replace("<?php echo ", "\".", $q);
				$q = str_replace("; ?>", ".\"", $q);
				$q = str_replace("?>", ".\"", $q);
				eval("\$query = \"" . $q . "\";");
				$rs = $dbo->fetchArray($query);

				if (!isset($json['multiple']) || ! $json['multiple']) {
					$html .= '
				<option></option>';
				}

				// se non presente, carica eventuale valore predefinito
				if (($value == "0" || $value == "") && isset($json['valore_predefinito']) && $json['valore_predefinito'] != "") $value = get_var($json['valore_predefinito']);

				$prev = "";
				for($i = 0; $i < sizeof($rs); $i ++) {
					if (isset($rs[$i]["optgroup"])) {
						if ($prev != $rs[$i]["optgroup"]) {
							$html .= '
				<optgroup label="' . $rs[$i]["optgroup"] . '"></optgroup>';
							$prev = $rs[$i]["optgroup"];
						}
						$rs[$i]['descrizione'] = "&nbsp;&nbsp;&nbsp;" . $rs[$i]['descrizione'];
					}
					$sub_attr = array();
					if (in_array($rs[$i]['id'], explode(',', $value)) || ($rs[$i]['id'] == $value)) array_push($sub_attr, 'selected="true"');
					if (isset($rs[$i]['_bgcolor_']) && $rs[$i]['_bgcolor_'] != '') array_push($sub_attr, 'style="background:' . $rs[$i]['_bgcolor_'] . '; color:' . color_inverse($rs[$i]['_bgcolor_']) . ';"');

					// Leggo ulteriori campi oltre a id e descrizione per inserirli nell'option nella forma "data-nomecampo1", "data-nomecampo2", ecc
					foreach ($rs[$i] as $k => $v) {
						if ($k != 'id' && $k != 'descrizione' && $k != 'optgroup') array_push($sub_attr, 'data-' . $k . '="' . $v . '"');
					}

					$html .= '
				<option value="' . $rs[$i]['id'] . '" ' . implode(" ", $sub_attr) . '>' . $rs[$i]['descrizione'] . '</option>';
				}
			}

			// Generazione <select> da JSON
			// esempio creazione select con opzioni: Maschio, Femmina, Unisex
			// {[ "type": "select", "label": "Sesso", "name": "sesso", "required": 0, "class": "", "values": "list=\"\": \"\", \"M\": \"Maschio\", \"F\": \"Femmina\", \"U\": \"Unisex\"", "value": "$sesso$", "extra": "" ]}
			else if (preg_match_all("/^list=(.+?)$/", $values, $m)) {
				$data = json_decode("{" . $m[1][0] . "}");
				foreach ($data as $id => $etichetta) {
					$sub_attr = array();
					if ($id == $value) array_push($sub_attr, 'selected="true"');
					$html .= '
				<option value="' . $id . '" ' . implode(" ", $sub_attr) . '>' . $etichetta . '</option>';
				}
			}

			array_push($attributi, "data-placeholder");
			$valori["data-placeholder"] = $placeholder;

			$html .= '
			</select>';

			if (in_array("disabled", $attributi) || in_array("readonly", $attributi)) $html .= '
			<script>$("#' . $element_id . '").prop("disabled", true);</script>';

			if (in_array("readonly", $attributi)) {
				$html .= '
				<select class="hide" name="' . $json['name'] . '"';
				if (in_array("multiple", $attributi)) $html .= ' multiple';
				$html .= '>';

				$val = explode(",", $value);
				foreach ($val as $v) {
					$html .= '
				<option value="' . $v . '" selected="true"></option>';
				}

				$html .= '
			</select>';
			}

			break;

		case 'textarea' :
			$html .= '
			<textarea |attr|>' . $value . '</textarea>';
			unset($value);
			break;

		case 'checkbox' :
			if ($value == 1) {
				array_push($attributi, "checked");
				$valori["checked"] = "true";
				$value = "on";
			}

			if (in_array("readonly", $attributi)) array_push($attributi, "disabled");

			array_push($attributi, 'type');
			$valori["type"] = "checkbox";

			$placeholder = (isset($json["placeholder"])) ? $json["placeholder"] : $json["label"];

			$html .= '
			<div class="input-group">
				<span class="input-group-addon">
					<input |attr|>';
			if (in_array("readonly", $attributi)) $html .= '
					<input type="hidden" name="' . $json['name'] . '" value="' . $value . '">';
			$html .= '
				</span>
				<input type="text" class="form-control" placeholder="' . $placeholder . '" disabled>
			</div>';

			unset($valori["class"][0]);
			unset($value);

			break;

		case 'image' :
			unset($valori["class"][0]);
			// Form upload
			if ($value == '') {
				array_push($attributi, 'type');
				$valori["type"] = "file";
				$html .= '
			<input |attr|>';
			}
			// Visualizzazione immagine e spunta per cancellazione
			else {
				array_push($valori["class"], "img-thumbnail");
				array_push($valori["class"], "img-responsive");
				$html .= '
			<img src="' . $json['value'] . '" class="' . implode(" ", $valori["class"]) . '" id="img_' . $element_id . '" ' . $attr . ' ' . $json['extra'] . '><br>
			<label>
				<input type="checkbox" onclick="if( $(this).is(\':checked\') ){ $(\'#' . $element_id . '\').val(\'deleteme\'); }else{ $(\'#' . $element_id . '\').val( $(\'#prev_' . $element_id . '\').val() ); }">
				' . _("Elimina") . '
			</label>
			<input type="hidden" name="' . $json['name'] . '" value="' . $json['value'] . '" id="' . $element_id . '">
			<input type="hidden" name="prev_' . $json['name'] . '" value="' . $json['value'] . '" id="prev_' . $element_id . '">';
			}

			unset($value);

			break;

		default :
			$html .= "	<span |attr|>" . $value . "</span>\n";
			break;
	}

	if (isset($json['icon-after'])) {
		$html .= '
		<span class="input-group-addon';
		if (strpos("<button", $json['icon-after']) == 0) $html .= ' no-padding';
		$html .= '">' . $json['icon-after'] . '</span>';
	}

	if (isset($json['icon-before']) || isset($json['icon-after'])) {
		$html .= '
		</div>';
	}

	$html .= '
	</div>';

	if(isset($script_value) && $script_value != ""){
		$html .= '
	<script>
		$("#'.$element_id.'").val("'.addslashes($script_value).'");
	</script>';
	}

	if (isset($json['extra'])) array_push($attributi, trim($json['extra']));

	if (isset($value)) {
		array_push($attributi, 'value');
		$valori["value"] = $value;
	}

	$result = array();
	foreach ($attributi as $attributo) {
		$valore = $attributo;
		if (isset($valori[$attributo]) && $valori[$attributo] != "") {
			if (is_array($valori[$attributo])) $valore .= '="' . implode(" ", $valori[$attributo]) . '"';
			else $valore .= '="' . $valori[$attributo] . '"';
		}
		array_push($result, $valore);
	}

	$html = str_replace("|attr|", implode(" ", $result), $html);

	return $html;
}
?>

