<?php
ini_set('display_errors', true);
error_reporting(E_ALL);

$errors = [];
$form_errors = [];
// check php version
$php_ver = (float) PHP_VERSION;

if($php_ver < 5.4)
    array_push($errors, "Your php version is $php_ver. Required 5.4");
$modules = get_loaded_extensions();
$need_modules = array('mysql', 'pdo_mysql', 'ctype', 'mbstring', 'session', 'PDO', 'curl');

foreach($need_modules as $nd)
{
    if(!in_array($nd, $modules))
        array_push($errors, "Need php extension - $nd");
}

if(!file_exists('./bootstrap/config.php.example'))
    array_push($errors, 'File ./bootstrap/config.php.example not found');
elseif(!is_readable('./bootstrap/config.php.example'))
    array_push($errors, 'File ./bootstrap/config.php.example is not readable');

if(!file_exists('./dump.sql'))
    array_push($errors, 'File ./dump.sql not found');
elseif(!is_readable('./dump.sql'))
    array_push($errors, 'File ./dump.sql is not readable');

if(!is_writable('./bootstrap'))
    array_push($errors, 'Directory ./bootstrap is not writable. I have to save a configuration file there..');


if($_SERVER['REQUEST_METHOD'] == 'POST' && !$errors)
{
    $login = trim($_POST['login']);
    $pass = trim($_POST['pass']);
    if(!$login)
        array_push($form_errors, 'Enter login');
    if(!$pass)
        array_push($form_errors, 'Enter password');

    $dbHost = trim($_POST['db']['host']);
    $dbName = trim($_POST['db']['name']);
    $dbUser = trim($_POST['db']['user']);
    $dbPass = trim($_POST['db']['password']);
    $bot_timeout = trim($_POST['other']['bot_timeout']);
	$bot_timeout = ($bot_timeout*60);
    if(!$dbHost)
        array_push($form_errors, 'Enter DB Host');
    if(!$dbName)
        array_push($form_errors, 'Enter DB Name');
    if(!$dbUser)
        array_push($form_errors, 'Enter DB User');

    $otherRC4_key = trim($_POST['other']['rc4_key']);

    if(!$otherRC4_key)
        array_push($form_errors, 'Enter RC4 key');

    if(!$bot_timeout)
        array_push($form_errors, 'Enter Bots timeout');
		
    if(empty($form_errors))
    {
        try{
            $dsn = 'mysql:host=' . $dbHost .
                # ';dbname='    . $dbName .
                ';port='      . '' .
                ';connect_timeout=15';

            $db = new PDO($dsn, $dbUser, $dbPass);
            $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            $db->beginTransaction();
            $tables = $db->query("SHOW DATABASES")->fetchAll(PDO::FETCH_COLUMN);
            if(!in_array($dbName, $tables))
                $db->exec("CREATE DATABASE `$dbName`");
            $db->exec("USE `$dbName`");
            $db->exec(file_get_contents("./dump.sql"));
            $db->commit();
        }catch (PDOException $e){
            if(isset($db) && $db instanceof PDO)
                $db->rollBack();
            array_push($form_errors, $e->getMessage());
        }

        if(!$form_errors)
        {
            $config = file_get_contents('./bootstrap/config.php.example');
            $config = str_replace("{db.host}", $dbHost, $config);
            $config = str_replace("{db.name}", $dbName, $config);
            $config = str_replace("{db.user}", $dbUser, $config);
            $config = str_replace("{db.password}", $dbPass, $config);
            $config = str_replace("{login}", $login, $config);
            $config = str_replace("{pass}", $pass, $config);
            $config = str_replace("{other.rc4_key}", $otherRC4_key, $config);
			$config = str_replace("{bot_timeout}", $bot_timeout, $config);

            file_put_contents('./bootstrap/config.php', $config);
            chmod('./bootstrap/config.php', 0777);

            header("Location: admin.php?do=auth");
            exit();
        }
    }
}

?>

<html>
<head>
    <meta charset="utf-8">
    <title>Инсталлятор</title>
    <link rel="stylesheet" href="public/css/bootstrap.min.css">
    <script src="public/js/jquery-2.1.3.min.js"></script>
    <script src="public/js/bootstrap.min.js"></script>
    <script src="public/js/app.js"></script>
</head>
<body style="background: #fff">

