<?php
include_once(__DIR__."/core.php");
include_once($docroot."/lib/function_gps.php");

$start = filter("start");
$length = filter("length");
$columns = filter("columns");
$order = filter("order")[0];
$_SESSION['id_module'] = $id_module;
$modulo_custom=get_var("Cartella Custom");
$total = getQuery($id_module);





// Lettura parametri modulo
$module = $dbo->fetchArray("SELECT * FROM zz_modules WHERE id=" . prepare($id_module))[0];
$module_query = ($module['options2'] != "") ? $module['options2'] : $module['options'];
if(strpos($module_query, "|fields|") === false){
	$module_query = json_decode($module_query, true);
	$module_query = $module_query['main_query'][0]['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 = str_replace("|fields|", $total["select"], $module_query);

$results = array();
$results["data"] = array();
$results["recordsTotal"] = 0;
$results["recordsFiltered"] = 0;
$results["summable"] = array();

/*
 * Modifico la query principale per limitare i record nel caso l'utente abbia permessi da limitare
 */
$permessi = $dbo->fetchArray("SELECT clause FROM zz_gruppi_modules WHERE idgruppo=(SELECT id FROM zz_gruppi WHERE nome=" . prepare($_SESSION['gruppo']) . ") AND idmodule=" . prepare($id_module));
if (sizeof($permessi) == 1) {
	// Includo il file init.php che contiene già i replace corretti di $additional_where[]
	if (file_exists($docroot . "/modules/" . $module['module_dir'] . "/".$modulo_custom."/init.php")) include ($docroot . "/modules/" . $module['module_dir'] . "/".$modulo_custom."/init.php");
	else if (file_exists($docroot . "/modules/" . $module['module_dir'] . "/init.php"))  include ($docroot . "/modules/" . $module['module_dir'] . "/init.php");
}

if ($module_query != '' && $module_query != 'menu' && $module_query != 'custom') {
	$query = str_replace_once("SELECT", "SELECT COUNT(*) as tot, ", $module_query);
	$cont = $dbo->fetchArray($query);
	if($cont!= null) $results["recordsTotal"] = $cont[0]['tot'];

	// Se ci sono dei parametri di ricerca per questo modulo li accodo alla query
	$search_filters = array();
	for($i = 0; isset($columns[$i]["search"]["value"]); $i ++) {
		if ($columns[$i]["search"]["value"] != "") {
			if(strpos($total["search_inside"][$i], "|search|") !== false){
				$sears = explode(",", $columns[$i]["search"]["value"]);
				foreach ($sears as $sear) {
					$sear = trim($sear);
					array_push($search_filters, str_replace("|search|", prepare("%".$sear."%"), $total["search_inside"][$i]));	
				}
			}
			else array_push($search_filters, "`".$total["search_inside"][$i] . "` LIKE ".prepare("%" . trim($columns[$i]["search"]["value"]) . "%"));
		}


		
	}


	
	if (sizeof($search_filters) > 0) {
		$module_query = str_replace("1=1", "1=1 AND (" . implode(" AND ", $search_filters) . ") ", $module_query);
	}

	// cerco se sono previsti dei filtri per i moduli esempio documenti
	$query_documenti="select  * from  zz_modules_documenti where idmodule='".$id_module."'";
	$rs_filtro = $dbo->fetchArray( $query_documenti );				
	if ( sizeof($rs_filtro)	== '1' ){			
		$module_query = str_replace( $rs_filtro[0]['cerca'], $rs_filtro[0]['sostituisci'] , $module_query );	
		if ( ($_SESSION['gruppo'] != 'Amministratori') && ($_SESSION['gruppo'] != 'Agenti') && ($_SESSION['gruppo'] != 'Tecnici') ){			
			$module_query = str_replace("1=1", "1=1 and co_documenti.idanagrafica='".$_SESSION['idanagrafica']."'", $module_query);
		}
	}
	

// NUOVO Aggiungo eventuali filtri dei permessi
	$id_gruppo=query_secca("","id","zz_gruppi","where nome ='".$_SESSION['gruppo']."'");
	$query_filtri="select  * from  zz_gruppi_modules where idmodule='".$id_module."' and idgruppo='".$id_gruppo."' and enabled='1'";
	
	$rs_filtro = $dbo->fetchArray( $query_filtri );				
	if ( sizeof($rs_filtro)	== '1' ){			
		$filtro=$rs_filtro[0]['clause'];
		$filtro=str_replace("|idanagrafica|", $_SESSION['idanagrafica'] , $filtro);
		$filtro=str_replace("|idagente|", $_SESSION['idanagrafica'] , $filtro);
		$filtro=str_replace("|idtecnico|", $_SESSION['idanagrafica'] , $filtro);
		$module_query = str_replace("1=1", "1=1 " . $filtro, $module_query);
	}
	// commento vecchia procedura di filtri per utente
		//if ($additional_where[$module_name] != '') {
		//	$module_query = str_replace("1=1", "1=1 " . $additional_where[$module_name], $module_query);
		//}
// Fine nuova procedura per filtri utente

	if (isset($order["dir"]) && isset($order["column"])) {
		$module_query = explode("ORDER", $module_query)[0] . "ORDER BY `" . $total["order_by"][$order["column"]] . "` " . $order["dir"];
	}

	if(count ($total["summable"])!=0){
		$query = str_replace_once("SELECT", "SELECT ".implode(",",$total["summable"])." FROM(SELECT ", $module_query).") AS `z`";
		$sums = $dbo->fetchArray($query)[0];
		if($sums != null){
			$r = array();
			foreach ($sums as $key => $sum) {
				if(strpos($key, "sum_") !== false) $r[str_replace("sum_", "", $key)] = $sum;
			}
			$results["summable"] = $r;
		}
	}

	// Paginazione
	$module_query .= " LIMIT " . $start . ", " . $length;
	
	
	$module_query = str_replace("and co_documenti.idanagrafica=|idanagrafica|", "" , $module_query);
	
	$query = str_replace_once("SELECT", "SELECT SQL_CALC_FOUND_ROWS", $module_query);
	

	$_SESSION['query_controller'] = $query;
	
	// generazione mappe in base al modulo
	if ( $modules_info[$id_module]['name'] == "Pianificazione" ){
		crea_paginagps_pianificazione();
	}
	if ( $modules_info[$id_module]['name'] == "Anagrafiche" ){
		crea_paginagps_ana();
	}
	if ( $modules_info[$id_module]['name'] == "Sedi" ){
		crea_paginagps_ana_sedi();
	}
	
	
	$rs = $dbo->fetchArray($query);

	
	
	
	
	$cont = $dbo->fetchArray("SELECT FOUND_ROWS()");
	if($cont!= null) $results["recordsFiltered"] = $cont[0]['FOUND_ROWS()'];

	//$rs = $dbo->fetchArray($module_query);

	for($r = 0; $r < sizeof($rs); $r ++) {
		$attr = '';

		if (isset($rs[$r]['_bg_']) && $rs[$r]['_bg_'] != '') {
			$attr .= ' data-background="' . $rs[$r]['_bg_'] . '" data-color:"' . color_inverse($rs[$r]['_bg_']) . '"';
		}

		$array = array();
		$num=0;
		
		foreach ($total["fields"] as $field) {
			

			$tag_start = "";
			$tag_end = "";
			$tag_start_img="";
			$tag_start_inc="";
			
			if ($total['grassetto'][$num] != '0') {
				$tag_start = "<b/>";
				$tag_start_inc = "<b/>";
			}
			
			
			// Allineamento a destra se il valore della prima riga sembra una valuta o è numerico
				
				// if (preg_match('/(,)/', $rs[$r][$field])) {		OLD PROCEDURA							
			if ($total['allineamento'][$num] == '1') {
				$tag_start ="<div class='text-right'>".$tag_start_inc;
				$tag_end = "</div>";
			}
			if ($total['allineamento'][$num] == '2') {
				$tag_start="<div class='text-center'>".$tag_start_inc;
				$tag_end= "</div>";
			}
			
	
			
	
			// Check per tipologie di campi particolari
			// Icona
			if (preg_match("/^color_(.+?)$/", $field, $m)) {
				if(isset($rs[$r]["color_title_" . $m[1]])) $title = htmlentities($rs[$r]["color_title_" . $m[1]]);
				else $title = "";
				$value = "<div class='img-responsive text-center small' data-background='" . $rs[$r][$field] . "' data-color:'" . color_inverse($rs[$r][$field]) . "' data-toggle=\"tooltip\" title=\"" . $title . "\">&nbsp;" . $title . "</div>";
			}

			// Icona di stampa
			else if (trim($field) == '_print_') {
				$print_url = $rs[$r]['_print_'];

				preg_match_all('/\$(.+?)\$/', $print_url, $matches);

				for($m = 0; $m < sizeof($matches[0]); $m ++) {
					$print_url = str_replace($matches[0][$m], $rs[$r][$matches[1][$m]], $print_url);
				}

				$value = "<a href='" . $rootdir . "/templates/" . $print_url . "' target='_blank'><i class='fa fa-2x fa-print'></i></a>";
			}
			
		// Imamgine
			else if (trim($field) == '_img_') {
				$image_path	= "files/articoli/".$rs[$r][$field];
				if( is_file($image_path) ){
					$tag_start_img = "<div class='pull-left image' valign='middle' >\n";
					$tag_start_img = $tag_start_img."<img src=".$image_path." class='img-thumbnail' >\n";
					$tag_start_img = $tag_start_img."</div>";
				}
				$value="";
				
				
			}
			
		// fine imamgine	
			
			// Data
			else if (preg_match("/^Data/", $field)) {
				
				
				$value = "<div class='text-center'>" . $rs[$r][$field] . "</div>";
			}
			// Icona
			else if (preg_match("/^icon_(.+?)$/", trim($field), $m)) {
				$value = '<div class="text-center"><i class="' . $rs[$r][$field] . '"></i> <small>' . $rs[$r]["icon_title_" . $m[1]] . '</small></div>';
			}
			else {
				$value = $rs[$r][$field];
			}

			if ($total['a_capo'][$num] != '0') {
				$value = wordwrap ($value, $total['a_capo'][$num] , "<br />" ,1);
			}
			
			
			
			// inizio colonna
			if (isset($rs[$r]['_link_']) && $rs[$r]['_link_'] != '') {
				$text = "<span data-link=\"" . $rootdir . $rs[$r]['_link_'] . "\"  " . $attr . ">";
			}
			else if (trim($field) == '_print_') $text = "<span " . $attr . ">";
			else $text = "<span data-link=\"editor.php?id_module=" . $id_module . "&id_record=" . $rs[$r]['id'] . "\" " . $attr . ">";

			
			
			
			
			$text .= " " . $tag_start . $tag_start_img . $value . $tag_end . "</span>";

			array_push($array, $text);
			$num=$num +1 ;
			// fine colonna
		}

		array_push($results["data"], $array);
	}
}

echo json_encode($results);

?>
