<?php
	$currDir = dirname(__FILE__);
	require("{$currDir}/incCommon.php");
	$GLOBALS['page_title'] = $Translation['view or rebuild fields'];
	include("{$currDir}/incHeader.php");

	/*
		$schema: [ tablename => [ fieldname => [ appgini => '...', 'db' => '...'], ... ], ... ]
	*/

	/* application schema as created in AppGini */
	$schema = array(   
		'main' => array(   
			'id' => array('appgini' => 'INT unsigned not null primary key auto_increment '),
			'main' => array('appgini' => 'VARCHAR(255) null ')
		),
		'clients' => array(   
			'matricule_client' => array('appgini' => 'INT unsigned not null primary key '),
			'date_inscription' => array('appgini' => 'DATE null '),
			'nom_prenom' => array('appgini' => 'VARCHAR(255) null '),
			'sexe' => array('appgini' => 'VARCHAR(255) null '),
			'date_naissance' => array('appgini' => 'DATE null '),
			'age' => array('appgini' => 'INT null '),
			'nni' => array('appgini' => 'VARCHAR(255) null unique '),
			'adresse' => array('appgini' => 'VARCHAR(255) null '),
			'telephone' => array('appgini' => 'VARCHAR(255) null '),
			'email' => array('appgini' => 'VARCHAR(80) null '),
			'banque' => array('appgini' => 'INT unsigned null '),
			'compte' => array('appgini' => 'VARCHAR(255) null '),
			'photo' => array('appgini' => 'VARCHAR(40) null '),
			'signature' => array('appgini' => 'VARCHAR(40) null '),
			'agence' => array('appgini' => 'INT unsigned null '),
			'dossier' => array('appgini' => 'VARCHAR(255) null '),
			'urgence' => array('appgini' => 'VARCHAR(255) null '),
			'observation' => array('appgini' => 'TEXT null ')
		),
		'gestionnaires' => array(   
			'matricule_gestionnaire' => array('appgini' => 'INT unsigned not null primary key '),
			'date_recrutement' => array('appgini' => 'DATE null '),
			'nom_prenom' => array('appgini' => 'VARCHAR(255) null '),
			'telephone' => array('appgini' => 'VARCHAR(255) null '),
			'email' => array('appgini' => 'VARCHAR(80) null '),
			'adresse' => array('appgini' => 'VARCHAR(255) null '),
			'fonction' => array('appgini' => 'INT unsigned null '),
			'agence' => array('appgini' => 'INT unsigned null '),
			'photo' => array('appgini' => 'VARCHAR(40) null '),
			'observation' => array('appgini' => 'TEXT null ')
		),
		'partenaires' => array(   
			'matricule_partenaire' => array('appgini' => 'INT unsigned not null primary key '),
			'raison_sociale' => array('appgini' => 'VARCHAR(255) null '),
			'contact' => array('appgini' => 'VARCHAR(255) null '),
			'fonction' => array('appgini' => 'VARCHAR(255) null '),
			'adresse' => array('appgini' => 'VARCHAR(255) null '),
			'telephone' => array('appgini' => 'VARCHAR(255) null '),
			'email' => array('appgini' => 'VARCHAR(80) null '),
			'banque' => array('appgini' => 'INT unsigned null '),
			'compte' => array('appgini' => 'INT unsigned null '),
			'observation' => array('appgini' => 'TEXT null ')
		),
		'paiements' => array(   
			'idpaiement' => array('appgini' => 'INT(3) unsigned zerofill not null primary key auto_increment '),
			'code' => array('appgini' => 'VARCHAR(255) null unique '),
			'matricule' => array('appgini' => 'INT unsigned null '),
			'nom_prenom' => array('appgini' => 'INT(3) unsigned zerofill null '),
			'banque' => array('appgini' => 'INT(3) unsigned zerofill null '),
			'compte' => array('appgini' => 'INT(3) unsigned zerofill null '),
			'type_paiement' => array('appgini' => 'INT unsigned null '),
			'date_paiement' => array('appgini' => 'DATE null '),
			'num_facture' => array('appgini' => 'VARCHAR(255) null '),
			'montant' => array('appgini' => 'DECIMAL(10,0) null '),
			'beneficiaire' => array('appgini' => 'INT(3) unsigned zerofill null '),
			'banque_beneficiaire' => array('appgini' => 'INT(3) unsigned zerofill null '),
			'compte_beneficiaire' => array('appgini' => 'INT(3) unsigned zerofill null '),
			'observation' => array('appgini' => 'TEXT null ')
		),
		'emetteurs' => array(   
			'idemetteur' => array('appgini' => 'INT unsigned not null primary key auto_increment '),
			'emetteur' => array('appgini' => 'VARCHAR(255) null '),
			'adresse' => array('appgini' => 'VARCHAR(255) null '),
			'email' => array('appgini' => 'VARCHAR(80) null '),
			'telephone' => array('appgini' => 'VARCHAR(255) null '),
			'observation' => array('appgini' => 'VARCHAR(255) null ')
		),
		'bieleteries' => array(   
			'idbieleterie' => array('appgini' => 'INT(3) unsigned zerofill not null primary key auto_increment '),
			'link_tarif' => array('appgini' => 'VARCHAR(255) null '),
			'num_facture' => array('appgini' => 'VARCHAR(255) null unique '),
			'date' => array('appgini' => 'DATE null '),
			'client' => array('appgini' => 'INT unsigned null ')
		),
		'tarifs' => array(   
			'idtarif' => array('appgini' => 'INT unsigned not null primary key auto_increment '),
			'link_bieleterie' => array('appgini' => 'INT(3) unsigned zerofill null '),
			'parcours' => array('appgini' => 'VARCHAR(255) null '),
			'compagnie' => array('appgini' => 'INT unsigned null '),
			'pnr' => array('appgini' => 'VARCHAR(255) null '),
			'emetteur' => array('appgini' => 'INT unsigned null '),
			'prix_achat' => array('appgini' => 'DECIMAL(10,0) null default \'0\' '),
			'commission' => array('appgini' => 'DECIMAL(10,0) null default \'0\' '),
			'total' => array('appgini' => 'DECIMAL(10,0) null ')
		),
		'transferts_argent' => array(   
			'idtransfert' => array('appgini' => 'INT(3) unsigned zerofill not null primary key auto_increment '),
			'num_facture' => array('appgini' => 'VARCHAR(255) null unique '),
			'code_transaction' => array('appgini' => 'INT null unique '),
			'date' => array('appgini' => 'DATE null '),
			'emetteur' => array('appgini' => 'INT unsigned null '),
			'nni_emetteur' => array('appgini' => 'INT(3) unsigned zerofill null '),
			'phone_emetteur' => array('appgini' => 'INT unsigned null '),
			'adresse_emetteur' => array('appgini' => 'INT unsigned null '),
			'beneficiaire' => array('appgini' => 'VARCHAR(255) null '),
			'nni_beneficiaire' => array('appgini' => 'VARCHAR(255) null '),
			'phone_beneficiaire' => array('appgini' => 'VARCHAR(255) null '),
			'adresse_beneficiaire' => array('appgini' => 'VARCHAR(255) null '),
			'prix_achat' => array('appgini' => 'DECIMAL(10,0) null default \'0\' '),
			'commission' => array('appgini' => 'DECIMAL(10,0) null default \'0\' '),
			'total' => array('appgini' => 'DECIMAL(10,0) null '),
			'statut' => array('appgini' => 'VARCHAR(255) not null '),
			'observation' => array('appgini' => 'TEXT null ')
		),
		'colis' => array(   
			'idcoli' => array('appgini' => 'INT(3) unsigned zerofill not null primary key auto_increment '),
			'num_facture' => array('appgini' => 'VARCHAR(255) null unique '),
			'link_envoi_colis' => array('appgini' => 'VARCHAR(255) null '),
			'code_transaction' => array('appgini' => 'VARCHAR(255) null unique '),
			'date_envoi' => array('appgini' => 'DATE null '),
			'emetteur' => array('appgini' => 'INT(3) unsigned zerofill null '),
			'phone_emetteur' => array('appgini' => 'INT unsigned null ')
		),
		'envois_colis' => array(   
			'idenvois_coli' => array('appgini' => 'INT unsigned not null primary key auto_increment '),
			'link_colis' => array('appgini' => 'INT unsigned null '),
			'description' => array('appgini' => 'VARCHAR(255) null '),
			'destination' => array('appgini' => 'INT unsigned null '),
			'ville' => array('appgini' => 'INT unsigned null '),
			'prix_unitaire' => array('appgini' => 'DECIMAL(10,0) null default \'0\' '),
			'qts' => array('appgini' => 'DECIMAL(10,0) null default \'0\' '),
			'prix_total' => array('appgini' => 'DECIMAL(10,0) null default \'0\' '),
			'beneficiaire' => array('appgini' => 'VARCHAR(255) null '),
			'telephone_beneficiaire' => array('appgini' => 'VARCHAR(255) null '),
			'nni_beneficiaire' => array('appgini' => 'VARCHAR(255) null '),
			'date_reception' => array('appgini' => 'DATE null '),
			'statut' => array('appgini' => 'VARCHAR(255) not null '),
			'observation' => array('appgini' => 'TEXT null ')
		),
		'parc_auto' => array(   
			'idparc' => array('appgini' => 'INT unsigned not null primary key auto_increment '),
			'type' => array('appgini' => 'VARCHAR(255) null '),
			'marque' => array('appgini' => 'INT unsigned null '),
			'model' => array('appgini' => 'INT unsigned null '),
			'immatriculation' => array('appgini' => 'VARCHAR(255) null '),
			'places' => array('appgini' => 'VARCHAR(255) null '),
			'observation' => array('appgini' => 'TEXT null ')
		),
		'location_vh' => array(   
			'idlocation' => array('appgini' => 'INT(3) unsigned zerofill not null primary key auto_increment '),
			'link_liste' => array('appgini' => 'VARCHAR(255) null '),
			'num_facture' => array('appgini' => 'VARCHAR(255) null '),
			'date_saisie' => array('appgini' => 'DATE null '),
			'client' => array('appgini' => 'INT unsigned null ')
		),
		'liste_location' => array(   
			'idlocations' => array('appgini' => 'INT(3) unsigned zerofill not null primary key auto_increment '),
			'link_location' => array('appgini' => 'INT(3) unsigned zerofill null '),
			'date_location' => array('appgini' => 'DATE null '),
			'date_fin_location' => array('appgini' => 'DATE null '),
			'vehicule' => array('appgini' => 'INT unsigned null '),
			'model' => array('appgini' => 'INT unsigned null '),
			'type' => array('appgini' => 'VARCHAR(255) null '),
			'prix_unitaire' => array('appgini' => 'DECIMAL(10,0) null default \'0\' '),
			'qts' => array('appgini' => 'DECIMAL(10,0) null default \'0\' '),
			'prix_total' => array('appgini' => 'DECIMAL(10,0) null '),
			'observation' => array('appgini' => 'VARCHAR(255) null ')
		),
		'fonctions' => array(   
			'idfonction' => array('appgini' => 'INT unsigned not null primary key auto_increment '),
			'fonction' => array('appgini' => 'VARCHAR(255) null '),
			'observation' => array('appgini' => 'TEXT null ')
		),
		'agences' => array(   
			'idagence' => array('appgini' => 'INT unsigned not null primary key auto_increment '),
			'agence' => array('appgini' => 'VARCHAR(255) null '),
			'adresse' => array('appgini' => 'VARCHAR(255) null '),
			'ville' => array('appgini' => 'INT unsigned null '),
			'observation' => array('appgini' => 'TEXT null ')
		),
		'villes' => array(   
			'idville' => array('appgini' => 'INT unsigned not null primary key auto_increment '),
			'ville' => array('appgini' => 'VARCHAR(255) null '),
			'observation' => array('appgini' => 'TEXT null ')
		),
		'banques' => array(   
			'idbanque' => array('appgini' => 'INT unsigned not null primary key auto_increment '),
			'banque' => array('appgini' => 'VARCHAR(255) null '),
			'adresse' => array('appgini' => 'VARCHAR(255) null '),
			'telephone' => array('appgini' => 'VARCHAR(255) null '),
			'email' => array('appgini' => 'VARCHAR(80) null '),
			'contact' => array('appgini' => 'VARCHAR(255) null '),
			'observation' => array('appgini' => 'TEXT null ')
		),
		'type_paiements' => array(   
			'idtype_payment' => array('appgini' => 'INT unsigned not null primary key auto_increment '),
			'type_paiement' => array('appgini' => 'VARCHAR(255) null '),
			'observation' => array('appgini' => 'TEXT null ')
		),
		'compagnies' => array(   
			'idcompagnie' => array('appgini' => 'INT unsigned not null primary key auto_increment '),
			'compagnie' => array('appgini' => 'VARCHAR(255) null '),
			'observation' => array('appgini' => 'TEXT null ')
		),
		'statuts' => array(   
			'idstatut' => array('appgini' => 'INT unsigned not null primary key auto_increment '),
			'statut' => array('appgini' => 'VARCHAR(255) null ')
		),
		'visas' => array(   
			'idvisa' => array('appgini' => 'INT unsigned not null primary key auto_increment '),
			'date_depot' => array('appgini' => 'DATE null '),
			'client' => array('appgini' => 'INT unsigned null '),
			'num_passport' => array('appgini' => 'INT unsigned null '),
			'type_visa' => array('appgini' => 'INT unsigned null '),
			'emetteur' => array('appgini' => 'INT unsigned null '),
			'prix_achat' => array('appgini' => 'DECIMAL(10,0) null default \'0\' '),
			'commission' => array('appgini' => 'DECIMAL(10,0) null default \'0\' '),
			'total' => array('appgini' => 'DECIMAL(10,0) null '),
			'statut' => array('appgini' => 'INT unsigned null ')
		),
		'type_visas' => array(   
			'idtype_visa' => array('appgini' => 'INT unsigned not null primary key auto_increment '),
			'type_visa' => array('appgini' => 'VARCHAR(255) null ')
		),
		'models' => array(   
			'idmodel' => array('appgini' => 'INT unsigned not null primary key auto_increment '),
			'marque' => array('appgini' => 'VARCHAR(255) not null '),
			'model' => array('appgini' => 'VARCHAR(255) not null ')
		),
		'facture' => array(   
			'idfacture' => array('appgini' => 'INT(3) unsigned zerofill not null primary key auto_increment '),
			'num_facture' => array('appgini' => 'VARCHAR(255) null unique '),
			'type' => array('appgini' => 'VARCHAR(255) not null '),
			'date' => array('appgini' => 'DATE null '),
			'client' => array('appgini' => 'INT unsigned null '),
			'societe' => array('appgini' => 'INT unsigned null '),
			'travaux' => array('appgini' => 'VARCHAR(255) null ')
		),
		'detail_facture' => array(   
			'dfid' => array('appgini' => 'INT unsigned not null primary key auto_increment '),
			'factureid' => array('appgini' => 'INT unsigned null '),
			'designation' => array('appgini' => 'VARCHAR(255) null '),
			'quantite' => array('appgini' => 'DECIMAL(10,0) null default \'1\' '),
			'prixunitaire' => array('appgini' => 'DECIMAL(10,0) null default \'0\' '),
			'total' => array('appgini' => 'DECIMAL(10,0) null ')
		),
		'compta' => array(   
			'idcompta' => array('appgini' => 'INT unsigned not null primary key auto_increment '),
			'date' => array('appgini' => 'DATE null '),
			'libelle' => array('appgini' => 'VARCHAR(255) null '),
			'description' => array('appgini' => 'VARCHAR(255) null '),
			'recette' => array('appgini' => 'DECIMAL(10,0) null default \'0\' '),
			'depense' => array('appgini' => 'DECIMAL(10,0) null default \'0\' '),
			'caisse' => array('appgini' => 'DECIMAL(10,0) null default \'0\' '),
			'observation' => array('appgini' => 'VARCHAR(255) null ')
		),
		'tresorerie_caisse' => array(   
			'idtresorerie_caisse' => array('appgini' => 'INT(7) unsigned zerofill not null primary key auto_increment '),
			'date' => array('appgini' => 'DATE null '),
			'journee_du' => array('appgini' => 'VARCHAR(255) null '),
			'link_in' => array('appgini' => 'VARCHAR(255) null ')
		),
		'tresorerie_items' => array(   
			'idtresorerie_item' => array('appgini' => 'INT(7) unsigned zerofill not null primary key auto_increment '),
			'link_out' => array('appgini' => 'INT(7) unsigned zerofill null '),
			'justificatif' => array('appgini' => 'VARCHAR(255) null '),
			'libelles' => array('appgini' => 'VARCHAR(255) null '),
			'montant' => array('appgini' => 'DECIMAL(10,0) null default \'0\' '),
			'commission_agence' => array('appgini' => 'DECIMAL(10,0) null default \'0\' '),
			'net_compagnie' => array('appgini' => 'DECIMAL(10,0) null '),
			'observations' => array('appgini' => 'VARCHAR(255) null ')
		),
		'piece_reglements' => array(   
			'idpiece' => array('appgini' => 'INT(7) unsigned zerofill not null primary key auto_increment '),
			'date' => array('appgini' => 'DATE null '),
			'beneficiaire' => array('appgini' => 'VARCHAR(255) null '),
			'operation' => array('appgini' => 'VARCHAR(255) null '),
			'montant' => array('appgini' => 'DECIMAL(10,0) null default \'0\' '),
			'banque' => array('appgini' => 'INT unsigned null '),
			'compte' => array('appgini' => 'VARCHAR(255) null '),
			'num_cheque' => array('appgini' => 'VARCHAR(255) null '),
			'date_cheque' => array('appgini' => 'DATE null '),
			'imputation' => array('appgini' => 'VARCHAR(255) null '),
			'observations' => array('appgini' => 'VARCHAR(255) null ')
		),
		'autorisation_change' => array(   
			'idautorisation' => array('appgini' => 'INT(7) unsigned zerofill not null primary key auto_increment '),
			'date' => array('appgini' => 'DATE null '),
			'nom_prenom' => array('appgini' => 'VARCHAR(255) null '),
			'nationalite' => array('appgini' => 'VARCHAR(255) null '),
			'profession' => array('appgini' => 'VARCHAR(255) null '),
			'adresse' => array('appgini' => 'VARCHAR(255) null '),
			'num_compte' => array('appgini' => 'VARCHAR(255) null '),
			'nature_operation' => array('appgini' => 'VARCHAR(255) null '),
			'piece_justificative' => array('appgini' => 'VARCHAR(255) null '),
			'nature_devises' => array('appgini' => 'VARCHAR(255) null '),
			'montant_chiffre' => array('appgini' => 'DECIMAL(10,0) null default \'0\' '),
			'cours' => array('appgini' => 'FLOAT(10,0) null default \'0\' '),
			'montant_fois_cours' => array('appgini' => 'DECIMAL(10,0) null '),
			'commission' => array('appgini' => 'FLOAT(10,0) null default \'0\' '),
			'contre_valeur' => array('appgini' => 'DECIMAL(10,0) null default \'0\' '),
			'total' => array('appgini' => 'VARCHAR(255) null ')
		),
		'fiches_changes' => array(   
			'idfichechange' => array('appgini' => 'INT(7) unsigned zerofill not null primary key auto_increment '),
			'date' => array('appgini' => 'DATE null '),
			'journee_du' => array('appgini' => 'VARCHAR(255) null '),
			'link_in' => array('appgini' => 'VARCHAR(255) null ')
		),
		'fiches_changes_items' => array(   
			'idfiche_change_item' => array('appgini' => 'INT(7) unsigned zerofill not null primary key auto_increment '),
			'link_out' => array('appgini' => 'INT(7) unsigned zerofill null '),
			'nom_prenom' => array('appgini' => 'VARCHAR(255) null '),
			'num_identite' => array('appgini' => 'VARCHAR(255) null '),
			'montant' => array('appgini' => 'DECIMAL(10,0) null default \'0\' '),
			'devises' => array('appgini' => 'VARCHAR(255) null '),
			'achats' => array('appgini' => 'DECIMAL(10,0) null '),
			'ventes' => array('appgini' => 'DECIMAL(10,0) null default \'0\' '),
			'observations' => array('appgini' => 'VARCHAR(255) null ')
		),
		'bon_passage' => array(   
			'idbon' => array('appgini' => 'INT(7) unsigned zerofill not null primary key auto_increment '),
			'date' => array('appgini' => 'DATE null '),
			'pnr' => array('appgini' => 'VARCHAR(255) null '),
			'nous_prions' => array('appgini' => 'VARCHAR(255) null '),
			'au_nom_de' => array('appgini' => 'VARCHAR(255) null '),
			'parcours' => array('appgini' => 'VARCHAR(255) null '),
			'depart' => array('appgini' => 'DATE null '),
			'retour' => array('appgini' => 'DATE null '),
			'total_ht' => array('appgini' => 'DECIMAL(10,0) null default \'0\' '),
			'commissions' => array('appgini' => 'FLOAT(10,0) null default \'0\' '),
			'total_ttc' => array('appgini' => 'DECIMAL(10,0) null '),
			'frais_pta' => array('appgini' => 'DECIMAL(10,0) null '),
			'net_payer' => array('appgini' => 'DECIMAL(10,0) null '),
			'num_billet' => array('appgini' => 'VARCHAR(255) null '),
			'observations' => array('appgini' => 'VARCHAR(255) null ')
		),
		'caisse_journaliere' => array(   
			'idcaisse_journaliere' => array('appgini' => 'INT(7) unsigned zerofill not null primary key auto_increment '),
			'date' => array('appgini' => 'DATE null '),
			'link_in' => array('appgini' => 'VARCHAR(255) null ')
		),
		'item_caisse_journaliere' => array(   
			'link_out' => array('appgini' => 'INT(7) unsigned zerofill null '),
			'iditem_caisse_journaliere' => array('appgini' => 'INT unsigned not null primary key auto_increment '),
			'justificatif' => array('appgini' => 'VARCHAR(255) null '),
			'nom_prenom' => array('appgini' => 'VARCHAR(255) null '),
			'destination' => array('appgini' => 'VARCHAR(255) null '),
			'compagnie' => array('appgini' => 'VARCHAR(255) null '),
			'prix_ht' => array('appgini' => 'DECIMAL(10,0) null default \'0\' '),
			'commission' => array('appgini' => 'FLOAT(10,0) null default \'0\' '),
			'prix_ttc' => array('appgini' => 'DECIMAL(10,0) null default \'0\' '),
			'observations' => array('appgini' => 'VARCHAR(255) null ')
		)
	);

	$table_captions = getTableList();

	/* function for preparing field definition for comparison */
	function prepare_def($def) {
		$def = strtolower($def);

		/* ignore 'null' */
		$def = preg_replace('/\s+not\s+null\s*/', '%%NOT_NULL%%', $def);
		$def = preg_replace('/\s+null\s*/', ' ', $def);
		$def = str_replace('%%NOT_NULL%%', ' not null ', $def);

		/* ignore length for int data types */
		$def = preg_replace('/int\s*\([0-9]+\)/', 'int', $def);

		/* make sure there is always a space before mysql words */
		$def = preg_replace('/(\S)(unsigned|not null|binary|zerofill|auto_increment|default)/', '$1 $2', $def);

		/* treat 0.000.. same as 0 */
		$def = preg_replace('/([0-9])*\.0+/', '$1', $def);

		/* treat unsigned zerofill same as zerofill */
		$def = str_ireplace('unsigned zerofill', 'zerofill', $def);

		/* ignore zero-padding for date data types */
		$def = preg_replace("/date\s*default\s*'([0-9]{4})-0?([1-9])-0?([1-9])'/", "date default '$1-$2-$3'", $def);

		return trim($def);
	}

	/**
	 *  @brief creates/fixes given field according to given schema
	 *  @return integer: 0 = error, 1 = field updated, 2 = field created
	 */
	function fix_field($fix_table, $fix_field, $schema, &$qry) {
		if(!isset($schema[$fix_table][$fix_field])) return 0;

		$def = $schema[$fix_table][$fix_field];
		$field_added = $field_updated = false;
		$eo['silentErrors'] = true;

		// field exists?
		$res = sql("show columns from `{$fix_table}` like '{$fix_field}'", $eo);
		if($row = db_fetch_assoc($res)){
			// modify field
			$qry = "alter table `{$fix_table}` modify `{$fix_field}` {$def['appgini']}";
			sql($qry, $eo);

			// remove unique from db if necessary
			if($row['Key'] == 'UNI' && !stripos($def['appgini'], ' unique')){
				// retrieve unique index name
				$res_unique = sql("show index from `{$fix_table}` where Column_name='{$fix_field}' and Non_unique=0", $eo);
				if($row_unique = db_fetch_assoc($res_unique)){
					$qry_unique = "drop index `{$row_unique['Key_name']}` on `{$fix_table}`";
					sql($qry_unique, $eo);
					$qry .= ";\n{$qry_unique}";
				}
			}

			return 1;
		}

		// missing field is defined as PK and table has another PK field?
		$current_pk = getPKFieldName($fix_table);
		if(stripos($def['appgini'], 'primary key') !== false && $current_pk !== false) {
			// if current PK is not another AppGini-defined field, then rename it.
			if(!isset($schema[$fix_table][$current_pk])) {
				// no need to include 'primary key' in definition since it's already a PK field
				$redef = str_ireplace(' primary key', '', $def['appgini']);
				$qry = "alter table `{$fix_table}` change `{$current_pk}` `{$fix_field}` {$redef}";
				sql($qry, $eo);
				return 1;
			}

			// current PK field is another AppGini-defined field
			// this happens if table had a PK field in AppGini then it was unset as PK
			// and another field was created and set as PK
			// in that case, drop PK index from current PK
			// and also remove auto_increment from it if defined
			// then proceed to creating the missing PK field
			$pk_def = str_ireplace(' auto_increment', '', $schema[$fix_table][$current_pk]);
			sql("alter table `{$fix_table}` modify `{$current_pk}` {$pk_def}", $eo);
		}

		// create field
		$qry = "alter table `{$fix_table}` add column `{$fix_field}` {$def['appgini']}";
		sql($qry, $eo);
		return 2;
	}

	/* process requested fixes */
	$fix_table = (isset($_GET['t']) ? $_GET['t'] : false);
	$fix_field = (isset($_GET['f']) ? $_GET['f'] : false);
	$fix_all = (isset($_GET['all']) ? true : false);

	if($fix_field && $fix_table) $fix_status = fix_field($fix_table, $fix_field, $schema, $qry);

	/* retrieve actual db schema */
	foreach($table_captions as $tn => $tc){
		$eo['silentErrors'] = true;
		$res = sql("show columns from `{$tn}`", $eo);
		if($res){
			while($row = db_fetch_assoc($res)){
				if(!isset($schema[$tn][$row['Field']]['appgini'])) continue;
				$field_description = strtoupper(str_replace(' ', '', $row['Type']));
				$field_description = str_ireplace('unsigned', ' unsigned', $field_description);
				$field_description = str_ireplace('zerofill', ' zerofill', $field_description);
				$field_description = str_ireplace('binary', ' binary', $field_description);
				$field_description .= ($row['Null'] == 'NO' ? ' not null' : '');
				$field_description .= ($row['Key'] == 'PRI' ? ' primary key' : '');
				$field_description .= ($row['Key'] == 'UNI' ? ' unique' : '');
				$field_description .= ($row['Default'] != '' ? " default '" . makeSafe($row['Default']) . "'" : '');
				$field_description .= ($row['Extra'] == 'auto_increment' ? ' auto_increment' : '');

				$schema[$tn][$row['Field']]['db'] = '';
				if(isset($schema[$tn][$row['Field']])){
					$schema[$tn][$row['Field']]['db'] = $field_description;
				}
			}
		}
	}

	/* handle fix_all request */
	if($fix_all){
		foreach($schema as $tn => $fields){
			foreach($fields as $fn => $fd){
				if(prepare_def($fd['appgini']) == prepare_def($fd['db'])) continue;
				fix_field($tn, $fn, $schema, $qry);
			}
		}

		redirect('admin/pageRebuildFields.php');
		exit;
	}
