<?php

function getUserInput(string $label): string
{
	echo $label;

	return str_replace("\n", '', fgets(STDIN));
}

const TEMPLATE_SETTINGS = '<?php

/*
 * This file was auto generated on :DATETIME
 */
 
declare(strict_types=1);

final class Setting
{
    public const MYSQL_HOST = \':HOST\';
    public const MYSQL_USER = \':USER\';
    public const MYSQL_PASSWORD = \':PASSWORD\';
    public const MYSQL_DATABASE = \':DATABASE\';

    public const PATH_ROOT = \':ROOT_PATH/\';
    public const PATH_QR_CODES = self::PATH_ROOT . \'backend/qr/\';
    public const PATH_TMP = self::PATH_ROOT . \'backend/tmp/\';
}
';

$hostname = getUserInput('MySQL host address (default "localhost"): ');
$username = getUserInput('MySQL user: ');
$password = getUserInput('MySQL password (shown!): ');
$database = getUserInput('MySQL database: ');

$settings = str_replace(
	[':HOST', ':USER', ':PASSWORD', ':DATABASE', ':ROOT_PATH', ':DATETIME'],
	[$hostname, $username, $password, $database, getcwd(), (new DateTime())->format('Y-m-d H:i:s')],
	TEMPLATE_SETTINGS
);

$file = fopen(getcwd() . '/backend/classes/Setting.php', 'w');
fwrite($file, $settings);
fclose($file);

require 'backend/classes/core/Autoloader.php';

Autoloader::BuildCache();

$autoloader = new Autoloader();

$file = fopen('backend/scripts/setup.sql', 'r');
$setupSql = fread($file, filesize('backend/scripts/setup.sql'));
fclose($file);

$db = new MySqlDatabase($hostname, $username, $password, $database);
$db->Query($setupSql);

echo 'Ringfinger setup has successfully finished.' . PHP_EOL;