<?php 
session_start();
error_reporting(E_ALL);
if(!isset($_SESSION['install_step']) || $_SESSION['install_step'] < 2) {
	header("location:./requirements.php");
	exit();
}

function SplitSQL($file,$mysqli,$delimiter = ';') {
	$templine = "";
	$lines = file($file);
	foreach ($lines as $line) {
		if (substr($line, 0, 2) == '--' || $line == '') {
			continue;
		}
		$templine .= $line;
		if(substr(trim($line), -1, 1) == ';')	{		
			$mysqli->query($templine) or die($mysqli->error);
			$templine = '';
		}
	}
}

function paste_file($source,$server,$username,$password,$database,$destination) {
	$sampleFile = file_get_contents($source);
	$sampleFile = str_replace("{{server}}",$server,$sampleFile);
	$sampleFile = str_replace("{{username}}",$username,$sampleFile);
	$sampleFile = str_replace("{{password}}",$password,$sampleFile);
	$sampleFile = str_replace("{{database}}",$database,$sampleFile);
	file_put_contents($destination,$sampleFile);
}
function create_json_files()
{
    $lib_path = dirname( dirname(__FILE__) )."/application/libraries/";         
    $files = scandir($lib_path);
    $ignore_files = array(".", "..", "index.html", "sources");
    foreach($files as $file)
    {
        if(in_array($file, $ignore_files)) continue;
        
        $file_name_parts = explode(".", $file);
        $json_path =  $lib_path . "/sources/".$file_name_parts[0].".json";
        if(file_exists($json_path) == FALSE)
        {
            $default_data = array("order" => "1", "icon" => ( strtolower($file_name_parts[0]) . ".png") , "status" => "1", "linkCacheTime" => "3600" );
            file_put_contents($json_path, json_encode($default_data));            
        }
    }
}
if(isset($_POST['submit'])) 
{
	$error = false;
	
	$server = $_POST['server'];
	$username = $_POST['username'];
	$password = $_POST['password'];
	$database = $_POST['database'];
	
	$mysqli = @new mysqli($server, $username, $password, $database);
	
	if($mysqli->connect_error) {
		$error = true;
	}
	else {
		paste_file("samples/connect.sample",$server,$username,$password,$database,"db/connect.php");
		paste_file("samples/database.sample",$server,$username,$password,$database,"../application/config/database.php");
		SplitSQL('db/db.sql',$mysqli);
                
                create_json_files();
                
		$_SESSION['install_step'] = 3;
		header("location:./website_details_settings.php");
		exit();
	}
}
include("includes/head.php"); 
?>
<title>Database Details</title>
<?php include("includes/header.php"); ?>
<?php include("includes/sidebar.php"); ?>
<div class="rightSide">
	<div class="col-xs-12">
		<div class="tab-content shadow-1">
			<div class="tab-pane active">
				<form class="form-horizontal" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
					<?php
					if(isset($_POST['submit']) && $error == true) {
						?>
						<div class="alert alert-danger alert-dismissable">
							<a class="close" data-dismiss="alert" aria-label="close">&times;</a>
							<strong>Error!</strong> Unable to connect to database.
						</div>
						<?php
					}
					?>
					<div class="form-group">
						<label class="col-sm-3 control-label">Database Server</label>
						<div class="col-sm-9">
							<input type="text" name="server" placeholder="e.g: localhost" class="form-control" required value="<?php echo (isset($server) ? $server : ""); ?>" />
						</div>
					</div>
					<div class="form-group">
						<label class="col-sm-3 control-label">Database Name</label>
						<div class="col-sm-9">
							<input type="text" name="database" placeholder="Database Name" class="form-control" required value="<?php echo (isset($database) ? $database : ""); ?>" />
						</div>
					</div>
					<div class="form-group">
						<label class="col-sm-3 control-label">Database Username</label>
						<div class="col-sm-9">
							<input type="text" name="username" placeholder="Database Username" class="form-control" required value="<?php echo (isset($username) ? $username : ""); ?>" />
						</div>
					</div>
					<div class="form-group">
						<label class="col-sm-3 control-label">Database Password</label>
						<div class="col-sm-9">
							<input type="password" name="password" placeholder="Database Password" class="form-control" value="<?php echo (isset($password) ? $password : ""); ?>" />
						</div>
					</div>
					<div class="form-group">
						<div class="col-sm-offset-3 col-sm-8">
							<button type="submit" name="submit" class="btn btn-theme btn-lg">Submit</button>
						</div>
					</div>
				</form>
			</div>
		</div>
	</div>
</div>
<?php include("includes/footer.php"); ?>