?>

<?php if($fix_status == 1 || $fix_status == 2){ ?>
	<div class="alert alert-info alert-dismissable">
		<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
		<i class="glyphicon glyphicon-info-sign"></i>
		<?php 
			$originalValues = array('<ACTION>', '<FIELD>', '<TABLE>', '<QUERY>');
			$action = ($fix_status == 2 ? 'create' : 'update');
			$replaceValues = array($action, $fix_field, $fix_table, $qry);
			echo str_replace($originalValues, $replaceValues, $Translation['create or update table']);
		?>
	</div>
<?php } ?>

<div class="page-header"><h1>
	<?php echo $Translation['view or rebuild fields'] ; ?>
	<button type="button" class="btn btn-default" id="show_deviations_only"><i class="glyphicon glyphicon-eye-close"></i> <?php echo $Translation['show deviations only'] ; ?></button>
	<button type="button" class="btn btn-default hidden" id="show_all_fields"><i class="glyphicon glyphicon-eye-open"></i> <?php echo $Translation['show all fields'] ; ?></button>
</h1></div>

<p class="lead"><?php echo $Translation['compare tables page'] ; ?></p>

<div class="alert summary"></div>
<table class="table table-responsive table-hover table-striped">
	<thead><tr>
		<th></th>
		<th><?php echo $Translation['field'] ; ?></th>
		<th><?php echo $Translation['AppGini definition'] ; ?></th>
		<th><?php echo $Translation['database definition'] ; ?></th>
		<th id="fix_all"></th>
	</tr></thead>

	<tbody>
	<?php foreach($schema as $tn => $fields){ ?>
		<tr class="text-info"><td colspan="5"><h4 data-placement="left" data-toggle="tooltip" title="<?php echo str_replace ( "<TABLENAME>" , $tn , $Translation['table name title']) ; ?>"><i class="glyphicon glyphicon-th-list"></i> <?php echo $table_captions[$tn]; ?></h4></td></tr>
		<?php foreach($fields as $fn => $fd){ ?>
			<?php $diff = ((prepare_def($fd['appgini']) == prepare_def($fd['db'])) ? false : true); ?>
			<?php $no_db = ($fd['db'] ? false : true); ?>
			<tr class="<?php echo ($diff ? 'warning' : 'field_ok'); ?>">
				<td><i class="glyphicon glyphicon-<?php echo ($diff ? 'remove text-danger' : 'ok text-success'); ?>"></i></td>
				<td><?php echo $fn; ?></td>
				<td class="<?php echo ($diff ? 'bold text-success' : ''); ?>"><?php echo $fd['appgini']; ?></td>
				<td class="<?php echo ($diff ? 'bold text-danger' : ''); ?>"><?php echo thisOr($fd['db'], $Translation['does not exist']); ?></td>
				<td>
					<?php if($diff && $no_db){ ?>
						<a href="pageRebuildFields.php?t=<?php echo $tn; ?>&f=<?php echo $fn; ?>" class="btn btn-success btn-xs btn_create" data-toggle="tooltip" data-placement="top" title="<?php echo $Translation['create field'] ; ?>"><i class="glyphicon glyphicon-plus"></i> <?php echo $Translation['create it'] ; ?></a>
					<?php }elseif($diff){ ?>
						<a href="pageRebuildFields.php?t=<?php echo $tn; ?>&f=<?php echo $fn; ?>" class="btn btn-warning btn-xs btn_update" data-toggle="tooltip" title="<?php echo $Translation['fix field'] ; ?>"><i class="glyphicon glyphicon-cog"></i> <?php echo $Translation['fix it'] ; ?></a>
					<?php } ?>
				</td>
			</tr>
		<?php } ?>
	<?php } ?>
	</tbody>
