<?php
//use Illuminate\Support\Facades\DB;

use \Backend\Models\AdminUser;
use JetBrains\PhpStorm\ArrayShape;


/**
 * @param string $servername
 * @param string $username
 * @param string $password
 * @param string $DBName
 * @return string[]
 */
function myDB(string $servername, string $username, string $password, string $DBName): array
{
    $conn = new mysqli($servername, $username, $password);

    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    $sql = "CREATE DATABASE ".$DBName;
    if ($conn->query($sql) === TRUE) {
        echo "Database created successfully";
    } else {
        echo "Error creating database: " . $conn->error;
    }
    $conn->close();
    return array(
        "driver" => "mysql",
        "host" => $servername,
        "database" => $DBName,
        "username" => $username,
        "password" => $password
    );
}

/**
 * @param string $DBName
 * @return string[]
 */
function liteDB(string $DBName): array
{
    New SQLite3("Database/".$DBName.".sqlite");
    $test = array(
        'driver' => 'sqlite',
        'database' => realpath(dirname(__FILE__)."/Database/".$DBName.".sqlite")
           //'Backend/Database/'.$DBName.'.sqlite'
    );
    var_dump($test);
    return $test;
}


$servername = "localhost";
$username = "root";
$password = "V#_xWL6_";
$DBName = "TestDB";
if(isset($_POST["dbSetup"])){


    switch($_POST["dbType"]){
        case "mysql":
            $dbCon = myDB($_POST["dbServername"],$_POST["dbUsername"],$_POST["dbPassword"], $_POST["dbName"]);
            break;
        case "sqlite":
            $dbCon = liteDB($_POST["dbName"]);
            break;
        default:
            die("wrong dbType");
    }

    file_put_contents("../config/database.json", json_encode($dbCon));

    require_once('../bootstrap.php');
    try{
        $capsule->Connection()->getPdo();
    } catch (\Exception $e) {
        //file_put_contents("../config/database.json", NULL);
        die("Could not connect to the database.  Please check your configuration. error:" . $e );
    }
    require_once ('Database/databaseMigration.php');
    AdminUser::firstOrCreate([
        'user_name' => $_POST["AdminUsername"], 'password' => password_hash($_POST["AdminPassword"],PASSWORD_DEFAULT)
    ]);



}else{
    echo "not set";

}






