<?php
	define('PREPEND_PATH', '');
	$app_dir = dirname(__FILE__);
	include("{$app_dir}/defaultLang.php");
	include("{$app_dir}/language.php");
	include("{$app_dir}/lib.php");

	/*
	 * calculated fields configuration array, $calc:
	 *         table => [calculated fields], ..
	 *         where calculated fields:
	 *             field => query, ...
	 */
	$calc = array(
		'main' => array(
		),
		'clients' => array(
		),
		'gestionnaires' => array(
		),
		'partenaires' => array(
		),
		'paiements' => array(
		),
		'emetteurs' => array(
		),
		'bieleteries' => array(
		),
		'tarifs' => array(
		),
		'transferts_argent' => array(
		),
		'colis' => array(
		),
		'envois_colis' => array(
		),
		'parc_auto' => array(
		),
		'location_vh' => array(
		),
		'liste_location' => array(
		),
		'fonctions' => array(
		),
		'agences' => array(
		),
		'villes' => array(
		),
		'banques' => array(
		),
		'type_paiements' => array(
		),
		'compagnies' => array(
		),
		'statuts' => array(
		),
		'visas' => array(
		),
		'oumras' => array(
			'duree_visa' => 'SELECT `oumras`.`fin_visa` - `oumras`.`debut_visa` FROM `oumras` 
WHERE `oumras`.`idoumra`=\'%ID%\'',
		),
		'assurances' => array(
		),
		'type_visas' => array(
		),
		'facture' => array(
		),
		'detail_facture' => array(
		),
		'recettes' => array(
		),
		'depenses' => array(
		),
		'caisse' => array(
			'recettes' => 'SELECT 
    SUM(montant) recettes
FROM 
    recettes;',
			'depenses' => 'SELECT 
    SUM(montant) depenses
FROM 
    depenses;',
			'caisse' => 'SELECT `caisse`.`recettes` - `caisse`.`depenses` 
FROM `caisse` 
WHERE `caisse`.`idcaisse`=\'%ID%\'',
		),
		'tresorerie_caisse' => array(
		),
		'tresorerie_items' => array(
			'commission_agence' => 'SELECT `tresorerie_items`.`montant` - `tresorerie_items`.`net_compagnie` FROM `tresorerie_items` 
WHERE `tresorerie_items`.`idtresorerie_item`=\'%ID%\'',
		),
		'piece_reglements' => array(
		),
		'autorisation_change' => array(
		),
		'bon_passage' => array(
		),
		'fiches_changes' => array(
		),
		'fiches_changes_items' => array(
		),
		'caisse_journaliere' => array(
		),
		'item_caisse_journaliere' => array(
		),
		'models' => array(
		),
		'natures' => array(
		),
		'services' => array(
		),
		'liens' => array(
		),
		'types_client' => array(
		),
		'cartes_fidelite' => array(
		),
		'designations' => array(
		),
		'parcours' => array(
		),
		'pays' => array(
		),
		'provenance' => array(
		),
		'programmes' => array(
		),
		'justificatifs' => array(
		),
		'devise' => array(
		),
		'intermediares' => array(
		),
		'formule' => array(
		),
		'operations' => array(
		),
		'pointages' => array(
		),
		'fichiers_partages' => array(
		),
		'note_de_service' => array(
		),
	);

	cleanup_calc_fields($calc);
	list($table, $id) = get_params();
	if(!$table || !strlen($id))
		return_json(array(), 'Access denied or invalid parameters');
	if(!isset($calc[$table]))
		return_json(array('table' => $table), 'No fields to calculate in this table');

	/*
		update_calc_fields($table, $id, $calc[$table])

		then, for each parent of $table and its parent's $parent_id 
		stored in record $id of $table:
		update_calc_fields($parent_table, $parent_id, $calc[$parent_table])
	 */
	$caluclations_made = array();
	$caluclations_made[] = update_calc_fields($table, $id, $calc[$table]);

	// get parents of current table
	$parents = get_parent_tables($table);
	$pk = getPKFieldName($table);
	$safe_id = makeSafe($id);
	foreach($parents as $pt => $mlufs /* main lookup fields in child */) {
		if(!isset($calc[$pt])) continue; // parent table has no calc fields

		foreach($mlufs as $mluf) {
			// retrieve parent record ID as stored in lookup field of current table
			$pid = sqlValue("SELECT `{$mluf}` FROM `{$table}` WHERE `{$pk}`='{$safe_id}'");
			if(!strlen($pid)) continue;

			$caluclations_made[] = update_calc_fields($pt, $pid, $calc[$pt]);
		}
	}

	return_json($caluclations_made);

	#############################################################

	function update_calc_fields($table, $id, $formulas) {
		$mi = getMemberInfo();
		$pk = getPKFieldName($table);
		$safe_id = makeSafe($id);
		$eo = array('silentErrors' => true);
		$caluclations_made = array();
		$replace = array(
			'%ID%' => $safe_id,
			'%USERNAME%' => makeSafe($mi['username']),
			'%GROUPID%' => makeSafe($mi['groupID']),
			'%GROUP%' => makeSafe($mi['group'])
		);

		foreach($formulas as $field => $query) {
			$query = str_replace(array_keys($replace), array_values($replace), $query);
			$calc_value = sqlValue($query);
			if($calc_value  === false) continue;

			// update calculated field
			$safe_calc_value = makeSafe($calc_value);
			$update_query = "UPDATE `{$table}` SET `{$field}`='{$safe_calc_value}' " .
				"WHERE `{$pk}`='{$safe_id}'";
			$res = sql($update_query, $eo);
			if($res) $caluclations_made[] = array(
				'table' => $table,
				'id' => $id,
				'field' => $field,
				'value' => $calc_value
			);
		}

		return $caluclations_made;
	}

	/* get and validate params */
	function get_params() {
		$ret_error = array(false, false);

		$table = $_REQUEST['table'];
		$id = $_REQUEST['id'];
		if(!get_sql_from($table)) return $ret_error;
		if(!check_record_permission($table, $id)) return $ret_error;

		return array($table, $id);
	}

	function return_json($data = array(), $error = '') {
		@header('Content-type: application/json');
		die(json_encode(array('data' => $data, 'error' => $error)));
	}

	function cleanup_calc_fields(&$calc) {
		foreach($calc as $tn => $conf) {
			if(!count($conf)) unset($calc[$tn]);
		}
	}
