<?php
// This script and data application were generated by AppGini 5.71
// Download AppGini for free from https://bigprof.com/appgini/download/

	/* Configuration */
	/*************************************/

		$pcConfig = array(
			'clients' => array(   
				'ville' => array(   
					'parent-table' => 'villes',
					'parent-primary-key' => 'id',
					'child-primary-key' => 'idclient',
					'child-primary-key-index' => 0,
					'tab-label' => 'Clients',
					'auto-close' => true,
					'table-icon' => 'resources/table_icons/card_front.png',
					'display-refresh' => true,
					'display-add-new' => true,
					'forced-where' => '',
					'display-fields' => array(2 => 'Responsable administratif', 10 => 'DEPOT', 11 => 'RETRAIT', 12 => 'SOLDE'),
					'display-field-names' => array(2 => 'responsable_administratif', 10 => 'tdepot', 11 => 'tretrait', 12 => 'sold'),
					'sortable-fields' => array(0 => '`clients`.`idclient`', 1 => 2, 2 => 3, 3 => 4, 4 => '`villes1`.`ville`', 5 => 6, 6 => 7, 7 => 8, 8 => 9, 9 => 10, 10 => '`clients`.`tdepot`', 11 => '`clients`.`tretrait`', 12 => '`clients`.`sold`', 13 => 14),
					'records-per-page' => 10,
					'default-sort-by' => 2,
					'default-sort-direction' => 'asc',
					'open-detail-view-on-click' => true,
					'display-page-selector' => true,
					'show-page-progress' => true,
					'template' => 'children-clients',
					'template-printable' => 'children-clients-printable',
					'query' => "SELECT `clients`.`idclient` as 'idclient', `clients`.`matricule` as 'matricule', `clients`.`responsable_administratif` as 'responsable_administratif', `clients`.`adresse` as 'adresse', IF(    CHAR_LENGTH(`villes1`.`ville`), CONCAT_WS('',   `villes1`.`ville`), '') as 'ville', `clients`.`pays` as 'pays', `clients`.`telephone` as 'telephone', `clients`.`email` as 'email', `clients`.`forme_juridique` as 'forme_juridique', `clients`.`autre` as 'autre', CONCAT('$', FORMAT(`clients`.`tdepot`, 2)) as 'tdepot', CONCAT('$', FORMAT(`clients`.`tretrait`, 2)) as 'tretrait', CONCAT('$', FORMAT(`clients`.`sold`, 2)) as 'sold', `clients`.`observations` as 'observations' FROM `clients` LEFT JOIN `villes` as villes1 ON `villes1`.`id`=`clients`.`ville` "
				)
			),
			'villes' => array(   
			),
			'enregistrements' => array(   
				'client' => array(   
					'parent-table' => 'clients',
					'parent-primary-key' => 'idclient',
					'child-primary-key' => 'id',
					'child-primary-key-index' => 0,
					'tab-label' => 'Enregistrements',
					'auto-close' => true,
					'table-icon' => 'resources/table_icons/book_addresses.png',
					'display-refresh' => true,
					'display-add-new' => true,
					'forced-where' => '',
					'display-fields' => array(2 => 'DOMAINE', 3 => 'DATE ENREGISTREMENT', 4 => 'DATE EXPIRATION', 5 => 'STATUT'),
					'display-field-names' => array(2 => 'domaine', 3 => 'date_enregistrement', 4 => 'date_expiration', 5 => 'expiration'),
					'sortable-fields' => array(0 => '`enregistrements`.`id`', 1 => '`clients1`.`responsable_administratif`', 2 => 3, 3 => '`enregistrements`.`date_enregistrement`', 4 => '`enregistrements`.`date_expiration`', 5 => 6),
					'records-per-page' => 10,
					'default-sort-by' => 2,
					'default-sort-direction' => 'asc',
					'open-detail-view-on-click' => true,
					'display-page-selector' => true,
					'show-page-progress' => true,
					'template' => 'children-enregistrements',
					'template-printable' => 'children-enregistrements-printable',
					'query' => "SELECT `enregistrements`.`id` as 'id', IF(    CHAR_LENGTH(`clients1`.`responsable_administratif`), CONCAT_WS('',   `clients1`.`responsable_administratif`), '') as 'client', `enregistrements`.`domaine` as 'domaine', if(`enregistrements`.`date_enregistrement`,date_format(`enregistrements`.`date_enregistrement`,'%d/%m/%Y'),'') as 'date_enregistrement', if(`enregistrements`.`date_expiration`,date_format(`enregistrements`.`date_expiration`,'%d/%m/%Y'),'') as 'date_expiration', `enregistrements`.`expiration` as 'expiration' FROM `enregistrements` LEFT JOIN `clients` as clients1 ON `clients1`.`idclient`=`enregistrements`.`client` "
				)
			),
			'depots' => array(   
				'matricule' => array(   
					'parent-table' => 'clients',
					'parent-primary-key' => 'idclient',
					'child-primary-key' => 'id',
					'child-primary-key-index' => 0,
					'tab-label' => 'Depots',
					'auto-close' => true,
					'table-icon' => 'resources/table_icons/coins_add.png',
					'display-refresh' => true,
					'display-add-new' => true,
					'forced-where' => '',
					'display-fields' => array(2 => 'Client', 3 => 'Date', 4 => 'Montant'),
					'display-field-names' => array(2 => 'client', 3 => 'date', 4 => 'montant'),
					'sortable-fields' => array(0 => '`depots`.`id`', 1 => '`clients1`.`matricule`', 2 => '`clients1`.`responsable_administratif`', 3 => '`depots`.`date`', 4 => '`depots`.`montant`', 5 => '`depots`.`totaldepot`'),
					'records-per-page' => 10,
					'default-sort-by' => 2,
					'default-sort-direction' => 'asc',
					'open-detail-view-on-click' => true,
					'display-page-selector' => true,
					'show-page-progress' => true,
					'template' => 'children-depots',
					'template-printable' => 'children-depots-printable',
					'query' => "SELECT `depots`.`id` as 'id', IF(    CHAR_LENGTH(`clients1`.`matricule`), CONCAT_WS('',   `clients1`.`matricule`), '') as 'matricule', IF(    CHAR_LENGTH(`clients1`.`responsable_administratif`), CONCAT_WS('',   `clients1`.`responsable_administratif`), '') as 'client', if(`depots`.`date`,date_format(`depots`.`date`,'%d/%m/%Y'),'') as 'date', CONCAT('$', FORMAT(`depots`.`montant`, 2)) as 'montant', CONCAT('$', FORMAT(`depots`.`totaldepot`, 2)) as 'totaldepot' FROM `depots` LEFT JOIN `clients` as clients1 ON `clients1`.`idclient`=`depots`.`matricule` "
				)
			),
			'retraits' => array(   
				'matricule' => array(   
					'parent-table' => 'clients',
					'parent-primary-key' => 'idclient',
					'child-primary-key' => 'id',
					'child-primary-key-index' => 0,
					'tab-label' => 'Retraits',
					'auto-close' => true,
					'table-icon' => 'resources/table_icons/coins_delete.png',
					'display-refresh' => true,
					'display-add-new' => true,
					'forced-where' => '',
					'display-fields' => array(2 => 'Client', 3 => 'Date', 4 => 'Domaine', 5 => 'Service', 6 => 'Montant'),
					'display-field-names' => array(2 => 'client', 3 => 'date', 4 => 'domaine', 5 => 'service', 6 => 'montant'),
					'sortable-fields' => array(0 => '`retraits`.`id`', 1 => '`clients1`.`matricule`', 2 => '`clients1`.`responsable_administratif`', 3 => '`retraits`.`date`', 4 => 5, 5 => 6, 6 => '`retraits`.`montant`', 7 => '`retraits`.`totalretrait`', 8 => 9),
					'records-per-page' => 10,
					'default-sort-by' => 2,
					'default-sort-direction' => 'asc',
					'open-detail-view-on-click' => true,
					'display-page-selector' => true,
					'show-page-progress' => true,
					'template' => 'children-retraits',
					'template-printable' => 'children-retraits-printable',
					'query' => "SELECT `retraits`.`id` as 'id', IF(    CHAR_LENGTH(`clients1`.`matricule`), CONCAT_WS('',   `clients1`.`matricule`), '') as 'matricule', IF(    CHAR_LENGTH(`clients1`.`responsable_administratif`), CONCAT_WS('',   `clients1`.`responsable_administratif`), '') as 'client', if(`retraits`.`date`,date_format(`retraits`.`date`,'%d/%m/%Y'),'') as 'date', `retraits`.`domaine` as 'domaine', `retraits`.`service` as 'service', CONCAT('$', FORMAT(`retraits`.`montant`, 2)) as 'montant', CONCAT('$', FORMAT(`retraits`.`totalretrait`, 2)) as 'totalretrait', `retraits`.`observations` as 'observations' FROM `retraits` LEFT JOIN `clients` as clients1 ON `clients1`.`idclient`=`retraits`.`matricule` "
				)
			),
			'soldes' => array(   
				'matricule' => array(   
					'parent-table' => 'clients',
					'parent-primary-key' => 'idclient',
					'child-primary-key' => 'idsoldes',
					'child-primary-key-index' => 0,
					'tab-label' => 'Soldes',
					'auto-close' => true,
					'table-icon' => 'resources/table_icons/coins.png',
					'display-refresh' => true,
					'display-add-new' => true,
					'forced-where' => '',
					'display-fields' => array(2 => 'Client', 3 => 'Date', 4 => 'Total depot', 5 => 'Total retrait', 6 => 'Solde'),
					'display-field-names' => array(2 => 'client', 3 => 'date', 4 => 'total_depot', 5 => 'total_retrait', 6 => 'solde'),
					'sortable-fields' => array(0 => '`soldes`.`idsoldes`', 1 => '`clients1`.`matricule`', 2 => '`clients1`.`responsable_administratif`', 3 => '`soldes`.`date`', 4 => '`soldes`.`total_depot`', 5 => '`soldes`.`total_retrait`', 6 => '`soldes`.`solde`'),
					'records-per-page' => 10,
					'default-sort-by' => 2,
					'default-sort-direction' => 'asc',
					'open-detail-view-on-click' => true,
					'display-page-selector' => true,
					'show-page-progress' => true,
					'template' => 'children-soldes',
					'template-printable' => 'children-soldes-printable',
					'query' => "SELECT `soldes`.`idsoldes` as 'idsoldes', IF(    CHAR_LENGTH(`clients1`.`matricule`), CONCAT_WS('',   `clients1`.`matricule`), '') as 'matricule', IF(    CHAR_LENGTH(`clients1`.`responsable_administratif`), CONCAT_WS('',   `clients1`.`responsable_administratif`), '') as 'client', if(`soldes`.`date`,date_format(`soldes`.`date`,'%d/%m/%Y'),'') as 'date', `soldes`.`total_depot` as 'total_depot', `soldes`.`total_retrait` as 'total_retrait', CONCAT('$', FORMAT(`soldes`.`solde`, 2)) as 'solde' FROM `soldes` LEFT JOIN `clients` as clients1 ON `clients1`.`idclient`=`soldes`.`matricule` "
				)
			)
		);

	/*************************************/
	/* End of configuration */


	$currDir = dirname(__FILE__);
	include("{$currDir}/defaultLang.php");
	include("{$currDir}/language.php");
	include("{$currDir}/lib.php");
	@header('Content-Type: text/html; charset=' . datalist_db_encoding);

	handle_maintenance();

	/**
	* dynamic configuration based on current user's permissions
	* $userPCConfig array is populated only with parent tables where the user has access to
	* at least one child table
	*/
	$userPCConfig = array();
	foreach($pcConfig as $pcChildTable => $ChildrenLookups){
		$permChild = getTablePermissions($pcChildTable);
		if($permChild[2]){ // user can view records of the child table, so proceed to check children lookups
			foreach($ChildrenLookups as $ChildLookupField => $ChildConfig){
				$permParent = getTablePermissions($ChildConfig['parent-table']);
				if($permParent[2]){ // user can view records of parent table
					$userPCConfig[$pcChildTable][$ChildLookupField] = $pcConfig[$pcChildTable][$ChildLookupField];
					// show add new only if configured above AND the user has insert permission
					if($permChild[1] && $pcConfig[$pcChildTable][$ChildLookupField]['display-add-new']){
						$userPCConfig[$pcChildTable][$ChildLookupField]['display-add-new'] = true;
					}else{
						$userPCConfig[$pcChildTable][$ChildLookupField]['display-add-new'] = false;
					}
				}
			}
		}
	}

	/* Receive, UTF-convert, and validate parameters */
	$ParentTable = $_REQUEST['ParentTable']; // needed only with operation=show-children, will be validated in the processing code
	$ChildTable = $_REQUEST['ChildTable'];
		if(!in_array($ChildTable, array_keys($userPCConfig))){
			/* defaults to first child table in config array if not provided */
			$ChildTable = current(array_keys($userPCConfig));
		}
		if(!$ChildTable){ die('<!-- No tables accessible to current user -->'); }
	$SelectedID = strip_tags($_REQUEST['SelectedID']);
	$ChildLookupField = $_REQUEST['ChildLookupField'];
		if(!in_array($ChildLookupField, array_keys($userPCConfig[$ChildTable]))){
			/* defaults to first lookup in current child config array if not provided */
			$ChildLookupField = current(array_keys($userPCConfig[$ChildTable]));
		}
	$Page = intval($_REQUEST['Page']);
		if($Page < 1){
			$Page = 1;
		}
	$SortBy = ($_REQUEST['SortBy'] != '' ? abs(intval($_REQUEST['SortBy'])) : false);
		if(!in_array($SortBy, array_keys($userPCConfig[$ChildTable][$ChildLookupField]['sortable-fields']), true)){
			$SortBy = $userPCConfig[$ChildTable][$ChildLookupField]['default-sort-by'];
		}
	$SortDirection = strtolower($_REQUEST['SortDirection']);
		if(!in_array($SortDirection, array('asc', 'desc'))){
			$SortDirection = $userPCConfig[$ChildTable][$ChildLookupField]['default-sort-direction'];
		}
	$Operation = strtolower($_REQUEST['Operation']);
		if(!in_array($Operation, array('get-records', 'show-children', 'get-records-printable', 'show-children-printable'))){
			$Operation = 'get-records';
		}

	/* process requested operation */
	switch($Operation){
		/************************************************/
		case 'show-children':
			/* populate HTML and JS content with children tabs */
			$tabLabels = $tabPanels = $tabLoaders = '';
			foreach($userPCConfig as $ChildTable => $childLookups){
				foreach($childLookups as $ChildLookupField => $childConfig){
					if($childConfig['parent-table'] == $ParentTable){
						$TableIcon = ($childConfig['table-icon'] ? "<img src=\"{$childConfig['table-icon']}\" border=\"0\" />" : '');
						$tabLabels .= sprintf('<li%s><a href="#panel_%s-%s" id="tab_%s-%s" data-toggle="tab">%s%s</a></li>' . "\n\t\t\t\t\t",($tabLabels ? '' : ' class="active"'), $ChildTable, $ChildLookupField, $ChildTable, $ChildLookupField, $TableIcon, $childConfig['tab-label']);
						$tabPanels .= sprintf('<div id="panel_%s-%s" class="tab-pane%s"><img src="loading.gif" align="top" />%s</div>' . "\n\t\t\t\t", $ChildTable, $ChildLookupField, ($tabPanels ? '' : ' active'), $Translation['Loading ...']);
						$tabLoaders .= sprintf('post("parent-children.php", { ChildTable: "%s", ChildLookupField: "%s", SelectedID: "%s", Page: 1, SortBy: "", SortDirection: "", Operation: "get-records" }, "panel_%s-%s");' . "\n\t\t\t\t", $ChildTable, $ChildLookupField, addslashes($SelectedID), $ChildTable, $ChildLookupField);
					}
				}
			}

			if(!$tabLabels){ die('<!-- no children of current parent table are accessible to current user -->'); }
			?>
			<div id="children-tabs">
				<ul class="nav nav-tabs">
					<?php echo $tabLabels; ?>
				</ul>
				<span id="pc-loading"></span>
			</div>
			<div class="tab-content"><?php echo $tabPanels; ?></div>

			<script>
				$j(function(){
					/* for iOS, avoid loading child tabs in modals */
					var iOS = /(iPad|iPhone|iPod)/g.test(navigator.userAgent);
					var embedded = ($j('.navbar').length == 0);
					if(iOS && embedded){
						$j('#children-tabs').next('.tab-content').remove();
						$j('#children-tabs').remove();
						return;
					}

					/* ajax loading of each tab's contents */
					<?php echo $tabLoaders; ?>
				})
			</script>
			<?php
			break;

		/************************************************/
		case 'show-children-printable':
			/* populate HTML and JS content with children buttons */
			$tabLabels = $tabPanels = $tabLoaders = '';
			foreach($userPCConfig as $ChildTable => $childLookups){
				foreach($childLookups as $ChildLookupField => $childConfig){
					if($childConfig['parent-table'] == $ParentTable){
						$TableIcon = ($childConfig['table-icon'] ? "<img src=\"{$childConfig['table-icon']}\" border=\"0\" />" : '');
						$tabLabels .= sprintf('<button type="button" class="btn btn-default" data-target="#panel_%s-%s" id="tab_%s-%s" data-toggle="collapse">%s %s</button>' . "\n\t\t\t\t\t", $ChildTable, $ChildLookupField, $ChildTable, $ChildLookupField, $TableIcon, $childConfig['tab-label']);
						$tabPanels .= sprintf('<div id="panel_%s-%s" class="collapse"><img src="loading.gif" align="top" />%s</div>' . "\n\t\t\t\t", $ChildTable, $ChildLookupField, $Translation['Loading ...']);
						$tabLoaders .= sprintf('post("parent-children.php", { ChildTable: "%s", ChildLookupField: "%s", SelectedID: "%s", Page: 1, SortBy: "", SortDirection: "", Operation: "get-records-printable" }, "panel_%s-%s");' . "\n\t\t\t\t", $ChildTable, $ChildLookupField, addslashes($SelectedID), $ChildTable, $ChildLookupField);
					}
				}
			}

			if(!$tabLabels){ die('<!-- no children of current parent table are accessible to current user -->'); }
			?>
			<div id="children-tabs" class="hidden-print">
				<div class="btn-group btn-group-lg">
					<?php echo $tabLabels; ?>
				</div>
				<span id="pc-loading"></span>
			</div>
			<div class="vspacer-lg"><?php echo $tabPanels; ?></div>

			<script>
				$j(function(){
					/* for iOS, avoid loading child tabs in modals */
					var iOS = /(iPad|iPhone|iPod)/g.test(navigator.userAgent);
					var embedded = ($j('.navbar').length == 0);
					if(iOS && embedded){
						$j('#children-tabs').next('.tab-content').remove();
						$j('#children-tabs').remove();
						return;
					}

					/* ajax loading of each tab's contents */
					<?php echo $tabLoaders; ?>
				})
			</script>
			<?php
			break;

		/************************************************/
		case 'get-records-printable':
		default: /* default is 'get-records' */

			if($Operation == 'get-records-printable'){
				$userPCConfig[$ChildTable][$ChildLookupField]['records-per-page'] = 2000;
			}

			// build the user permissions limiter
			$permissionsWhere = $permissionsJoin = '';
			$permChild = getTablePermissions($ChildTable);
			if($permChild[2] == 1){ // user can view only his own records
				$permissionsWhere = "`$ChildTable`.`{$userPCConfig[$ChildTable][$ChildLookupField]['child-primary-key']}`=`membership_userrecords`.`pkValue` AND `membership_userrecords`.`tableName`='$ChildTable' AND LCASE(`membership_userrecords`.`memberID`)='".getLoggedMemberID()."'";
			}elseif($permChild[2] == 2){ // user can view only his group's records
				$permissionsWhere = "`$ChildTable`.`{$userPCConfig[$ChildTable][$ChildLookupField]['child-primary-key']}`=`membership_userrecords`.`pkValue` AND `membership_userrecords`.`tableName`='$ChildTable' AND `membership_userrecords`.`groupID`='".getLoggedGroupID()."'";
			}elseif($permChild[2] == 3){ // user can view all records
				/* that's the only case remaining ... no need to modify the query in this case */
			}
			$permissionsJoin = ($permissionsWhere ? ", `membership_userrecords`" : '');

			// build the count query
			$forcedWhere = $userPCConfig[$ChildTable][$ChildLookupField]['forced-where'];
			$query = 
				preg_replace('/^select .* from /i', 'SELECT count(1) FROM ', $userPCConfig[$ChildTable][$ChildLookupField]['query']) .
				$permissionsJoin . " WHERE " .
				($permissionsWhere ? "( $permissionsWhere )" : "( 1=1 )") . " AND " .
				($forcedWhere ? "( $forcedWhere )" : "( 2=2 )") . " AND " .
				"`$ChildTable`.`$ChildLookupField`='" . makeSafe($SelectedID) . "'";
			$totalMatches = sqlValue($query);

			// make sure $Page is <= max pages
			$maxPage = ceil($totalMatches / $userPCConfig[$ChildTable][$ChildLookupField]['records-per-page']);
			if($Page > $maxPage){ $Page = $maxPage; }

			// initiate output data array
			$data = array(
				'config' => $userPCConfig[$ChildTable][$ChildLookupField],
				'parameters' => array(
					'ChildTable' => $ChildTable,
					'ChildLookupField' => $ChildLookupField,
					'SelectedID' => $SelectedID,
					'Page' => $Page,
					'SortBy' => $SortBy,
					'SortDirection' => $SortDirection,
					'Operation' => $Operation
				),
				'records' => array(),
				'totalMatches' => $totalMatches
			);

			// build the data query
			if($totalMatches){ // if we have at least one record, proceed with fetching data
				$startRecord = $userPCConfig[$ChildTable][$ChildLookupField]['records-per-page'] * ($Page - 1);
				$data['query'] = 
					$userPCConfig[$ChildTable][$ChildLookupField]['query'] .
					$permissionsJoin . " WHERE " .
					($permissionsWhere ? "( $permissionsWhere )" : "( 1=1 )") . " AND " .
					($forcedWhere ? "( $forcedWhere )" : "( 2=2 )") . " AND " .
					"`$ChildTable`.`$ChildLookupField`='" . makeSafe($SelectedID) . "'" . 
					($SortBy !== false && $userPCConfig[$ChildTable][$ChildLookupField]['sortable-fields'][$SortBy] ? " ORDER BY {$userPCConfig[$ChildTable][$ChildLookupField]['sortable-fields'][$SortBy]} $SortDirection" : '') .
					" LIMIT $startRecord, {$userPCConfig[$ChildTable][$ChildLookupField]['records-per-page']}";
				$res = sql($data['query'], $eo);
				while($row = db_fetch_row($res)){
					$data['records'][$row[$userPCConfig[$ChildTable][$ChildLookupField]['child-primary-key-index']]] = $row;
				}
			}else{ // if no matching records
				$startRecord = 0;
			}

			if($Operation == 'get-records-printable'){
				$response = loadView($userPCConfig[$ChildTable][$ChildLookupField]['template-printable'], $data);
			}else{
				$response = loadView($userPCConfig[$ChildTable][$ChildLookupField]['template'], $data);
			}

			// change name space to ensure uniqueness
			$uniqueNameSpace = $ChildTable.ucfirst($ChildLookupField).'GetRecords';
			echo str_replace("{$ChildTable}GetChildrenRecordsList", $uniqueNameSpace, $response);
		/************************************************/
	}
