<?php
//NOTE That sample file need to be in the same folder and be called "config.php.sample"

//seting Vars


//Location of new config file
$configfilePath  = 'assets/php/config.php';
//name of SQL File
$sqlfileName =  'SYSDesk.sql';

if(isset($_POST['submits1'])) 
{ 
    //You have to get the form data
    $DBName = $_POST["DBName"]; 
    $DBUser = $_POST["DBUser"];
    $DBPass = $_POST["DBPassword"];
    
    echo "$DBname";
    echo "$DBUser";
    echo "$DBpass";
    //Open your .txt file
    $filecontent = file_get_contents("config.php.sample");
    $filecontent = str_replace("DBName","$DBName",$filecontent);
    $filecontent = str_replace("DBUser","$DBUser",$filecontent);
    $filecontent = str_replace("DBPass","$DBPass",$filecontent);
    $file = fopen("$configfilePath", 'w+'); 
    ftruncate($file, 0);
    fwrite($file , $filecontent);
    fclose($file);
    die(header("Location: setup.php?step=2"));
}


if(isset($_POST['submits2'])) 
{ 
require_once "$configfilePath";
 $username = $password = $confirm_password = "";
$username_err = $password_err = $confirm_password_err = "";
    // Validate username
    if(empty(trim($_POST["username"]))){
        $username_err = "Please enter a username.";
    } else{
        // Prepare a select statement
        $sql = "SELECT id FROM users WHERE username = ?";
        
        if($stmt = mysqli_prepare($link, $sql)){
            // Bind variables to the prepared statement as parameters
            mysqli_stmt_bind_param($stmt, "s", $param_username);
            
            // Set parameters
            $param_username = trim($_POST["username"]);
            
            // Attempt to execute the prepared statement
            if(mysqli_stmt_execute($stmt)){
                /* store result */
                mysqli_stmt_store_result($stmt);
                
                if(mysqli_stmt_num_rows($stmt) == 1){
                    $username_err = "This username is already taken.";
                } else{
                    $username = trim($_POST["username"]);
                }
            } else{
                echo "Oops! Something went wrong. Please try again later.";
            }
        }
         
        // Close statement
        mysqli_stmt_close($stmt);
    }
    
    // Validate password
    if(empty(trim($_POST["password"]))){
        $password_err = "Please enter a password.";     
    } elseif(strlen(trim($_POST["password"])) < 6){
        $password_err = "Password must have atleast 6 characters.";
    } else{
        $password = trim($_POST["password"]);
    }
    
    // Validate confirm password
    if(empty(trim($_POST["confirm_password"]))){
        $confirm_password_err = "Please confirm password.";     
    } else{
        $confirm_password = trim($_POST["confirm_password"]);
        if(empty($password_err) && ($password != $confirm_password)){
            $confirm_password_err = "Password did not match.";
        }
    }
    if(empty($username_err) && empty($password_err) && empty($confirm_password_err)){
        $sql = "INSERT INTO users (username, password) VALUES (?, ?)";
        if($stmt = mysqli_prepare($link, $sql)){
            mysqli_stmt_bind_param($stmt, "ss", $param_username, $param_password);
            $param_username = $username;
            $param_password = password_hash($password, PASSWORD_DEFAULT);
            if(mysqli_stmt_execute($stmt)){
                header("location: setup.php?step=5");
            } else{
                echo "Something went wrong. Please try again later.";
            }
        }
        mysqli_stmt_close($stmt);
    }
    mysqli_close($link);
}


$step = isset( $_GET['step'] ) ? (int) $_GET['step'] : 1;
?>

<?php
$serv = $_SERVER['PHP_SELF'];

if ($step == '1') {
echo"Setup Database connection";
echo"<form method='post' action='$serv'>";
    echo "DBName:<br><input type='text' name='DBName' ><br>";
        echo "DBUser:<br><input type='text' name='DBUser' ><br>";
    echo "DBPassword:<br><input type='text' name='DBPassword' ><br>";
   echo "<input type='submit' name='submits1' value='Create config' ><br>";
echo "</form>";
}

if ($step == '2') {
echo "<a href='setup.php?step=1'>If conection faild click here</a><br>";
require_once "$configfilePath";
mysqli_close($link);
header("Location: setup.php?step=3");
}


if ($step == '3') {
echo "Populating DB";
require_once "$configfilePath";
    $templine = '';
    $lines = file($sqlfileName);
    $error = '';
    foreach ($lines as $line){
        if(substr($line, 0, 2) == '--' || $line == ''){
            continue;
        }
        $templine .= $line;
        if (substr(trim($line), -1, 1) == ';'){
            if(!$link->query($templine)){
                $error .= 'Error performing query "<b>' . $templine . '</b>": ' . $link->error . '<br /><br />';
            }
            $templine = '';
        }
    }
header("Location: setup.php?step=4");
}


if ($step == '4') {
echo"<p>Please fill this form to create an account.</p>";
echo"<form method='post' action='setup.php?step=4'>";
            echo"<div class='form-group ''>";
                echo"<label>Username</label><br>";
                echo"<input type='text' name='username' class='form-control' value='$username'>";
                echo"<span class='help-block'> $username_err </span>";
            echo"</div>";
            echo"<div class='form-group (!empty($password_err)) ? 'has-error' : '''>";
                echo"<label>Password</label><br>";
                echo"<input type='password' name='password' class='form-control' value='$password'>";
                echo"<span class='help-block'> $password_err</span>";
            echo"</div>";
            echo"<div class='form-group  (!empty($confirm_password_err)) 'has-error' : '''>";
                echo"<label>Confirm Password</label><br>";
                echo "<input type='password' name='confirm_password' class='form-control' value='$confirm_password'>";
                echo"<span class='help-block'> $confirm_password_err </span>";
            echo"</div>";
                echo "<input type='submit' name='submits2' value='Create User' ><br>";
echo "</form>";
}

if ($step == '5') {
echo "Setup done !";
echo"<br>";
echo "Please remove setup.php, config.php.sample and your .SQL file";
}

?>