<?php
// Possibile ulteriore implementazione: eseguire un controllo sui permessi dell'utente per limitare lo scaricamento dei dati.
header("Access-Control-Allow-Origin: *");
include_once (__DIR__ . "/../core.php");
include ("./lib/modutil.php");

$key = filter("key");
if (! isset($key) || ! user_check($key)) {
	echo "-1";
	return false;
}

$id = filter('id');
$search = filter('search');
$reduced = filter('reduced');
$last_updated = filter('upd');
$operation = filter('op');

$campi = filter('campi');
$value = filter('values');
$table = filter('table');
$str_update = filter('str_update');





$select = "*";
$where = "";
$order = "";


// c0e024d9200b5705bc4804722636378a


// http://localhost/ges360v2/api/?key=c0e024d9200b5705bc4804722636378a&table=in_mail&campi=oggetto,contenuto&values='testoggetto','test contenuto'&op=insert

$results = array();

switch ($operation) {
	case 'updates' :
		if (isset($last_updated)) $where = " WHERE updated_at >= " . prepare($last_updated);

		$excluded = explode(",", get_var("API_excluded_tables"));
		
		// Attenzione: query specifica per MySQL
		$datas = $dbo->fetchArray("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA=" . prepare($db_name));
		if ($datas != null) {
			foreach ($datas as $data) {
				if (! in_array($data["TABLE_NAME"], $excluded)) $results[$data["TABLE_NAME"]] = $dbo->fetchArray("SELECT * FROM " . $data["TABLE_NAME"] . $where);
			}
		}
		break;

	case 'update' :
		
		$results = $dbo->query("update ".$table." " . $str_update  . ")");
		
		break;
	
	
	case 'insert' :
		
		$results = $dbo->query("insert into ".$table." (" . $campi . ") VALUES (" . $value . ")");
		
		break;
	case 'deleted':
		if (isset($last_updated)) $where = "AND updated_at >= " . prepare($last_updated);

		$excluded = explode(",", get_var("API_excluded_tables"));
		
		// Attenzione: query specifica per MySQL
		$datas = $dbo->fetchArray("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA=" . prepare($db_name));
		if ($datas != null) {
			foreach ($datas as $data) {
				$id = $dbo->fetchArray("SELECT `id` FROM `zz_tables` WHERE `name`=".prepare($data["TABLE_NAME"]));
				if (! in_array($data["TABLE_NAME"], $excluded) && $id != null){
					$id = $id[0]['id'];

					$deleted = $dbo->fetchArray("SELECT SQL_CALC_FOUND_ROWS `id` FROM `zz_deleted` WHERE `id_table`=".prepare($id)." ORDER BY `id` ASC");
					$cont_del = $dbo->fetchArray("SELECT FOUND_ROWS()")[0]['FOUND_ROWS()'];

					$column = $dbo->fetchArray("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ".prepare($data["TABLE_NAME"])." AND EXTRA LIKE '%AUTO_INCREMENT%' AND TABLE_SCHEMA = ".prepare($db_name))[0]['COLUMN_NAME'];

					$temps = $dbo->fetchArray("SELECT SQL_CALC_FOUND_ROWS `".$column."` FROM `".$data["TABLE_NAME"]."` ORDER BY `".$column."` ASC");
					$cont = $dbo->fetchArray("SELECT FOUND_ROWS()")[0]['FOUND_ROWS()'];

					$result = $dbo->fetchArray("SELECT AUTO_INCREMENT FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = ".prepare($data["TABLE_NAME"])." AND TABLE_SCHEMA = ".prepare($db_name));
					for($i = 1; $i<$result[0]['AUTO_INCREMENT']; $i++){
						if(ricerca($temps, $i, $cont, $column) == -1 && ricerca($deleted, $i, $cont_del) == -1) {
							$dbo->query("INSERT INTO `zz_deleted` (`id`, `id_table`) VALUES (".prepare($i).", ".prepare($id).")");
						}
					}
					
					$results[$data["TABLE_NAME"]] = $dbo->fetchArray("SELECT `id` FROM `zz_deleted` WHERE `id_table`=".prepare($id)." ".$where." ORDER BY `id` ASC");
				}
			}
		}

		break;

	case 'interventi' :
		$order = "ORDER BY idintervento";

		if (isset($id)) $where = "WHERE `idintervento`=" . prepare($id);
		else {
			if (isset($reduced)) $select = "`idintervento`";
		}

		$results = $dbo->fetchArray("SELECT " . $select . " FROM `in_interventi` " . $where . " " . $order);

		break;

	case 'anagrafiche' :
		$order = "ORDER BY `idanagrafica`";

		if (isset($id)) $where = "WHERE `idanagrafica`=" . prepare($id);
		else {
			if (isset($search)) $where = "WHERE `ragione_sociale` LIKE " . prepare("%" . $search . "%");
			if (isset($reduced)) $select = "`idanagrafica`";
		}

		$results = $dbo->fetchArray("SELECT " . $select . " FROM `an_anagrafiche` " . $where . " " . $order);

		break;
	case 'import' :
		

		$results = $dbo->fetchArray("SELECT * FROM ".$table);

		break;

	default :
		break;
}

echo json_encode($results,  JSON_PRETTY_PRINT); // JSON_FORCE_OBJECTJSON_PRETTY_PRINT
?>
