<?php
/**
* @project: ImgAnnotations
* @author: Bram Prieshof
*/

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

//seting Vars
//Location of sample config file
$sampleconfigfilePath  = 'db.php.sample';
//Location of new config file
$configfilePath  = 'db.php';
//Name of SQL File
$sqlfileName =  'DB-Template.sql';

if(isset($_POST['submit'])) 
{ 
    //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("$sampleconfigfilePath");
    $filecontent = str_replace("DBName","$DBName",$filecontent);
    $filecontent = str_replace("DBUserName","$DBUser",$filecontent);
    $filecontent = str_replace("DBPassword","$DBPass",$filecontent);
    $file = fopen("$configfilePath", 'w+'); 
    ftruncate($file, 0);
    fwrite($file , $filecontent);
    fclose($file);
    die(header("Location: setup.php?step=2"));
}
$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='password' name='DBPassword' ><br>";
    echo "<input type='submit' name='submit' 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($mysqli);
    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(!$mysqli->query($templine)){
                $error .= 'Error performing query "<b>' . $templine . '</b>": ' . $mysqli->error . '<br /><br />';
            }
            $templine = '';
        }
    }
header("Location: setup.php?step=4");
}

if ($step == '4') {
    unlink("$sqlfileName");
    unlink("$sampleconfigfilePath");
    unlink('setup.php');
    echo "Setup done,removed unnecessary setup files<br><a href='./'>Go to index</a>";
}

?>