<?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('clients', "create table if not exists `clients` (   `idclients` INT unsigned not null auto_increment , primary key (`idclients`), `matricule` VARCHAR(255) , unique `matricule_unique` (`matricule`), `nom_prenom` VARCHAR(255) , `telephone` VARCHAR(255) , `email` VARCHAR(80) , `adresse` VARCHAR(255) , `commentaire` VARCHAR(255) ) CHARSET utf8", $silent);
		setupTable('fournisseurs', "create table if not exists `fournisseurs` (   `idfournisseurs` INT unsigned not null auto_increment , primary key (`idfournisseurs`), `raison_sociale` VARCHAR(255) , `pays` INT unsigned , `adresse` VARCHAR(255) , `telephone` VARCHAR(255) , `email` VARCHAR(80) , `note` TEXT ) CHARSET utf8", $silent);
		setupIndexes('fournisseurs', array('pays'));
		setupTable('marchandises', "create table if not exists `marchandises` (   `idmarchandises` INT unsigned not null auto_increment , primary key (`idmarchandises`), `designation` VARCHAR(255) , `reference` VARCHAR(255) , unique `reference_unique` (`reference`), `fournisseur` INT unsigned , `provenance` INT unsigned , `achat` DECIMAL(10,0) default '0' , `vente` DECIMAL(10,0) default '0' , `stock` DECIMAL(10,0) default '0' , `stockaa` DECIMAL(10,0) default '0' , `stockvv` DECIMAL(10,0) default '0' , `sstock` DECIMAL(10,0) default '0' ) CHARSET utf8", $silent);
		setupIndexes('marchandises', array('fournisseur','provenance'));
		setupTable('provenances', "create table if not exists `provenances` (   `idprovenances` INT unsigned not null auto_increment , primary key (`idprovenances`), `provenance` VARCHAR(255) ) CHARSET utf8", $silent);
		setupTable('achats', "create table if not exists `achats` (   `idachats` INT unsigned not null auto_increment , primary key (`idachats`), `date` DATE , `reference` INT unsigned , `designation` INT unsigned , `quantitea` DECIMAL(10,0) default '0' , `punitairea` DECIMAL(10,0) default '0' , `ptotala` DECIMAL(10,0) default '0' , `ptotala2` DECIMAL(10,0) default '0' , `tqtsa` DECIMAL(10,0) default '0' ) CHARSET utf8", $silent);
		setupIndexes('achats', array('designation'));
		setupTable('ventes', "create table if not exists `ventes` (   `idventes` INT unsigned not null auto_increment , primary key (`idventes`), `date` DATE , `matricule` INT unsigned , `client` INT unsigned , `reference` INT unsigned , `designation` INT unsigned , `quantitev` DECIMAL(10,0) default '0' , `punitairev` DECIMAL(10,0) default '0' , `ptotalv` DECIMAL(10,0) default '0' , `ptotalv2` DECIMAL(10,0) default '0' , `tqtsv` DECIMAL(10,0) default '0' ) CHARSET utf8", $silent);
		setupIndexes('ventes', array('matricule','designation'));
		setupTable('retours', "create table if not exists `retours` (   `idretours` INT unsigned not null auto_increment , primary key (`idretours`), `date` DATE , `reference` INT unsigned , `matricule` INT unsigned , `client` INT unsigned , `facture` VARCHAR(255) , `designation` INT unsigned , `quantiter` DECIMAL(10,0) default '0' , `punitairer` DECIMAL(10,0) default '0' , `ptotalr` DECIMAL(10,0) default '0' , `ptotalr2` DECIMAL(10,0) default '0' , `tqtsr` DECIMAL(10,0) default '0' ) CHARSET utf8", $silent);
		setupIndexes('retours', array('matricule','designation'));


		// 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;
		}
	}
?>