<?php
include_once(__DIR__."/../../core.php");
include_once (__DIR__."/../../lib/function_home.php");
$name="Viste";

$record = $records[0];
echo '
<form action="" method="post" role="form">
	<input type="hidden" name="backto" value="record-edit">
	<input type="hidden" name="op" value="update">

	<div class="panel panel-primary">
		<div class="clearfix"></div>
		</br>	
		
		<div class="col-md-4">				
			<div class="pull-left">		
				<button type="submit" class="btn-app btn-success"><i class="fa fa-check"></i> Salva </button>	';						
				?>
				<button type="button" class="btn-app btn-primary" data-href="<?php echo $rootdir ?>/modules/viste/duplica_vista.php?idvista=<?php echo $id_record ?>" data-toggle="modal" data-title="Duplica Vista" data-target="#bs-popup"><i class="fa fa-files-o"></i> Duplica </a>
			
			
			
			
			<?php
			echo '
			</div>
		</div>
		
		<div class="col-md-4">				
			<div class="pull-right">	';

				if( $records[0]['mod_personale'] =='1' ){
				?>					
					<div class="pull-right showcase sweet"> 		
						<button type="button" class="btn-app btn-danger" aria-label="Show SweetAlert2 success message" ><i class="fa fa-trash-o"></i> Elimina</span></button>		
					</div>	
				<?php } 	
echo '
			
			</div>	
		</div>
		
		<div class="col-md-4">		
		</div>			
		<div class="clearfix"></div>
		
	</div>
	

	<!-- DATI -->
	<div class="panel panel-primary">
		<div class="panel-heading">
			<h3 class="panel-title">' . _("Opzioni di visualizzazione") . '</h3>
		</div>

		<div class="panel-body">';
$options = ($record["options2"] == "") ? $record["options"] : $record["options2"];
if ($options == "menu") echo '
			<p><strong>' . _("Il modulo che stai analizzando è un semplice menu") . '.</strong></p>';
else if ($options == "custom") echo '
			<p><strong>' . _("Il modulo che stai analizzando possiede una struttura complessa") . '.</strong></p>';

$total = getQuery($id_record);
if(strpos($options, "|fields|") === false){
	$module_query = json_decode($options, true);
	$module_query = $module_query['main_query'][0]['query'];
}
$module_query = str_replace("|fields|", $total["select"], $module_query);
$module_query = str_replace("|period_start|", $_SESSION['period_start'], $module_query);
$module_query = str_replace("|period_end|", $_SESSION['period_end'], $module_query);

	$module_query_sql=testa_query_sql($id_record);

echo '
			<div class="row">
				<div class="col-xs-12 col-md-6">
					{[ "type": "text", "label": "' . _("Nome del modulo") . '", "name": "name", "value": "' . $record["name"] . '", "readonly": "1" ]}
				</div>

				<div class="col-xs-12 col-md-6">
					{[ "type": "text", "label": "' . _("Nome personalizzato") . '", "name": "name2", "value": "' . $record["name2"] . '", "help": "Il nome che identifica il modulo" ]}
				</div>
			</div>

			<div class="row">
				<div class="col-xs-12 col-md-6">
					{[ "type": "textarea", "label": "' . _("Query di default") . '", "name": "options", "value": "'.str_replace("]}", "] }", $record["options"]) .'", "readonly": "1", "class": "autosize" ]}
				</div>

				<div class="col-xs-12 col-md-6">
					{[ "type": "textarea", "label": "' . _("Query personalizzata") . '", "name": "options2", "value": "'.str_replace("]}", "] }", $record["options2"]) .'", "class": "autosize", "help": "La query in sostituzione a quella di default: custom, menu oppure <SQL>" ]}
				</div>								
			</div>';																				
			
	
if ($options != "" && $options != "menu" && $options != "custom") echo '
			<div class="row">
				<div class="col-xs-12 col-md-12">
					<p><strong>Query risultante:</strong></p>
					<p>'. $module_query_sql . '</p>
				</div>
				
			</div>';

				
			
echo '
		</div>
	</div>';