</table>
<div class="alert summary"></div>

<style>
	.bold{ font-weight: bold; }
	[data-toggle="tooltip"]{ display: block !important; }
</style>

<script>
	$j(function(){
		$j('[data-toggle="tooltip"]').tooltip();

		$j('#show_deviations_only').click(function(){
			$j(this).addClass('hidden');
			$j('#show_all_fields').removeClass('hidden');
			$j('.field_ok').hide();
		});

		$j('#show_all_fields').click(function(){
			$j(this).addClass('hidden');
			$j('#show_deviations_only').removeClass('hidden');
			$j('.field_ok').show();
		});

		$j('.btn_update, #fix_all').click(function(){
			return confirm("<?php echo $Translation['field update warning'] ; ?>");
		});

		var count_updates = $j('.btn_update').length;
		var count_creates = $j('.btn_create').length;
		if(!count_creates && !count_updates){
			$j('.summary').addClass('alert-success').html("<?php echo $Translation['no deviations found'] ; ?>");
		}else{
			var fieldsCount = "<?php echo $Translation['error fields']; ?>";
			fieldsCount = fieldsCount.replace(/<CREATENUM>/, count_creates ).replace(/<UPDATENUM>/, count_updates);


			$j('.summary')
				.addClass('alert-warning')
				.html(
					fieldsCount + 
					'<br><br>' + 
					'<a href="pageBackupRestore.php" class="alert-link">' +
						'<b><?php echo addslashes($Translation['backup before fix']); ?></b>' +
					'</a>'
				);

			$j('<a href="pageRebuildFields.php?all=1" class="btn btn-danger btn-block"><i class="glyphicon glyphicon-cog"></i> <?php echo addslashes($Translation['fix all']); ?></a>').appendTo('#fix_all');
		}
	});
</script>

<?php
	include("{$currDir}/incFooter.php");
?>