<div class="container" style="margin-top: 25px;">
    <?php if(!empty($errors)):?>
        <div class="alert alert-danger alert-dismissible" role="alert">
            <strong>Configuration check: </strong><br>
            <ul>
                <?php foreach($errors as $error):?>
                    <li><?php echo($error)?></li>
                <?php endforeach?>
            </ul>

        </div>
    <?php endif?>
    <div class="well well-lg">
        <?php if(!empty($form_errors)):?>
            <div class="alert alert-danger alert-dismissible" role="alert">
                <strong>Form errors: </strong><br>
                <ul>
                    <?php foreach($form_errors as $error):?>
                        <li><?php echo($error)?></li>
                    <?php endforeach?>
                </ul>

            </div>
        <?php endif?>
        <form action="install.php" class="form-horizontal" method="post">
            <fieldset>
                <legend>Access to admin area</legend>
                <div class="form-group">
                    <label class="control-label col-sm-3">Login</label>
                    <div class="col-sm-9">
                        <input type="text" name="login" <?php echo($errors ? 'disabled' : '')?> class="form-control" value="<?php echo isset($_POST['login']) ? htmlentities($_POST['login']) : ''?>">
                    </div>
                </div>

                <div class="form-group">
                    <label class="control-label col-sm-3">Pass</label>
                    <div class="col-sm-9">
                        <input type="text" name="pass" <?php echo($errors ? 'disabled' : '')?> class="form-control" value="<?php echo isset($_POST['pass']) ? htmlentities($_POST['pass']) : ''?>">
                    </div>
                </div>
            </fieldset>

            <fieldset>
                <legend>Database settings</legend>
                <div class="form-group">
                    <label class="control-label col-sm-3">DB Host</label>
                    <div class="col-sm-9">
                        <input type="text" name="db[host]" placeholder="localhost" <?php echo($errors ? 'disabled' : '')?> class="form-control" value="<?php echo isset($_POST['db']['host']) ? htmlentities($_POST['db']['host']) : ''?>">
                    </div>
                </div>
                <div class="form-group">
                    <label class="control-label col-sm-3">DB Name</label>
                    <div class="col-sm-9">
                        <input type="text" name="db[name]" <?php echo($errors ? 'disabled' : '')?> class="form-control" value="<?php echo isset($_POST['db']['name']) ? htmlentities($_POST['db']['name']) : ''?>">
                    </div>
                </div>
                <div class="form-group">
                    <label class="control-label col-sm-3">DB User</label>
                    <div class="col-sm-9">
                        <input type="text" name="db[user]" placeholder="root" <?php echo($errors ? 'disabled' : '')?> class="form-control" value="<?php echo isset($_POST['db']['user']) ? htmlentities($_POST['db']['user']) : ''?>">
                    </div>
                </div>
                <div class="form-group">
                    <label class="control-label col-sm-3">DB Password</label>
                    <div class="col-sm-9">
                        <input type="text" name="db[password]" <?php echo($errors ? 'disabled' : '')?> class="form-control" value="<?php echo isset($_POST['db']['password']) ? htmlentities($_POST['db']['password']) : ''?>">
                    </div>
                </div>
            </fieldset>

            <fieldset>
                <legend>Other settings</legend>

                <div class="form-group">
                    <label class="control-label col-sm-3">RC4 key</label>
                    <div class="col-sm-9">
                        <input type="text" name="other[rc4_key]" <?php echo($errors ? 'disabled' : '')?> class="form-control" value="<?php echo isset($_POST['other']['rc4_key']) ? htmlentities($_POST['other']['rc4_key']) : ''?>">
                    </div>
                </div>
				
                <div class="form-group">
                    <label class="control-label col-sm-3">Bots timeout</label>
                    <div class="col-sm-9">
                        <input type="text" placeholder="MINUTE (exemple: 5)" name="other[bot_timeout]" <?php echo($errors ? 'disabled' : '')?> class="form-control" value="<?php echo isset($_POST['other']['bot_timeout']) ? htmlentities($_POST['other']['bot_timeout']) : ''?>">
                    </div>
                </div>
				

                <div class="form-group">
                    <div class="col-sm-9 col-sm-offset-3">
                        <input type="submit" <?php echo($errors ? 'disabledss' : '')?> class="btn btn-primary btn-block" value="Install">
                    </div>
                </div>


            </fieldset>

        </form>
    </div>


</div>
</body>
</html>