if ($options != "" && $options != "custom") {
	echo '

	<div class="row">
		<div class="col-xs-12 col-md-9">
			<div class="panel panel-primary">
				<div class="panel-heading">
					<h3 class="panel-title">' . _("Campi disponibili") . '</h3>
				</div>

				<div class="panel-body">
					<div class="data">';
	$i = 0;
	$fields = $dbo->fetchArray("SELECT * FROM zz_viste WHERE id_module=" . $record['id'] . " ORDER BY `order` ASC");
	if ($fields != null) {
		foreach ($fields as $field) {
			echo '
					<div class="box ';
			if ($field["enabled"]) echo 'box-success';
			else echo 'box-danger';
			echo '">
							<div class="box-header with-border">
								<h3 class="box-title">
									<a data-toggle="collapse" href="#collapse'.$field["order"].'">' . str_replace("_POSITION_", $field["order"], _("Campo in posizione _POSITION_")) . ' ('.$field["name"].')</a>
								</h3>';
			if (! $field["default"]) {
				echo '
								<a class=" btn btn-danger pull-right" onclick="';
				echo "if(confirm('" . _("Eliminare questo elemento?") . "')){ location.href='" . $rootdir . "/editor.php?id_module=" . $id_module . "&id_record=" . $id_record . "&op=delete&id=" . $field['id'] . "'; }";
				echo '"><i class="fa fa-trash"></i> ' . _("Elimina") . '</a>';
			}
			echo '
							</div>
							<div id="collapse'.$field["order"].'" class="box-body collapse">
								<div class="row">
									<input type="hidden" value="' . $field["id"] . '" name="id[' . $i . ']">

									<div class="col-xs-12 col-md-6">
										{[ "type": "text", "label": "' . _("Nome") . '", "name": "name[' . $i . ']", "value": "' . $field["name"] . '"';
			if ($field["default"]) echo ', "readonly": "1"';
			echo ', "help": "Nome con cui il campo viene identificato e visualizzato nella tabella" ]}
									</div>

									<div class="col-xs-12 col-md-6">
										{[ "type": "text", "label": "' . _("Query prevista") . '", "name": "query[' . $i . ']", "value": "' . $field["query"] . '"';
			if ($field["default"]) echo ', "readonly": "1"';
			echo ', "required": "1", "help": "Nome effettivo del campo sulla tabella oppure subquery che permette di ottenere il valore del campo" ]}
									</div>
								</div>

								<div class="row">
									<div class="col-xs-12 col-md-6">
										{[ "type": "select", "label": "' . _("Gruppi con accesso") . '", "name": "gruppi[' . $i . '][]", "multiple": "1",  "values": "query=SELECT id, nome AS descrizione FROM zz_gruppi ORDER BY id ASC", "value": "';
			$groups = "";
			$results = $dbo->fetchArray("SELECT id_gruppo FROM zz_gruppi_viste WHERE id_vista=" . prepare($field["id"]));
			if ($results != null) {
				$n = count($results);
				for($d = 0; $d < $n; $d ++) {
					$groups .= $results[$d]["id_gruppo"];
					if ($d < $n - 1) $groups .= ",";
				}
			}
			echo $groups . '"';
			if ($field["default"]) echo ', "readonly": "1"';
			echo ', "help": "Gruppi di utenti in grado di visualizzare questo campo" ]}
									</div>

									<div class="col-xs-12 col-md-6">
										{[ "type": "select", "label": "' . _("Visibilità") . '", "name": "enabled[' . $i . ']", "values": "list=\"1\": \"' . _("Visibile nella sezione") . '\",\"0\":\"' . _("Nascosto (variabili di stato)") . '\"", "value": "' . $field['enabled'] . '"';
			if ($field["default"]) echo ', "readonly": "1"';
			echo ', "help": "Stato del campo: visibile nella tabella oppure nascosto" ]}
									</div>
								</div>

			<div class="row">					
								
					<div class="col-xs-12 col-md-2">
										{[ "type": "select", "label": "' . _("Allineamento") . '", "name": "allineamento[' . $i . ']", "values": "list=\"0\": \"' . _("Left") . '\", \"1\":\"' . _("Right") . '\" , \"2\":\"' . _("Center") . '\"", "value": "' . $field['allineamento'] . '"';
			if ($field["default"]) echo ', "readonly": "1"';
			echo ', "help": "Impostazione allineamento" ]}
									</div>
					
					<div class="col-xs-12 col-md-2">
										{[ "type": "checkbox", "label": "' . _("Grasetto") . '", "name": "grassetto[' . $i . ']", "value": "' . $field["grassetto"] . '"';
			if ($field["default"]) echo ', "readonly": "1"';
			echo ', "help": "Indica se il testo deve essere in grassetto" ]}
									</div>		
								
								
					<div class="col-xs-12 col-md-2">
										{[ "type": "text", "label": "' . _("A capo dopo") . '", "name": "capo_caratteri[' . $i . ']", "value": "' . $field["capo_caratteri"] . '"';
			if ($field["default"]) echo ', "readonly": "1"';
			echo ', "help": "Numero caratteri per andare a capo" ]}
									</div>			
								
								
								
			</div>					
								
								
								
								
								<div class="row">
									<div class="col-xs-12 col-md-4">
										{[ "type": "checkbox", "label": "' . _("Ricercabile") . '", "name": "search[' . $i . ']", "value": "' . $field["search"] . '"';
			if ($field["default"]) echo ', "readonly": "1"';
			echo ', "help": "Indica se il campo è ricercabile" ]}
									</div>';

								//	<div class="col-xs-12 col-md-4">
								//		{[ "type": "checkbox", "label": "' . _("Ricerca lenta") . '", "name": "slow[' . $i . ']", "value": "' . $field["slow"] . '"';
		//	if ($field["default"]) echo ', "readonly": "1"';
		//	echo ', "help": "Indica se la ricerca per questo campo è lenta (da utilizzare nel caso di evidenti rallentamenti, mostra solo un avviso all\'utente)" ]}
		//							</div>
echo '
									<div class="col-xs-12 col-md-4">
										{[ "type": "checkbox", "label": "' . _("Sommabile") . '", "name": "sum[' . $i . ']", "value": "' . $field["summable"] . '"';
			if ($field["default"]) echo ', "readonly": "1"';
			echo ', "help": "Indica se il campo è da sommare" ]}
									</div>
									
									
									
								</div>

								<div class="row">
									<div class="col-xs-12 col-md-12">
										{[ "type": "text", "label": "' . _("Ricerca tramite") . '", "name": "search_inside[' . $i . ']", "value": "' . $field["search_inside"] . '"';
			if ($field["default"]) echo ', "readonly": "1"';
			echo ', "help": "Query personalizzata per la ricerca (consigliata per colori e icone)" ]}
									</div>';
									

//									<div class="col-xs-12 col-md-6">
//										{[ "type": "text", "label": "' . _("Ordina tramite") . '", "name": "order_by[' . $i . ']", "value": "' . $field["order_by"] . '"';
//			if ($field["default"]) echo ', "readonly": "1"';
//			echo ', "help": "Query personalizzata per l\'ordinamento (date e numeri formattati tramite query)" ]}
//									</div>
	echo '
								</div>
							</div>
						</div>';
			$i ++;
		}
	}
	echo '
				</div>

				<div class="pull-right">
					<button type="button" class="btn btn-info" id="add"><i class="fa fa-plus"></i> ' . _("Aggiungi") . '</button>
					<button type="submit" class="btn btn-success"><i class="fa fa-check"></i> ' . _("Salva") . '</button>
				</div>

				</div>
			</div>
		</div>

		<div class="col-xs-12 col-md-3">
			<div class="panel panel-primary">
				<div class="panel-heading">
					<h3 class="panel-title">' . _("Ordine di visualizzazione") . '</h3>
				</div>

				<div class="panel-body sortable">';

	if ($fields != null) {
		foreach ($fields as $field) {
			echo '
				<p data-id="' . $field["id"] . '" data-idm="' . $record["id"] . '">
					<i class="fa fa-sort"></i>
					';
			if ($field["enabled"]) echo '<strong class="text-success">' . $field["name"] . '</strong>';
			else echo '<span class="text-danger">' . $field["name"] . '</span>';
			echo '
				</p>';
		}
	}
	echo '
			</div>
		</div>
	</div>';
}
echo '

</form>';
if ($options != "" && $options != "custom") {
	echo '
<form class="hide" id="template">
	<div class="box">
		<div class="box-header with-border">
			<h3 class="box-title">' . _("Nuovo campo") . '</h3>
		</div>
		<div class="box-body">
			<div class="row">
				<input type="hidden" value="" name="id[-id-]">

				<div class="col-xs-12 col-md-6">
					{[ "type": "text", "label": "' . _("Nome") . '", "name": "name[-id-]" ]}
				</div>

				<div class="col-xs-12 col-md-6">
					{[ "type": "text", "label": "' . _("Query prevista") . '", "name": "query[-id-]" ]}
				</div>
			</div>

			<div class="row">
				<div class="col-xs-12 col-md-6">
					{[ "type": "select", "label": "' . _("Gruppi con accesso") . '", "name": "gruppi[-id-][]", "multiple": "1",  "values": "query=SELECT id, nome AS descrizione FROM zz_gruppi ORDER BY id ASC" ]}
				</div>

				<div class="col-xs-12 col-md-6">
					{[ "type": "select", "label": "' . _("Visibilità") . '", "name": "enabled[-id-]", "values": "list=\"1\": \"' . _("Visibile nella sezione") . '\",\"0\":\"' . _("Nascosto (variabili di stato)") . '\"" ]}
				</div>
			</div>

			<div class="row">
				<div class="col-xs-12 col-md-4">
					{[ "type": "checkbox", "label": "' . _("Ricercabile") . '", "name": "search[-id-]" ]}
				</div>

				<div class="col-xs-12 col-md-4">
					{[ "type": "checkbox", "label": "' . _("Ricerca lenta") . '", "name": "slow[-id-]" ]}
				</div>

				<div class="col-xs-12 col-md-4">
					{[ "type": "checkbox", "label": "' . _("Sommabile") . '", "name": "sum[-id-]" ]}
				</div>
			</div>

			<div class="row">
				<div class="col-xs-12 col-md-6">
					{[ "type": "text", "label": "' . _("Ricerca tramite") . '", "name": "search_inside[-id-]" ]}
				</div>

				<div class="col-xs-12 col-md-6">
					{[ "type": "text", "label": "' . _("Ordina tramite") . '", "name": "order_by[-id-]" ]}
				</div>
			</div>
		</div>
	</div>
</form>';

// NUOVO BLOCCO PER FILTRI

 echo '
<form action="" method="post" role="form">
	<input type="hidden" name="backto" value="record-edit">
	<input type="hidden" name="op" value="filters">

    <div class="col-md-12">
        <div class="panel panel-warning">
            <div class="panel-heading">
                <h3 class="panel-title">'.tr('Filtri viste per gruppo di utenti').'</h3>
            </div>

            <div class="panel-body">
                <div class="data">';

    $num = 0;
    $additionals = $dbo->fetchArray('SELECT * FROM zz_gruppi_modules WHERE idmodule='.$id_record.' ORDER BY `id` ASC');
    foreach ($additionals as $num => $additional) {
        $editable = !($additional["default"] && $enable_readonly);
				
		echo '
                    <div class="box ';
        if ($additional['enabled']) {
            echo 'box-success';
        } else {
            echo 'box-danger';
        }
        echo '">
                            <div class="box-header with-border">
                                <h3 class="box-title">
                                    <a data-toggle="collapse" href="#additional-'.$additional['id'].'">Filtro:'.$additional["name"].'</a>
                                </h3>';
	   

        echo '
                            </div>
                            <div id="additional-'.$additional['id'].'" class="box-body collapse">
									<div class="row">
										<div class="col-md-12">
											{[ "type": "textarea", "label": "'.tr('Query').'", "name": "query['.$num.']", "value": "'.$additional['clause'].'"';
        if (!$editable) {
            echo ', "readonly": "1"';
        }
        echo ' ]}
										</div>
									</div>

								<div class="row">
                                    <input type="hidden" value="'.$additional['id'].'" name="id['.$num.']">


									<div class="col-md-6">
										{[ "type": "text", "label": "'.tr('Name').'", "name": "name['.$num.']", "value": "'.$additional['name'].'"  ]}
									</div>
									
                                    <div class="col-md-3">
                                        {[ "type": "select", "label": "'.tr('Gruppo').'", "name": "gruppo['.$num.']",  "values": "query=SELECT id, nome AS descrizione FROM zz_gruppi ORDER BY id ASC", "value": "'.$additional['idgruppo'].'"';
        if (!$editable) {
            echo ', "readonly": "1"';
        }
        echo ' ]}
                                    </div>
									<div class="col-md-3">
										{[ "type": "checkbox", "label": "'.tr('Abilita').'", "name": "enabled['.$num.']", "value": "'.$additional['enabled'].'"  ]}
									</div>
                                   								
								</div>
								<div class="row">	
									';
		if ($additional['default'] == '0' ){
			echo '							
									<div class="col-md-3">
										{[ "type": "checkbox", "label": "'.tr('Rimuovi').'", "name": "rimuovi['.$num.']", "value": ""  ]}
									</div>';
		 }
		 echo '	
								</div>

                            </div>
                        </div>';
    }
    echo '
                </div>

                <div class="row">
                    <div class="col-md-12 text-right">
                        <button type="button" class="btn btn-info" id="add_filter">
                            <i class="fa fa-plus"></i> '.tr('Aggiungi nuovo filtro').'
                        </button>

                        <button type="submit" class="btn btn-success">
                            <i class="fa fa-check"></i> '.tr('Salva').'
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</form>';

    echo '
<form class="hide" id="template_filter">
	<div class="box">
		<div class="box-header with-border">
			<h3 class="box-title">'.tr('Nuovo filtro').'</h3>
		</div>
		<div class="box-body">

			<div class="row">
				<div class="col-md-12">
					{[ "type": "textarea", "label": "'.tr('Query').'", "name": "query[-id-]" ]}
				</div>
			</div>

			<div class="row">
				<input type="hidden" value="" name="id[-id-]">

				<div class="col-md-6">
					{[ "type": "text", "label": "'.tr('Nome').'", "name": "name[-id-]" ]}
				</div>

				<div class="col-md-3">
					{[ "type": "select", "label": "'.tr('Gruppo').'", "name": "gruppo[-id-]", "values": "query=SELECT id, nome AS descrizione FROM zz_gruppi ORDER BY id ASC" ]}
				</div>

               
		</div>
	</div>
</form>';




echo '
<script>
function replaceAll(str, find, replace) {
  return str.replace(new RegExp(find, \'g\'), replace);
}
$(document).ready(function(){
	var n = ' . $i . ';
	$(document).on(\'click\', \'#add\', function(){
		$(\'#template .superselect, #template .superselectajax\').select2().select2("destroy");
		n++;
		var text = replaceAll($(\'#template\').html(), "-id-", ""+n);
		$(this).parent().parent().find(\'.data\').append(text);
		start_superselect();
	});
	
	var i = '.$num.';
	$(document).on("click", "#add_filter", function(){
		$("#template_filter .superselect, #template_filter .superselectajax").select2().select2("destroy");
		i++;
		var text = replaceAll($("#template_filter").html(), "-id-", "" + i);
		$(this).parent().parent().parent().find(".data").append(text);
		start_superselect();
	});
	
	
	$( ".sortable" ).disableSelection();
	$(".sortable").each(function() {
		$(this).sortable({
			cursor: \'move\',
			dropOnEmpty: true,
			scroll: true,
			start: function(event, ui) {
				ui.item.data(\'start\', ui.item.index());
			},
			update: function(event, ui) {
				$.get("' . $rootdir . '/editor.php", {
					id: ui.item.data(\'id\'),
					id_module: ' . $id_module . ',
					id_record: ' . $id_record . ',
					op: \'update_position\',
					start: ui.item.data(\'start\'),
					end: ui.item.index()
				});
			}
		});
	});
	
	
	
});
</script>';

}
?>

<script>


$('.showcase.sweet button').on('click', () => {
		swal({
		  title: 'Sei sicuro?',
		  text: "Eliminare questo elemento!",
		  type: 'warning',
		  showCancelButton: true,
		  confirmButtonColor: '#3085d6',
		  cancelButtonColor: '#d33',
		  confirmButtonText: 'Conferma!'
		}).then((result) => {
		  if (result.value) {			
			{ $('#form-delete_vista').submit(); }
		  }
		})
	})		

</script>
<form action="" method="post" role="form" id="form-delete_vista">
	<input type="hidden" name="backto" value="record-list">
	<input type="hidden" name="op" value="delete_vista">
</form>