<?php
/*******************************************************************************
 *                    _ _ _ _
 *                   / _ _  /
 *            _ _   / /__/ /_ _   ____ _ _   _ _ _    __
 *           / _ ` /   _ _// _ ` / __// _ ` / _ \\ \ / /
 *          / _ _// /\ \  / _ _/ \_ \/ _ _// / \/ \ ` /
 *          \_ , /_/  \_\ \_ ,  /__ /\_ , /_/      \_/
 *
 *******************************************************************************
 *    Application:  eReserv
 *    Version:      6
 *    Author:       David Di Certo
 *    Website:      http://www.cogites.com
 *    Email:        contact@cogites.com
 *    Copyright:    2013 - David Di Certo
 *******************************************************************************
 *    == FR ==      La revente et la redistribution de l'application sont
 *                  strictement interdites.
 *
 *                  Vous êtes tenu d'avoir pris connaissance des
 *                  Conditions Générales de Vente disponibles sur Cogites.com
 *                  (y compris pour la version Free).
 *
 *    == EN ==      Resale and redistribution of the application are
 *                  Strictly prohibited.
 *
 *                  You are required to have read the Terms and Conditions
 *                  available on Cogites.com (including the Free version).
 *
 *******************************************************************************
*/
function listFolderFiles($dir){
	$res = "";
	$folders = scandir($dir);
	foreach($folders as $subFolders){
		if($subFolders != '.' && $subFolders != '..'){
			if(!is_writable($dir.'/'.$subFolders)){
				$res = $res . ",";
				if(is_dir($dir.'/'.$subFolders)) listFolderFiles($dir.'/'.$subFolders);
			}
		}
	}
	return $res;
}

	define("LOGGER_ENABLED", TRUE);
	$no_visible_elements=true;
	$pageTitle = "eReserv 6 - Installation";
	require "../_container/container_top.php";

	$rss = dirname(dirname(dirname($_SERVER['SCRIPT_FILENAME'])));

	$optionsRadios = getPost('optionsRadios');
	$action = getPost('action');
	$msg = "";

	if (!empty($action) && $action == "INSTALL_NEW"){
		Logger::info ("---------------> Start eReserv Installation");
		Logger::info ("Action: " . $action);
		$server_host = getPost('server_host');
		$server_port = getPost('server_port');
		$server_dbname = getPost('server_dbname');
		$server_user = getPost('server_user');
		$server_password = getPost('server_password');
		$table_prefix = getPost('table_prefix');
		
		$username = getPost('username');
		$usermail = getPost('usermail');
		$userpass = getPost('userpass');

		$adapterNew = new Zend\Db\Adapter\Adapter(array(
			'driver' => 'Mysqli',
			'hostname' => $server_host,
			'port' => $server_port,
			'database' => $server_dbname,
			'username' => $server_user,
			'password' => $server_password,
			'charset' => 'UTF8'
		));

		try {
			$res = @$adapterNew->getDriver()->getConnection()->connect();
		} catch (Exception $e) {
			$msg = $e->getMessage();
			Logger::err ("ERROR: " . $msg);
			echo "<strong>L'erreur suivante est survenue:<br><br><div style='color:red;'>" . $msg . "</div></strong>";
			die();
		}
	$file = $rss . "/index.php";
	if (file_exists($file)){
		$content = file($file);
		if ($content === false) {
			echo "Problème à l'ouverture du fichier";
			die();
		}else{
			// replace the data
			$l = "";
			foreach ($content as $line) {
				if (stristr($line, 'location')) $l .= 'location= "' . CONTEXT_ROOT_RESS . '/front/admin";' . "\n";
				else $l .= $line;
			}
			// write the file
			if (!empty($l)) {
				file_put_contents($file, $l);
			}else{
				echo "Le fichier lu est vide";
				die();
			}
		}
	}else{
		echo "Fichier introuvable: " . $rss;
		die();
	}
	// read the file
	$file = $rss . "/data/db/db.php";
	if (file_exists($file)){
		$content = file($file);
		if ($content === false) {
			echo "Problème à l'ouverture du fichier";
			die();
		}else{
			// replace the data
			$l = "";
			foreach ($content as $line) {
				if (stristr($line, '$db_server')) $l .= '$db_server = "' . $_POST['server_host'] . '";' . "\n";
				else if (stristr($line, '$db_port')) $l .= '$db_port = "' . $_POST['server_port'] . '";' . "\n";
				else if (stristr($line, '$db_dbname')) $l .= '$db_dbname = "' . $_POST['server_dbname'] . '";' . "\n";
				else if (stristr($line, '$db_user')) $l .= '$db_user = "' . $_POST['server_user'] . '";' . "\n";
				else if (stristr($line, '$db_password')) $l .= '$db_password = "' . $_POST['server_password'] . '";' . "\n";
				else if (stristr($line, '$db_prefix')) $l .= '$db_prefix = "' . $_POST['table_prefix'] . '";' . "\n";
				else $l .= $line;
			}
			// write the file
			if (!empty($l)) {
				file_put_contents($file, $l);
			}else{
				echo "Le fichier lu est vide";
				die();
			}
		}
	}else{
		echo "Fichier introuvable..";
		die();
	}

		$sql_file = 'database.sql';

		$contents = file_get_contents($sql_file);
		$contents = str_replace('{DBNAME}', $server_dbname, $contents);
		$contents = str_replace('{TABLEPREFIX}', $table_prefix, $contents);
		
		// Remove C style and inline comments
		$comment_patterns = array('/\/\*.*(\n)*.*(\*\/)?/', //C comments
								  '/\s*--.*\n/', //inline comments start with --
								  '/\s*#.*\n/', //inline comments start with #
								  );
		$contents = preg_replace($comment_patterns, "\n", $contents);
		// Retrieve sql statements
		$statements = explode(";\n", $contents);
		$statements = preg_replace("/\s/", ' ', $statements);

		foreach ($statements as $sqlquery) {
			if (trim($sqlquery) != '') {
				try {
					$results = $adapterNew->query($sqlquery, $adapterNew::QUERY_MODE_EXECUTE);
					Logger::info ("Successfuly executed sqlquery: " . $sqlquery);
				} catch (Exception $e) {
					Logger::err ("ERROR Executing sqlquery: " . $sqlquery);
					$msg = 'ERROR: ' . $e->getMessage();
				}
			}
		}
		if ($optionsRadios <> "cbInstallMig6Free") {
			// Insert ADMIN user
			$sql = new Zend\Db\Sql\Sql($adapterNew);
			$insertAdminUser = $sql->insert();
			$insertAdminUser->into($table_prefix."users");
			$insertAdminUser->values(array(
					'recorddate' => new Zend\Db\Sql\Expression('NOW()'),
					'enable' => true,
					'username' => $username,
					'email' => $usermail,
					'password' => md5($userpass)
				   )
				);
			$results = $sql->prepareStatementForSqlObject($insertAdminUser)->execute();
	// TODO - Check result
			Logger::info ("ADMIN user ID created: " . $adapterNew->getDriver()->getLastGeneratedValue());
		}
		if ($optionsRadios == "cbInstallMig6Free") {
			$sql_file = 'dbupdfree.sql';

			$contents = file_get_contents($sql_file);
			$contents = str_replace('{DBNAME}', $server_dbname, $contents);
			$contents = str_replace('{TABLEPREFIX}', $table_prefix, $contents);
			
			// Remove C style and inline comments
			$comment_patterns = array('/\/\*.*(\n)*.*(\*\/)?/', //C comments
									  '/\s*--.*\n/', //inline comments start with --
									  '/\s*#.*\n/', //inline comments start with #
									  );
			$contents = preg_replace($comment_patterns, "\n", $contents);
			// Retrieve sql statements
			$statements = explode(";\n", $contents);
			$statements = preg_replace("/\s/", ' ', $statements);

			foreach ($statements as $sqlquery) {
				if (trim($sqlquery) != '') {
					try {
						$results = $adapterNew->query($sqlquery, $adapterNew::QUERY_MODE_EXECUTE);
						Logger::info ("Successfuly executed sqlquery: " . $sqlquery);
					} catch (Exception $e) {
						Logger::err ("ERROR Executing sqlquery: " . $sqlquery);
						$msg = 'ERROR: ' . $e->getMessage();
					}
				}
			}
		}
		if ($optionsRadios <> "cbInstallMig6Free") {

			// Insert CONFIG values
			$sql = new Zend\Db\Sql\Sql($adapterNew);
			$insertConfig = $sql->insert();
			$insertConfig->into($table_prefix."config");
			
	// TODO - Adapt save config to new version
	// TODO add main settings in Install GUI
			$dataConfig = array(
					array('name' => "date_format",'value' => "d.m.Y"),
					array('name' => "currency_symbol",'value' => "€"),
					array('name' => "tracking_payment",'value' => ""),
					array('name' => "language",'value' => "fr_FR"),
					array('name' => "max_list_page",'value' => "5"),
					array('name' => "tax_rate",'value' => "1"),
					array('name' => "mail_system",'value' => "0"),
					array('name' => "smtp_name",'value' => ""),
					array('name' => "smtp_host",'value' => ""),
					array('name' => "smtp_port",'value' => ""),
					array('name' => "smtp_class",'value' => ""),
					array('name' => "smtp_user",'value' => ""),
					array('name' => "smtp_password",'value' => ""),
					array('name' => "smtp_ssl",'value' => ""),
					array('name' => "allow_duplicate_reservation",'value' => "0"),
					array('name' => "lease_reminder_delay",'value' => "5"),
					array('name' => "lease_filename",'value' => "<RESERV_ID>_<NOM_LOC>_<PRENOM_LOC>"),
					array('name' => "lease_keep_on_server",'value' => "1"),
					array('name' => "lease_deposit_percent",'value' => "25"),
					array('name' => "lease_create_2copy",'value' => "1"),
					array('name' => "lease_dateline",'value' => "14"),
					array('name' => "log_enabled",'value' => "1"),
					array('name' => "db_backup_enabled",'value' => "1"),
					array('name' => "cal_start_current_month",'value' => "0"),
					array('name' => "renter_title",'value' => ""),
					array('name' => "renter_lastname",'value' => ""),
					array('name' => "renter_name",'value' => ""),
					array('name' => "renter_address",'value' => ""),
					array('name' => "renter_zipcode",'value' => ""),
					array('name' => "renter_city",'value' => ""),
					array('name' => "renter_country",'value' => ""),
					array('name' => "renter_phone",'value' => ""),
					array('name' => "renter_mobile",'value' => ""),
					array('name' => "renter_email",'value' => ""),
					array('name' => "renter_url",'value' => ""),
					array('name' => "cal_first_weekday",'value' => "1"),
					array('name' => "cal_show_week_number",'value' => "0"),
					array('name' => "cal_8days_week",'value' => "0"),
					array('name' => "cal_show_nomonth_days",'value' => "0"),
					array('name' => "cal_show_reserv_option",'value' => "1"),
					array('name' => "paypal_email",'value' => ""),
					array('name' => "paypal_currency",'value' => "EUR"),
					array('name' => "invoice_text1",'value' => ""),
					array('name' => "invoice_text2",'value' => ""),
					array('name' => "invoice_text3",'value' => ""),
					array('name' => "invoice_signing",'value' => ""),
					array('name' => "cal_multi_item_count",'value' => "10"),
				);
			foreach ($dataConfig as $data) {
				$insertConfig->values(array('name' => $data['name'],'value' => $data['value']));
				$selectString = $sql->getSqlStringForSqlObject($insertConfig);
				Logger::debug ("Insert Config: " . $selectString);
				$results = $adapterNew->query($selectString, $adapterNew::QUERY_MODE_EXECUTE);
				$affectedRows = $results->getAffectedRows();
				Logger::info ("Insert Config ID: " . $adapterNew->getDriver()->getLastGeneratedValue());

				// $results = $sql->prepareStatementForSqlObject($insertConfig)->execute();
				// echo "date_format Last ID: " . $adapterNew->getDriver()->getLastGeneratedValue()."<br>";
				// print_r($results);
			}
		}

		// try {
			// if (file_exists('config.ini')) {
				// Logger::debug ("Config.ini File found");
				// $reader = new Zend\Config\Reader\Ini();
				// $config = $reader->fromFile('config.ini');
				// $config = new Zend\Config\Config($config, true);
			// }else{
				// Logger::debug ("Config.ini File NOT found");
				// $config = new Zend\Config\Config(array(), true);
			// }
			// print_r($config);
			
			// Save Database configuration
			// $config->production = array();
			// $config->production->database = array();
			// $config->production->database->params = array();
			// $config->production->database->params->host = $server_host;
			// $config->production->database->params->username = $server_user;
			// $config->production->database->params->password = $server_password;
			// $config->production->database->params->dbname = $server_dbname;
			// $config->production->database->params->tableprefix = $table_prefix;
			// $writer = new Zend\Config\Writer\Ini();
			// $writer->toFile(CONFIG_FILENAME, $config);
			// Logger::info ("Database Configuration file successfully written.");
		// } catch (Exception $e) {
			// die('ERROR: ' . $e->getMessage());
		// }
		
		///////////////////////////////////////////////////
		// MIGRATION FROM eReserv 5.X
		///////////////////////////////////////////////////
			if ($optionsRadios == "cbInstallMig") {
				Logger::info (" --> MIGRATION start");
				$db_name_old = getPost('db_name_old');
				$table_prefix_old = getPost('table_prefix_old');
				$adapterOld = new Zend\Db\Adapter\Adapter(array(
					'driver' => 'Mysqli',
					'hostname' => $server_host,
					'port' => $server_port,
					'database' => $db_name_old,
					'username' => $server_user,
					'password' => $server_password,
					'charset' => 'UTF8'
				));

				//////////////////////////////////////
				// Get all rows of old 'locataires' Table
				//////////////////////////////////////
				$sqlOld = new Zend\Db\Sql\Sql($adapterOld);
				$select = $sqlOld->select();
				$select->from($table_prefix_old."locataires");
				$selectString = $sqlOld->getSqlStringForSqlObject($select);
				Logger::debug ("  query: " . $selectString);
				$results = $adapterOld->query($selectString, $adapterOld::QUERY_MODE_EXECUTE);
				Logger::info ("  Locataires ID trouve dans old Table: " . $results->count());

				foreach ($results->toArray() as $value) {
					// Check if locataire exist in new table
					$sql = new Zend\Db\Sql\Sql($adapterNew);
					$select = $sql->select();
					$select->from($table_prefix."tenant");
					if (!empty($value['prenom']))
						$select->where(array('name' => $value['prenom']));
					if (!empty($value['nom_locataire']))
						$select->where(array('lastname' => $value['nom_locataire']));
					if (!empty($value['rue']))
						$select->where(array('address1' => $value['rue']));
					if (!empty($value['code_postal']))
						$select->where(array('zipcode' => $value['code_postal']));
					if (!empty($value['ville']))
						$select->where(array('city' => $value['ville']));
					$selectString = $sql->getSqlStringForSqlObject($select);
					$res = $adapterNew->query($selectString, $adapterNew::QUERY_MODE_EXECUTE);
					// echo "  query: " . $selectString . "<br>";
					// echo  "  Locataire trouve dans new Table: " . $res->count() . "<br>";
					
					// Insert locataire in New table if not found
					if ($res->count() == 0) {
						$insert = $sql->insert();
						$insert->into($table_prefix."tenant");
						$insert->values(array(
							'title' => $value['titre'],
							'lastname' => $value['nom_locataire'],
							'name' => $value['prenom'],
							'address1' => $value['rue'],
							'zipcode' => $value['codepostal'],
							'city' => $value['ville'],
							'country' => $value['pays'],
							'phone' => $value['tel'],
							'cellphone' => $value['tel_portable'],
							'email' => $value['email'],
							'newsletter' => true,
							'comment' => $value['commentaires'],
							'recorddate' => $value['date_enreg_locataire'],
							'enable' => ($value['nom_locataire'] == 'supprimé' ? false : true)
						));
						$results = $sql->prepareStatementForSqlObject($insert)->execute();
						$newLoc = $adapterNew->getDriver()->getLastGeneratedValue();
					}else{
						// ID of the locataire found in new table
						$a = $res->toArray();
						$newLoc = $a[0]['tenant_id'];
					}
				}

				// Get all rows of old 'reserv' Table
				$sqlOld = new Zend\Db\Sql\Sql($adapterOld);
				$select = $sqlOld->select();
				$select->from(array('r' => $table_prefix_old."reserv"));
				$select->join(array('l' => $table_prefix_old."locataires"),'r.ID_locataire = l.ID_locataire', $select::SQL_STAR, $select::JOIN_LEFT);
				$select->join(array('lc' => $table_prefix_old."locations"),'r.ID_location = lc.ID_location', $select::SQL_STAR, $select::JOIN_LEFT);
				// $select->join(array('c' => $table_prefix_old."contrats"),'c.ID_location = lc.ID_location', array('c_description' => 'description', 'c_header' => 'en_tete', 'c_recorddate' => 'date_enreg', 'c_position' => 'position', 'c_idlocation' => 'ID_location'), $select::JOIN_LEFT);
				// $select->join(array('s' => $table_prefix_old."saisons"),'s.ID_location = lc.ID_location', $select::SQL_STAR, $select::JOIN_LEFT);

				$selectString = $sqlOld->getSqlStringForSqlObject($select);
				$results = $adapterOld->query($selectString, $adapterOld::QUERY_MODE_EXECUTE);
				Logger::debug ("  query: " . $selectString);
				Logger::info ("Nombre de reservations a traiter: " . $results->count());

				foreach ($results->toArray() as $value) {
					Logger::info ("======= BEGIN looping reservation =======");
					// Check if locataire exist in new table
					$select = $sql->select();
					$select->from($table_prefix."tenant");
					if (!empty($value['prenom']))
						$select->where(array('name' => $value['prenom']));
					if (!empty($value['nom_locataire']))
						$select->where(array('lastname' => $value['nom_locataire']));
					if (!empty($value['rue']))
						$select->where(array('address1' => $value['rue']));
					if (!empty($value['code_postal']))
						$select->where(array('zipcode' => $value['code_postal']));
					if (!empty($value['ville']))
						$select->where(array('city' => $value['ville']));
					$selectString = $sql->getSqlStringForSqlObject($select);
					$res = $adapterNew->query($selectString, $adapterNew::QUERY_MODE_EXECUTE);
					Logger::debug ("  query: " . $selectString);
					Logger::info ("  Locataire trouve dans new Table: " . $res->count());
					
					// Insert locataire in New table if not found
					if ($res->count() == 0) {
						$insert = $sql->insert();
						$insert->into($table_prefix."tenant");
						$insert->values(array(
							'title' => $value['titre'],
							'lastname' => $value['nom_locataire'],
							'name' => $value['prenom'],
							'address1' => $value['rue'],
							'zipcode' => $value['codepostal'],
							'city' => $value['ville'],
							'country' => $value['pays'],
							'phone' => $value['tel'],
							'cellphone' => $value['tel_portable'],
							'email' => $value['email'],
							'newsletter' => true,
							'comment' => $value['commentaires'],
							'recorddate' => $value['date_enreg_locataire'],
							'enable' => ($value['nom_locataire'] == 'supprimée' ? false : true)
						));
						Logger::debug ("  Statement: " . print_r($insert));
						$results = $sql->prepareStatementForSqlObject($insert)->execute();
						$newLocId = $adapterNew->getDriver()->getLastGeneratedValue();
						Logger::debug ("  Tenant added with ID: " . $newLocId);
					}else{
						// ID of the locatire found in new table
						$a = $res->toArray();
						$newLocId = $a[0]['tenant_id'];
					}

					// Check if Location exist
					$select = $sql->select();
					$select->from($table_prefix."tenancy");
					if (!empty($value['nom_location']))
						$select->where(array('name' => $value['nom_location']));
					if (!empty($value['description']))
						$select->where(array('comment' => $value['description']));
					$selectString = $sql->getSqlStringForSqlObject($select);
					$res = $adapterNew->query($selectString, $adapterNew::QUERY_MODE_EXECUTE);
					Logger::debug ("  query: " . $selectString);
					Logger::info ("  Location trouve dans new Table: " . $res->count());
					
					// Insert Location to new database
					if ($res->count() == 0) {
						$insert = $sql->insert();
						$insert->into($table_prefix."tenancy");
						$insert->values(array(
							'recorddate' => new Zend\Db\Sql\Expression('NOW()'),
							'name' => $value['nom_location'],
							'comment' => $value['description']
						));
						$results = $sql->prepareStatementForSqlObject($insert)->execute();
						$newTenancyId = $adapterNew->getDriver()->getLastGeneratedValue();
						Logger::debug ("  Tanancy added with ID: " . $newTenancyId);
					//////////////////////////////////////
					// Get all rows of old 'contrats' Table
					//////////////////////////////////////
						$select = $sqlOld->select();
						$select->from($table_prefix_old."contrats");
						$select->where(array('ID_location' => $value['ID_location']));
						$selectString = $sqlOld->getSqlStringForSqlObject($select);
						$res = $adapterOld->query($selectString, $adapterOld::QUERY_MODE_EXECUTE);
						Logger::debug ("  query: " . $selectString);
						Logger::info ("  Contrats ID trouve dans old Table: " . $res->count());

						foreach ($res->toArray() as $val) {
							// Insert value in new Contrat table
							$insert = $sql->insert();
							$insert->into($table_prefix."leasecontent");
							$insert->values(array(
								'recorddate' => $val['date_enreg'],
								'tenancy_id' => $newTenancyId,
								'position' =>  $val['position'],
								'header' =>  $val['en_tete'],
								'content' =>  $val['description']
							));
							$results = $sql->prepareStatementForSqlObject($insert)->execute();
						    $contrat_id = $adapterNew->getDriver()->getLastGeneratedValue();
						}
					//////////////////////
					// Get all rows of old 'saisons' Table
					//////////////////////
						// Find ID_location in old locations table
						$select = $sqlOld->select();
						$select->from($table_prefix_old."saisons");
						$select->where(array('ID_location' => $value['ID_location']));
						$selectString = $sqlOld->getSqlStringForSqlObject($select);
						$res = $adapterOld->query($selectString, $adapterOld::QUERY_MODE_EXECUTE);
						Logger::debug ("  query: " . $selectString);
						Logger::info ("  Saisons ID trouve dans old Table: " . $res->count());
						
						foreach ($res->toArray() as $val) {
							// Check if season exist in new table
							$select = $sql->select();
							$select->from($table_prefix."season");
							$select->where(array('tenancy_id' => $newTenancyId));
							$select->where(array('start_date' => $val['datedeb_periode']));
							$select->where(array('end_date' => $val['datefin_periode']));
							$selectString = $sql->getSqlStringForSqlObject($select);
							$res = $adapterNew->query($selectString, $adapterNew::QUERY_MODE_EXECUTE);
							Logger::debug ("  query: " . $selectString);
							Logger::info ("  Season trouve dans new Table: " . $res->count());

							// Insert locataire in New table if not found
							if ($res->count() == 0) {
								// Insert value in new Season table
								$insert = $sql->insert();
								$insert->into($table_prefix."season");
								$insert->values(array(
									'recorddate' => new Zend\Db\Sql\Expression('NOW()'),
									'seasontype_id' => $val['ID_saison'],
									'tenancy_id' =>  $newTenancyId,
									'start_date' =>  $val['datedeb_periode'],
									'end_date' =>  $val['datefin_periode']
								));
								$results = $sql->prepareStatementForSqlObject($insert)->execute();
								$season_id = $adapterNew->getDriver()->getLastGeneratedValue();
							}
						}
					}else{
						$a = $res->toArray();
						$newTenancyId = $a[0]['tenancy_id'];
					}
					Logger::debug ("  Last Locataire ID: " . $newLocId);
					Logger::debug ("  Last Tenancy   ID: " . $newTenancyId);

					// Finally insert reservation linked to locataire and location to new database
					$insert = $sql->insert();
					$insert->into($table_prefix."reservation");
					if (isset($value['etat_paiement'])){
						$paid = $value['etat_paiement'];
					}else{
						// on considere les reservation d'annee en cours comme non payées
						if ((date("Y",strtotime($value['datedeb'])) == date("Y")) || (date("Y",strtotime($value['datefin'])) == date("Y"))){
						// if (strpos($value['datedeb'], date("Y") !==false) || strpos($value['datefin'], date("Y") !==false)){
							$paid = false;
						}else{
							$paid = true;
						}
					}
					if ($value['etat_reserv'] == 2) {
						// if (strpos($value['datedeb'], date("Y") !==false) || strpos($value['datefin'], date("Y") !==false)){
						if ((date("Y",strtotime($value['datedeb'])) == date("Y")) || (date("Y",strtotime($value['datefin'])) == date("Y"))){
							if (isset($value['date_envoie_contrat']) && ($value['date_envoie_contrat'] != "0000-00-00")){
								$status = 2;
							}else{
								$status = 1;
							}
						}else{
							$status = 4;
						}
					}else{
						// const RESERV_OPTION = 1;
						// const RESERV_LEASE_SENT = 2;
						// const RESERV_VALIDATE = 3;
						// const RESERV_CLOSED = 4;
						if (isset($value['date_envoie_contrat']) && ($value['date_envoie_contrat'] != "0000-00-00")){
							$status = 2;
						}else{
							$status = 1;
						}
					}
					
					
					$insert->values(array(
						'recorddate' => $value['date_enreg'],
						'tenancy_id' => $newTenancyId,
						'tenant_id' => $newLocId,
						'arrival_date' =>  $value['datedeb'],
						'departure_date' =>  $value['datefin'],
						'lease_date' =>  (isset($value['date_envoie_contrat']) && ($value['date_envoie_contrat'] != "0000-00-00")) ? $value['date_envoie_contrat'] : NULL,
						'price' =>  $value['prix'],
						'paid' =>  $paid,
						'adults_nb' => $value['nbr_adultes'],
						'childs_nb' => $value['nbr_enfants_2_13'],
						'baby_nb' => $value['nbr_enfants_inf_2'],
						'disabled' => $value['pmr'],
						'status' => $status,
						'comment' => $value['commentaire_reserv']
					));
					$results = $sql->prepareStatementForSqlObject($insert)->execute();
					$reservation_id = $adapterNew->getDriver()->getLastGeneratedValue();
					
					//////////////////////
					// Get all rows of old 'paiement' Table
					//////////////////////
						// Find ID_location in old locations table
						$select = $sqlOld->select();
						$select->from($table_prefix_old."paiement");
						$select->where(array('ID_reserv' => $value['ID_reserv']));
						try{
							$selectString = $sqlOld->getSqlStringForSqlObject($select);
							$res = $adapterOld->query($selectString, $adapterOld::QUERY_MODE_EXECUTE);
							Logger::debug ("  query: " . $selectString);
							Logger::info ("  Paiements ID trouve dans old Table: " . $res->count());
							foreach ($res->toArray() as $val) {
								// Insert value in new payment table
								$insert = $sql->insert();
								$insert->into($table_prefix."payment");
								$insert->values(array(
									'recorddate' => $val['paiement_date'],
									'payment_date' => $val['paiement_date'],
									'reservation_id' => $reservation_id,
									'type' =>  $val['paiement_desc'],
									'amount' =>  $val['paiement_montant'],
									'method' =>  $val['paiement_mode']
								));
								$results = $sql->prepareStatementForSqlObject($insert)->execute();
								$paiement_id = $adapterNew->getDriver()->getLastGeneratedValue();
							}
						}catch(Exception $e){
						}

					Logger::info ("======= END looping reservation =======");
				} // end loop reserv table

				// Get all rows of old 'loueur' Table
				$sqlOld = new Zend\Db\Sql\Sql($adapterOld);
				$select = $sqlOld->select();
				$select->from(array('r' => $table_prefix_old."loueur"));
				$selectString = $sqlOld->getSqlStringForSqlObject($select);
				$results = $adapterOld->query($selectString, $adapterOld::QUERY_MODE_EXECUTE);
				Logger::info ("Nombre de loueur a traiter: " . $results->count());

				foreach ($results->toArray() as $value) {
					// Insert value in new Contrat table
					$insert = $sql->insert();
					$insert->into($table_prefix."landlord");
					$insert->values(array(
							'title' => $value['titre'],
							'lastname' => $value['nom_loueur'],
							'name' => $value['prenom_loueur'],
							'address1' => $value['rue'],
							'zipcode' => $value['codepostal'],
							'city' => $value['ville'],
							'country' => $value['pays'],
							'phone' => $value['tel'],
							'cellphone' => $value['tel_portable'],
							'email' => $value['email'],
							'recorddate' => $value['date_enreg_loueur']
					));
					$results = $sql->prepareStatementForSqlObject($insert)->execute();
					$res = $adapterNew->getDriver()->getLastGeneratedValue();
				}
			}
			if(is_dir("../install.done")) {
				@rename("../install.done", "../install.done-". date("Ymd"));
			}
			@rename("../install", "../install.done");
			$options = array(
				'send_expire_cookie' => false,
				'clear_storage'      => true,
			); 
			$sessionManager->destroy($options);
			?>
				<div class="row-fluid">
					<div id="wizardfinal" class="swMain">
						<div id="finalstep">
							<h2 class="StepTitle">Installation d'eReserv</h2>
							<div class="well">
								<h1>eReserv <small>est maintenant installé.</small></h1>
								<p></p>
								<p></p>
								<p><b>Clicker sur CONTINUER pour accéder à eReserv</b></p>
								
								<p class="center">
									<a href="../../" class="btn btn-large btn-primary"> CONTINUER...</a>
								</p>
								<div class="clearfix"></div>
							</div>
						</div>
					</div>
				</div>
			<?php
		Logger::info ("---------------> End of installation");
	}else{
	
	$config['reserv_hour_enabled'] = false;
	$config['reserv_hour_increment'] = 15;
	$config['reserv_hour_12HourFormat'] = 0;
	$config['reserv_hour_mintime'] = 0;
	$config['reserv_hour_maxtime'] = 0;
	

?>
<form id="wizardForm" name="wizardForm" method="post" action="" class="form-horizontal wizardForm">
	<input type="hidden" name="action" id="action" value="">
	<div class="row-fluid">
			<div class="span6">
				<header>
					<h2>Installation d'eReserv</h2>
				</header>
				<?php if ($msg !== "") { ?>
				
				<div class="alert alert-error">
					<button type="button" class="close" data-dismiss="alert"></button>
					<strong>ERROR: </strong><?php echo $msg; ?>
				</div>
				<?php } ?>
				<div id="wizard" class="swMain">
					<ul>
						<li><a href="#step-1">
						<span class="stepNumber">1</span>
						<span class="stepDesc">
						   Step 1<br />
						   <small>Welcome</small>
						</span>
						</a></li>
						<li><a href="#step-2">
						<span class="stepNumber">2</span>
						<span class="stepDesc">
						   Step 2<br />
						   <small>Prérequis</small>
						</span>
						</a></li>
						<li><a href="#step-3">
						<span class="stepNumber">3</span>
						<span class="stepDesc">
						   Step 3<br />
						   <small>Serveur MySql</small>
						</span>
						</a></li>
						<li><a href="#step-4">
						<span class="stepNumber">4</span>
						<span class="stepDesc">
						   Step 4<br />
						   <small>Migration</small>
						</span>                   
						</a></li>
						<li><a href="#step-5">
						<span class="stepNumber">5</span>
						<span class="stepDesc">
						   Step 5<br />
						   <small>Base de Données</small>
						</span>                   
						</a></li>
						<li><a href="#step-6">
						<span class="stepNumber">6</span>
						<span class="stepDesc">
						   Step 6<br />
						   <small>Login eReserv</small>
						</span>                   
						</a></li>
					</ul>
					<div id="step-1">
						<h2 class="StepTitle">Bienvenue</h2>
						<div class="well">
							<p></p>
							<p>Bienvenue dans l'installation d'eReserv. Vous allez être guidé dans toutes les étapes.</p>
							<p></p>
						</div>
					</div>
					<div id="step-2">
						<h2 class="StepTitle">Les Prérequis</h2>
						<div class="well">
							<p>Ci-dessous sont listés les prérequis. Si vous avez un "warning" il se peut qu'eReserv ne fonctionne pas correctement.</p>
						</div>
						<div class="control-group">
							<table class="table table-bordered table-striped table-condensed">
								<thead>
									<tr>
										<th>Composant</th>
										<th>Status</th>
										<th>Description</th>
									</tr>
								</thead>
								<tbody>
									<tr>
										<td>
											<code>PHP: (<?php echo phpversion(); ?>)</code>
										</td>
										<td>
									  <?php $status = ((version_compare(phpversion(), '5.3.0', '<')) ? "warning" : "success"); ?>
											<span class="label label-<?php echo $status; ?>"><?php echo $status; ?></span>
										</td>
										<td>Il faut au minimum PHP 5.3
										</td>
									</tr>
									  <?php
											$arrExtension = array("openssl" => "Permet l'envoi des mails par SMTP (version Pro)", "gd" => "Permet de convertir les images (version Pro)", "mysqli" => "Gère la connection à la base de données");
											$arrExt = get_loaded_extensions();
											foreach ($arrExtension as $ext => $desc){
												$status = ((array_search($ext, $arrExt) === false) ? "important" : "success");
										?>
									<tr>
										<td>
											<code><?php echo $ext; ?></code>
										</td>
										<td>
											<span class="label label-<?php echo $status; ?>"><?php echo $status; ?></span>
										</td>
										<td><?php echo $desc; ?>
										</td>
									</tr>
										<?php
											}
										?>
									<tr>
										<td>
											<code>output_buffering (<?php echo ini_get("output_buffering"); ?>)</code>
										</td>
										<td>
									  <?php $status = ini_get("output_buffering") >0 ? "success" : "warning"; ?>
											<span class="label label-<?php echo $status; ?>"><?php echo $status; ?></span>
										</td>
										<td>Ce paramètre doit être plus grand que "0"
										</td>
									</tr>
									<tr>
										<td>
											<code>date.timezone (<?php echo ini_get("date.timezone"); ?>)</code>
										</td>
										<td>
									  <?php $status = ini_get("date.timezone") ? "success" : "warning"; ?>
											<span class="label label-<?php echo $status; ?>"><?php echo $status; ?></span>
										</td>
										<td>Ce paramètre doit être renseigné
										</td>
									</tr>
									<tr>
										<td>
											<code>disable_functions (<?php echo ini_get("disable_functions"); ?>)</code>
										</td>
										<td>
									  <?php $status = ini_get("disable_functions") == '' ? "success" : "info"; ?>
											<span class="label label-<?php echo $status; ?>"><?php echo $status; ?></span>
										</td>
										<td>Certaines fonctions de PHP ne doivent pas être désactivées.
										</td>
									</tr>
									<tr>
										<td>
											<code>Read-only (<?php echo listFolderFiles('../../data/'); ?>)</code>
										</td>
										<td>
									  <?php $status = listFolderFiles('../../data/') == '' ? "success" : "warning"; ?>
											<span class="label label-<?php echo $status; ?>"><?php echo $status; ?></span>
										</td>
										<td>Il ne doit pas y avoir de répertoires en lecture seule
										</td>
									</tr>
								</tbody>
							</table>
						</div>
					</div>
					<div id="step-3">
						<h2 class="StepTitle">Paramètres de connexion à la base de données</h2>
						<div class="well">
							<p></p>
							<p>Renseignez ici les informations de connexion à votre base de données.</p>
							<p>En général, ce sont les mêmes informations que vous utilisez pour vous connecter à PHPMyAdmin.</p>
							<p></p>
						</div>

						<div class="control-group">
							<label for="server_host" class="control-label">Nom du Server</label>
							<div class="controls">
								<input type="text" name="server_host" id="server_host" value="<?php if (defined('DATABASE_DB_HOSTNAME')) echo DATABASE_DB_HOSTNAME; ?>">
							</div>
						</div>
						<div class="control-group hide">
							<label for="server_port" class="control-label">No du port (default 3306 sur MySQL)</label>
							<div class="controls">
								<input type="text" name="server_port" id="server_port" value="<?php if (defined('DATABASE_DB_HOSTNAME')) echo DATABASE_DB_PORT; else echo "3306"; ?>">
							</div>
						</div>
						<div class="control-group">
							<label for="server_user" class="control-label">Utilisateur</label>
							<div class="controls">
								<input type="text" name="server_user" id="server_user" value="<?php if (defined('DATABASE_DB_USER')) echo DATABASE_DB_USER; ?>">
							</div>
						</div>
						<div class="control-group">
							<label for="server_password" class="control-label">Mot de passe</label>
							<div class="controls">
								<input type="password" name="server_password" id="server_password" value="<?php if (defined('DATABASE_DB_PASSWORD')) echo DATABASE_DB_PASSWORD; ?>">
							</div>
						</div>
					</div>                      
					<div id="step-4">
						<h2 class="StepTitle">Installation Type</h2>
						<div class="well">
							<p></p>
							<p>Dans le cas d'une mise à jour depuis eReserv 5 PLUS, aidez-vous des informations qui se trouve dans le fichier conec.php.</p>
							<p></p>
						</div>
						<div class="control-group">
							<label class="control-label">Installation Type</label>
							<div class="controls">
							  <label class="radio">
								<input class="required" type="radio" name="optionsRadios" id="optionsRadios1" value="cbInstallNew" checked="">
								Nouvelle Installation
							  </label>
							  <div style="clear:both"></div>
							  <label class="radio">
								<input class="required" type="radio" name="optionsRadios" id="optionsRadios2" value="cbInstallMig6Free">
								Mise à jour depuis eReserv 6 Free
							  </label>
							  <div style="clear:both"></div>
							  <label class="radio">
								<input class="required" type="radio" name="optionsRadios" id="optionsRadios3" value="cbInstallMig">
								Mise à jour depuis eReserv 4/5 PLUS
							  </label>
							</div>
						</div>
						<div class="control-group" name="optionsUpgradeDb" id="optionsUpgradeDb">
							<label for="db_name_old" class="control-label">Base de données 5.x</label>
							<div class="controls">
								<input type="text" name="db_name_old" id="db_name_old" value="">
							</div>
						</div>
						<div class="control-group" name="optionsUpgradeTable" id="optionsUpgradeTable">
							<label for="table_prefix_old" class="control-label">Préfix des Tables 5.x</label>
							<div class="controls">
								<input type="text" name="table_prefix_old" id="table_prefix_old" value="ereserv_">
							</div>
						
						</div>
					</div>
					<div id="step-5">
						<h2 class="StepTitle">Paramètres des Tables</h2>
						<div class="well">
							<p></p>
							<p>Le nom de la base de données se trouve dans PHPMyadmin.</p>
							<p>Utilisez un préfixe pour les tables. Cela permet d'identifier rapidement tout ce qui concerne eReserv 6 mais aussi de ne pas avoir 2 tables ayant le même nom.</p>
							<p></p>
						</div>
						<div class="control-group">
							<label for="server_dbname" class="control-label">Nom de la nouvelle base de données</label>
							<div class="controls">
								<input type="text" name="server_dbname" id="server_dbname" value="<?php if (defined('DATABASE_DB_DBNAME')) echo DATABASE_DB_DBNAME; ?>">
							</div>
						</div>
						<div class="control-group">
							<label for="table_prefix" class="control-label">Préfixe des nouvelles Tables</label>
							<div class="controls">
								<input type="text" name="table_prefix" id="table_prefix" value="<?php if (defined('DATABASE_DB_TABLEPREFIX')) {echo DATABASE_DB_TABLEPREFIX;}else{echo "ereserv6_";} ?>">
							</div>
						</div>
					</div>
					<div id="step-6">
						<div id="stepAdminHeader">
						<h2 class="StepTitle">Nouvel Utilisateur</h2>
						<div class="well">
							<p></p>
							<p>Créez votre premier utilisateur pour vous connecter à eReserv.</p>
							<p></p>
						</div>
						</div>
						
						<div id="stepAdmin">
						<div class="control-group">
							<label for="username" class="control-label">Nom</label>
							<div class="controls">
								<input type="text" name="username" id="username">
							</div>
						</div>
						<div class="control-group">
							<label for="usermail" class="control-label">Email</label>
							<div class="controls">
								<input type="text" name="usermail" id="usermail">
							</div>
						</div>
						<div class="control-group">
							<label for="pass" class="control-label">Mot de passe</label>
							<div class="controls">
								<input type="password" name="userpass" id="userpass">
							</div>
						</div>
						<div class="control-group">
							<label for="pass2" class="control-label">Confirmer le mot de passe</label>
							<div class="controls">
								<input type="password" name="userpass2" id="userpass2">
							</div>
						</div>
						</div>
					</div>
				</div> 
			</div>
		</div>
	</div>
</form>
<?php } ?>
<?php require "../_container/container_bottom.php"; ?>
        <script type="text/javascript">
            $(document).ready(function() {
				$("#optionsUpgradeDb").hide();
				$("#optionsUpgradeTable").hide();

				$("#wizardForm").validate({
				 		rules: {
							db_name_old: {required: true},
							server_host: {required: true},
							server_dbname: {required: true},
							server_user: {required: true},
							server_password: {required: false},
							username: {required: true},
							usermail: {required: true,email: true},
							userpass: {required: true,minlength: 5},
							userpass2: {required: true,minlength: 5,equalTo: "#userpass"}
						}
				});
				// Smart Wizard	
				$('#wizard').smartWizard({
					transitionEffect: 'slide',
					keyNavigation: false,
					onLeaveStep: leaveAStepCallback,
					onFinish: onFinishCallback,
					enableFinishButton: false,
					labelNext: 'Suivant',
					labelPrevious: 'Précédent',
					labelFinish: 'Installer'
				});

				$('#wizardfinal').smartWizard({});
				<?php if (!empty($action) && $action == "INSTALL_NEW"){ ?>
					$('.actionBar').hide();
				<?php } ?>

				$('.content').css("height", '450px');
				$('.stepContainer').css("height", '450px');
				$('.swMain ul.anchor li a').css("width", 'auto');

				function leaveAStepCallback(obj){
					var step_num= obj.attr('rel');
					return validateSteps(step_num);
				}

				function onFinishCallback(){
					var isStepValid = true;
					isStepValid = $("#wizardForm").valid();
					if(isStepValid){
						$("#action").val("INSTALL_NEW");
						$('#wizard').smartWizard('showMessage',"Installation en cours. Merci de patienter...");

						$('#finalstep').show();
						// $("#step-5").html("sadfghfdsaf");
						$("#wizardForm").submit();
					}
				} 
				function validateSteps(step){
					var isStepValid = true;
					isStepValid = $("#wizardForm").valid();
					// if(step == 2){
						// if(validateStep1() == false ){
							// isStepValid = false; 
							// $('#wizard').smartWizard('showMessage','Please correct the errors in step'+step+ ' and click next.');
							// $('#wizard').smartWizard('setError',{stepnum:step,iserror:true});         
						// }else{
							// $('#wizard').smartWizard('setError',{stepnum:step,iserror:false});
						// }
					// }
					if (step == 2){
						if ($(".label-warning").length) {
							isStepValid = false;
							$('#wizard').smartWizard('showMessage','Contacter Cogites pour valider les paramètres.');
							$('#wizard').smartWizard('setError',{stepnum:step,iserror:true});
						}else{
							$('#wizard').smartWizard('setError',{stepnum:step,iserror:false});
						}
					}
					return isStepValid;
				} 
			});
			$("#optionsRadios1").click(function(){
				$("#optionsUpgradeDb").hide();
				$("#optionsUpgradeTable").hide();
				$("#stepAdmin").show();
			});
			$("#optionsRadios2").click(function(){
				$("#optionsUpgradeDb").hide();
				$("#optionsUpgradeTable").hide();
				$("#stepAdmin").hide();
			});
			$("#optionsRadios3").click(function(){
				$("#optionsUpgradeDb").show();
				$("#optionsUpgradeTable").show();
				$("#stepAdmin").show();
				$("#stepAdmin").show();
			});
        </script>
