<?php 
ini_set('display_errors', 'Off');
define('CONF', __DIR__.'/../conf/conf.php');

$action = $_POST['action'];

if ($action === 'db') {
    $dsn = implode('', ['mysql',':host=', $_POST['host'],';port=', $_POST['port'],';dbname=', $_POST['dbname'],';charset=utf8']);
    try {
        $pdo = new \PDO($dsn, $_POST['username'], $_POST['password']);
    } catch (PDOException $e) {
        $code = $e->getCode();
        switch ($code) {
            case 1045:$error = '数据库账号或密码错误，请重试';break;
            case 1049:$error = '数据库不存在，请确认数据库已被创建';break;
            case 2002:$error = '数据库连接被拒绝，请检查主机IP及主机端口';break;
            default:$error = '超出预期异常:'.$e->getMessage();break;
        }
        die('{"code":false,"error":"'.$error.'"}');
    }

    $statements = explode(";\r\n", file_get_contents(__DIR__.'/sc.sql'));
    foreach ($statements as $statement) {
        $stmt = $pdo->prepare($statement);
        $stmt->execute();
    }

    $conf = file_get_contents(CONF);
    $conf = str_replace('{username}', $_POST['username'], $conf);
    $conf = str_replace('{password}', $_POST['password'], $conf);
    $conf = str_replace('{dbname}', $_POST['dbname'], $conf);
    //$conf = str_replace('{prefix}', $_POST['prefix'], $conf);
    $conf = str_replace('{host}', $_POST['host'], $conf);
    $conf = str_replace('{port}', $_POST['port'], $conf);
    $return  = file_put_contents(CONF, $conf);
    if ($return === false) {
        die('{"code":false,"error":"无写入文件权限，请联系管理员获取文件写入权限"}');
    }

    die('{"code":true,"href":"setting.php"}');
}

if ($action === 'set') {
    $conf = file_get_contents(CONF);
    $conf = str_replace('{protocol}', $_POST['protocol'], $conf);
    $hostname = preg_replace('/http(s?):\/\//i', '', trim($_POST['hostname'], '/'));
    $conf = str_replace('{hostname}', $hostname, $conf);
    $conf = str_replace('{suffix}', $_POST['suffix'], $conf);
    $return  = file_put_contents(CONF, $conf);
    if ($return === false) {
        die('{"code":false,"error":"无写入文件权限，请联系管理员获取文件写入权限"}');
    }

    $return = rename(__DIR__.'/../admin', __DIR__.'/../'.trim($_POST['admin'], '/'));
    if ($return === false) {
        die('{"code":false,"error":"无写入文件权限，请联系管理员获取文件写入权限"}');
    }

    die('{"code":true,"href":"register.php"}');
}

if ($action === 'user') {
    $conf = include CONF;
    $host = $conf['host'];
    $conf = $conf['database'];
    $pdo = new \PDO(implode('', [
        'mysql',
        ':host=', $conf['host'],
        ';port=', $conf['port'],
        ';dbname=', $conf['dbname'],
        ';charset=', $conf['charset']
    ]), $conf['username'], $conf['password']);

    $stmt = $pdo->prepare('UPDATE sc_user SET u_account = ?, u_ciphers = ? WHERE id = ?');
    $stmt->execute([$_POST['username'], base64_encode(md5(base64_encode(sha1($_POST['password'])))), 1]);

    if ($stmt->errorCode() !== '00000') {
        die('{"code":false,"error":'.$stmt->errorInfo()[2].'}');
    }

    $path = [];
    foreach (scandir(__DIR__.'/../') as $name) {
        if (is_dir(__DIR__.'/../'.$name)) {
            $path[] = $name;
        }
    }
    $path = array_diff($path, ['.', '..', 'conf', 'controllers', 'core', 'file', 'install', 'templates', 'vendor']);
    $path = end($path);

    file_put_contents(__DIR__.'/../index.php', str_replace('require_once __DIR__.\'/install/redirect.php\';', '', file_get_contents(__DIR__.'/../index.php')));
    chmod(__DIR__.'/../index.php', 0555);
    file_put_contents(__DIR__.'/../'.$path.'/core.php', str_replace('require_once __DIR__.\'/../install/redirect.php\';', '', file_get_contents(__DIR__.'/../'.$path.'/core.php')));
    file_put_contents(__DIR__.'/../'.$path.'/login.php', str_replace('require_once __DIR__.\'/../install/redirect.php\';', '', file_get_contents(__DIR__.'/../'.$path.'/login.php')));

    delete(__DIR__);

    echo '{"code":true,"href":"'.$host['protocol'].'://'.$host['hostname'].'/'.$path.'/login.php'.'"}';
}

function delete($dir) {
    if (is_dir($dir)) {
        foreach (scandir($dir) as $file) {
            if ($file !== '.' && $file != '..') {
                delete($dir.'/'.$file);
            }
        }
        rmdir($dir);
    } else {
        unlink($dir);
    }
}
