<?php
	set_time_limit(900);
	// configuration
	$php_min = '5.4';
	$required_libs = array('mcrypt','zip','pdo');
	$mysql_host = "localhost";
	$mysql_database = "tender";
	$mysql_user = "root";
	$mysql_password = "";
	
	// check PHP version
	$phpversion = phpversion();
	if($phpversion < $php_min)
	{
		$error[] = "Versi PHP di komputer Anda ".$phpversion." (PHP minimal versi ".$php_min.")";
	}
	
	foreach($required_libs as $lib)
	{
		if (!extension_loaded($lib)) 
		{
			$error[] = "Ekstensi PHP ".$lib." belum terinstall.";
		}
	}
	
	// check database
	$db = new PDO("mysql:host=$mysql_host", $mysql_user, $mysql_password);
	$q = $db->query("SHOW DATABASES LIKE '$mysql_database';");
	
	foreach($q as $row)
	{
		$db_exists = true;
	}
	if(isset($db_exists))
		$error[] = "Database dengan nama '$mysql_database' sudah ada.";
	
	// ada error?
	if(isset($error))
	{
		echo 'Instalasi tidak dapat dilakukan karena:<ol><li>'.implode('</li><li>',$error).'</li></ol>';
	}
	else
	{
		// mulai instalasi
		$zip = new ZipArchive;
		if ($zip->open('tender.zip') === TRUE) 
		{
		    $zip->extractTo('.');
		    $zip->close();
		    
			# MySQL with PDO_MYSQL  
			$db->query('create database if not exists '.$mysql_database);
			$db->query('use '.$mysql_database);

			$query = file_get_contents("database/tender.sql");
			
			$stmt = $db->prepare($query);
			
			if ($stmt->execute())
			{
				$url = "http://".$_SERVER['HTTP_HOST'].str_replace('/install.php','',$_SERVER['REQUEST_URI'])."";
			    echo "Instalasi berhasil. Klik <a href='$url' target='_blank'>$url</a> untuk membuka aplikasi. <br /><b>Informasi Login:</b></br />
			    User admin<br />
			    Username: admin<br />
			    Password: admin	
			    <br /><br />
			    User Panitia<br />
			    Username: panitia<br />
			    Password: panitia			    
			    <br /><br />PENTING! Untuk keamanan, segera hapus file 'install.php'";
			}
			else 
			{
			    echo "Gagal melakukan instalasi database.";
			}
		} 
		else 
		{
		    echo 'Gagal membuka file ZIP.';
		}
	}
?>