<?php
	// check this file's MD5 to make sure it wasn't called before
	$prevMD5=@implode('', @file(dirname(__FILE__).'/setup.md5'));
	$thisMD5=md5(@implode('', @file("./updateDB.php")));
	if($thisMD5==$prevMD5){
		$setupAlreadyRun=true;
	}else{
		// set up tables
		if(!isset($silent)){
			$silent=true;
		}

		// set up tables
		setupTable('main', "create table if not exists `main` (   `id` INT unsigned not null auto_increment , primary key (`id`), `main` VARCHAR(255) null ) CHARSET utf8", $silent);
		setupTable('clients', "create table if not exists `clients` (   `idclient` INT unsigned not null auto_increment , primary key (`idclient`), `code` VARCHAR(255) not null , unique `code_unique` (`code`), `nom` VARCHAR(255) null , `prenom` VARCHAR(255) null , `societe` VARCHAR(255) null , `email` VARCHAR(80) null , `phone` VARCHAR(255) null , `whatsapp` VARCHAR(255) null , `note` TEXT null ) CHARSET utf8", $silent);
		setupTable('comptes', "create table if not exists `comptes` (   `code` INT unsigned null , `idcompte` INT(6) unsigned zerofill not null auto_increment , primary key (`idcompte`), `titulaire` INT unsigned null , `phone` INT unsigned null , `versements` DECIMAL(10,0) null default '0' , `retraits` DECIMAL(10,0) null default '0' , `solde` DECIMAL(10,0) null default '0' , `note` VARCHAR(255) null ) CHARSET utf8", $silent);
		setupIndexes('comptes', array('code'));
		setupTable('enregistrements', "create table if not exists `enregistrements` (   `idenregistrement` INT unsigned not null auto_increment , primary key (`idenregistrement`), `code_client` INT unsigned null , `client` INT unsigned null , `compte` INT(6) unsigned zerofill null , `domaine` VARCHAR(255) null , `pour` VARCHAR(255) null , `date_enregistrement` DATE null , `date_expiration` DATE null , `statut` VARCHAR(255) not null default 'En cours' , `note` VARCHAR(255) null ) CHARSET utf8", $silent);
		setupIndexes('enregistrements', array('code_client','compte'));
		setupTable('facture', "create table if not exists `facture` (   `idfacture` INT(4) unsigned zerofill not null auto_increment , primary key (`idfacture`), `type` VARCHAR(255) not null , `date` DATE null , `numero` VARCHAR(255) null , unique `numero_unique` (`numero`), `client` INT unsigned null , `societe` INT unsigned null , `travaux` VARCHAR(255) null ) CHARSET utf8", $silent);
		setupIndexes('facture', array('client'));
		setupTable('versements', "create table if not exists `versements` (   `idversement` INT(6) unsigned zerofill not null auto_increment , primary key (`idversement`), `date` DATE null , `code` INT unsigned null , `compte` INT(6) unsigned zerofill null , `titulaire` INT unsigned null , `motif` VARCHAR(255) null , `montant` DECIMAL(10,0) null , `total_m_versement` DECIMAL(10,0) null , `note` VARCHAR(255) null ) CHARSET utf8", $silent);
		setupIndexes('versements', array('code','compte'));
		setupTable('retraits', "create table if not exists `retraits` (   `idretrait` INT(6) unsigned zerofill not null auto_increment , primary key (`idretrait`), `date` DATE null , `code` INT unsigned null , `compte` INT(6) unsigned zerofill null , `titulaire` INT unsigned null , `motif` VARCHAR(255) null , `montant` DECIMAL(10,0) null , `note` VARCHAR(255) null , `total_m_retrait` DECIMAL(10,0) null ) CHARSET utf8", $silent);
		setupIndexes('retraits', array('code','compte'));
		setupTable('detail_facture', "create table if not exists `detail_facture` (   `dfid` INT unsigned not null auto_increment , primary key (`dfid`), `factureid` INT(4) unsigned zerofill null , `designation` VARCHAR(255) null , `quantite` DECIMAL(10,0) null default '1' , `prixunitaire` DECIMAL(10,0) null default '0' , `total` DECIMAL(10,0) null ) CHARSET utf8", $silent);
		setupIndexes('detail_facture', array('factureid'));
		setupTable('credit', "create table if not exists `credit` (   `idcredit` INT unsigned not null auto_increment , primary key (`idcredit`), `date` DATE null , `nom_prenom` INT unsigned null , `credit` DECIMAL(10,0) null , `remboursement` DECIMAL(10,0) null , `note` VARCHAR(255) null ) CHARSET utf8", $silent);
		setupIndexes('credit', array('nom_prenom'));
		setupTable('creanciers', "create table if not exists `creanciers` (   `idcreancier` INT unsigned not null auto_increment , primary key (`idcreancier`), `nom_prenom` VARCHAR(255) null , `telephone` VARCHAR(255) null , `email` VARCHAR(80) null , `adresse` VARCHAR(255) null , `note` VARCHAR(255) null ) CHARSET utf8", $silent);


		// save MD5
		if($fp=@fopen(dirname(__FILE__).'/setup.md5', 'w')){
			fwrite($fp, $thisMD5);
			fclose($fp);
		}
	}


	function setupIndexes($tableName, $arrFields){
		if(!is_array($arrFields)){
			return false;
		}

		foreach($arrFields as $fieldName){
			if(!$res=@db_query("SHOW COLUMNS FROM `$tableName` like '$fieldName'")){
				continue;
			}
			if(!$row=@db_fetch_assoc($res)){
				continue;
			}
			if($row['Key']==''){
				@db_query("ALTER TABLE `$tableName` ADD INDEX `$fieldName` (`$fieldName`)");
			}
		}
	}


	function setupTable($tableName, $createSQL='', $silent=true, $arrAlter=''){
		global $Translation;
		ob_start();

		echo '<div style="padding: 5px; border-bottom:solid 1px silver; font-family: verdana, arial; font-size: 10px;">';

		// is there a table rename query?
		if(is_array($arrAlter)){
			$matches=array();
			if(preg_match("/ALTER TABLE `(.*)` RENAME `$tableName`/", $arrAlter[0], $matches)){
				$oldTableName=$matches[1];
			}
		}

		if($res=@db_query("select count(1) from `$tableName`")){ // table already exists
			if($row = @db_fetch_array($res)){
				echo str_replace("<TableName>", $tableName, str_replace("<NumRecords>", $row[0],$Translation["table exists"]));
				if(is_array($arrAlter)){
					echo '<br>';
					foreach($arrAlter as $alter){
						if($alter!=''){
							echo "$alter ... ";
							if(!@db_query($alter)){
								echo '<span class="label label-danger">' . $Translation['failed'] . '</span>';
								echo '<div class="text-danger">' . $Translation['mysql said'] . ' ' . db_error(db_link()) . '</div>';
							}else{
								echo '<span class="label label-success">' . $Translation['ok'] . '</span>';
							}
						}
					}
				}else{
					echo $Translation["table uptodate"];
				}
			}else{
				echo str_replace("<TableName>", $tableName, $Translation["couldnt count"]);
			}
		}else{ // given tableName doesn't exist

			if($oldTableName!=''){ // if we have a table rename query
				if($ro=@db_query("select count(1) from `$oldTableName`")){ // if old table exists, rename it.
					$renameQuery=array_shift($arrAlter); // get and remove rename query

					echo "$renameQuery ... ";
					if(!@db_query($renameQuery)){
						echo '<span class="label label-danger">' . $Translation['failed'] . '</span>';
						echo '<div class="text-danger">' . $Translation['mysql said'] . ' ' . db_error(db_link()) . '</div>';
					}else{
						echo '<span class="label label-success">' . $Translation['ok'] . '</span>';
					}

					if(is_array($arrAlter)) setupTable($tableName, $createSQL, false, $arrAlter); // execute Alter queries on renamed table ...
				}else{ // if old tableName doesn't exist (nor the new one since we're here), then just create the table.
					setupTable($tableName, $createSQL, false); // no Alter queries passed ...
				}
			}else{ // tableName doesn't exist and no rename, so just create the table
				echo str_replace("<TableName>", $tableName, $Translation["creating table"]);
				if(!@db_query($createSQL)){
					echo '<span class="label label-danger">' . $Translation['failed'] . '</span>';
					echo '<div class="text-danger">' . $Translation['mysql said'] . db_error(db_link()) . '</div>';
				}else{
					echo '<span class="label label-success">' . $Translation['ok'] . '</span>';
				}
			}
		}

		echo "</div>";

		$out=ob_get_contents();
		ob_end_clean();
		if(!$silent){
			echo $out;
		}
	}
?>