<?php
if(file_exists('../config.php')){
    header('Location: '. siteURL() .'/app/login.php');
    die;
}

if($_SERVER['REQUEST_METHOD'] == 'POST'){
    if(isset($_POST['pre-install'])) {
       //
    }elseif(isset($_POST['install'])){
        error_reporting(0);
        ini_set('display_errors',0);

        $hostname = $_POST['hostname'];
        $username = $_POST['username'];
        $password = $_POST['password'];
        $dbname = $_POST['dbname'];
        $t_prefix = $_POST['table_prefix'];

        $password = empty($password) ? '' : $password;

        $content = '<?php

/* DATABASE SETTINGS */
define("DB_HOSTNAME", "'.$hostname.'");
define("DB_USERNAME", "'.$username.'");
define("DB_PASSWORD", "'.$password.'");
define("DB_NAME",     "'.$dbname.'");
define("DB_TABLE_PREFIX",     "'.$t_prefix.'");

?>';
        $error = false;
        try {
            $db = new PDO("mysql:host=$hostname", $username, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
        }
        catch (PDOException $e) {
            $errors = "Connection failed: " . $e->getMessage();
            $error = true;
        }

        $exists_db = false;

        if(!$error) {
            try {
                $db->exec('USE ' . $dbname);
                $exists_db = true;
            } catch (PDOException $e) {
                $exists_db = false;
            }
        }

        if(!$error) {
            // Make my_db the current database
            if (!$exists_db) {
                $sql = 'CREATE DATABASE ' . $dbname;

                try {
                    $db->exec($sql);
                } catch (PDOException $e) {
                    $errors = 'Error creating database: ' . $e->getMessage() . "\n";
                    $error = true;
                }
            }
        }

        if(!$error) {
            try {
                $sql = "USE " . $dbname;
                $db->exec($sql);
            } catch (PDOException $e) {
                $errors = 'Error creating database: ' . $e->getMessage() . "\n";
                $error = true;
            }
        }

        require_once('fb_auto_comments.php');
        $sql = get_sql($t_prefix);

        if(!$error) {
            try {
                $db->exec($sql);
            } catch (PDOException $e) {
                $errors = 'Error creating tables: ' . $e->getMessage() . "\n";
                $error = true;
            }
        }

        $user_email     = $_POST['admin_email'];
        $user_password  = $_POST['admin_password'];
        $user_password = sha1($user_password);

        if(!$error){
            try {
                $fp = fopen("../config.php", "wb");
                fwrite($fp, $content);
                fclose($fp);
            }catch (Exception $e){
                $errors = "Can't create config file: " . $e->getMessage();
                $error = true;
            }

        }

        if(!$error) {
            $check_user = $db->query("SELECT * FROM " . $t_prefix . "users WHERE `email` = '" . $user_email . "'");
            if($check_user->num_rows == 0) {
                $sql = "INSERT INTO " . $t_prefix . "users (`name`, `email`, `password`, `is_admin`, `status`, `created_at`, `fb_pages_limit`) VALUES('" . $user_email . "','" . $user_email . "','" . $user_password . "','1','1','" . time() . "','5000')";

                $db->exec($sql);
            }

            $url = siteURL() . '/app/login.php';
            header('Location: ' . $url);
        }

    }else{
        if(!file_exists('../config.php')){
            header('Location: pre-install.php');
            die;
        }
    }
}else{
    header('Location: pre-install.php');
    die;
}

function siteURL()
{
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    $domainName = $_SERVER['HTTP_HOST'];
    $siteName = trim($_SERVER['PHP_SELF'],"/");
    $siteName = explode("/",$siteName);
    if(empty($siteName))
        return $protocol.$domainName.'/';
    else{
	$protocol = $protocol.$domainName;
	for($i = 0; $i < count($siteName) - 2; $i++){
        	$protocol = $protocol.'/'.$siteName[$i];
		}
	return $protocol;
	}
}

?>

<!DOCTYPE html>
    <head>
		<!-- Title --> 
		<title> Fan Page Auto Commenter </title>
	
		<!-- Meta Data -->
        <meta charset="UTF-8">
		<meta name="description" content="HTML templeate by Sufain Khan" >
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<meta name="author" content="Sufian Khan bdcodex.net">
		
		
		<!-- Mobile Specific Meta -->
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<!--[if IE]><meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'><![endif]-->
		
		
		<!-- Favicon -->
		<link rel="shortcut icon" type="image/x-icon" href="img/favicon/favicon.ico"> 
		<link rel="apple-touch-icon" sizes="72x72" href="img/favicon/apple-touch-icon-72x72.png">
		<link rel="apple-touch-icon" sizes="114x114" href="img/favicon/apple-touch-icon-114x114.png">
		<link rel="apple-touch-icon" sizes="144x144" href="img/favicon/apple-touch-icon.png">
		
		
		<!-- Fonts -->
		<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700,800' rel='stylesheet' type='text/css'>
		<link rel="stylesheet" href="css/font-awesome.min.css">
	
	
		<!-- CSS -->
        <link rel="stylesheet" href="css/bootstrap.min.css">
        <link rel="stylesheet" href="css/main.css">

		
    </head>
    <body style="background: rgb(77, 89, 105) url('./img/bg.jpg') no-repeat fixed center center;">
        <!--[if lt IE 8]>
            <p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
        <![endif]-->
		
		<!-- Content Start here  -->
		
			<div id="form-pages">
				<div class="contianer">
					<div class="row">
						<div class="col-sm-offset-4 col-sm-4 col-xs-10 col-xs-offset-1">
							<div class="form-area">
				
								<h2>Install Application</h2>
                                <?php if(isset($error) && $error){ ?>
                                    <div role="alert" class="alert alert-danger alert-dismissable">
                                        <button type="button" class="close" data-dismiss="alert"
                                                aria-hidden="true">&times;</button>
                                        <?php echo $errors;?>
                                    </div>
                                <?php } ?>
								
								<form action="install.php" method="post">

									<div class="form-group">
										<label for="DatabaseName" class="sr-only"> Database Name </label>
										<input type="text" name="dbname" id="DatabaseName" class="form-control" placeholder="Database Name" required >
									</div>


									<div class="form-group">
										<label for="DatabaseUsername" class="sr-only"> Database Username </label>
										<input type="text" name="username" id="DatabaseUsername" class="form-control"  placeholder="Database Username" required>
									</div>
									
									<div class="form-group">
										<label for="DatabasePassword" class="sr-only"> Database Password</label>
										<input type="password" name="password" id="DatabasePassword" class="form-control" placeholder="Database Password">
									</div>

									<div class="form-group">
										<label for="DatabaseHost" class="sr-only"> Database Host </label>
										<input type="text" name="hostname" id="DatabaseHost" class="form-control" placeholder="Database Host" required >
									</div>

									<div class="form-group">
										<label for="DatabaseHost" class="sr-only"> Tables prefix </label>
										<input type="text" name="table_prefix" id="TablesPrefix" class="form-control" value="autocom_" >
									</div>

									<br>
									<br>
									
									<div class="form-group">
										<label for="AdminEmail" class="sr-only"> Admin Email</label>
										<input type="email" name="admin_email" id="AdminEmail"  class="form-control"  placeholder="Admin Email" required>
									</div> 
									
									<div class="form-group">
										<label for="AdminPassword" class="sr-only"> Re-type password </label>
										<input type="password" name="admin_password" id="AdminPassword:"  class="form-control" placeholder="Admin Password:" required>
									</div>

                                    <input type="hidden" name="install" value="true">
									
									<div class="clearfix form-group">
										<div class="row">
											<div class="col-sm-12 text-right">
												  <button type="submit" class="btn btn-fb">Install</button>
											</div>
										</div>
									</div>
									
								</form>
							
							</div>
						</div>
					</div>
				</div>
			</div>
			
			<footer id="footer">
				<div class="container">
					<div class="row">
						<div class="col-sm-12 text-center">
							<div class="footer">
								<p>Copyright © 2015 HENOZ Developers Pvt Ltd. All Rights Reserved.</p>
							</div>
						</div>
					</div>
				</div>
			</footer>

		<!-- Contents End here  //.-->
    </body>
</html>
