<?php
/**
 * Created by PhpStorm.
 * User: 中闽 < 1464674022@qq.com >
 * Date: 2020/2/4
 * Time: 12:47
 */

namespace app\install\controller;

use mysqli;
use think\Controller;
use think\Env;

class Index extends Controller
{
    protected function _initialize()
    {
        if (is_installed()) {
            $this->error('无法重复安装，请删除install.lock才能再次安装！', '/');
        }
    }

    public function index()
    {
        return $this->fetch('step1');
    }

    public function step2()
    {
        $data['pdo'] = class_exists('pdo') ? 1 : 0;
        $data['pdo_mysql'] = extension_loaded('pdo_mysql') ? 1 : 0;
        $data['curl'] = extension_loaded('curl') ? 1 : 0;
        $data['putenv'] = function_exists('putenv') ? 1 : 0;
        $data['upload_size'] = ini_get('file_uploads') ? ini_get('upload_max_filesize') : 0;
        $data['session'] = function_exists('session_start') ? 1 : 0;
        return $this->fetch('', ['data' => $data]);
    }

    public function step3()
    {
        $this->assign('db_host', Env::get('db_host', '127.0.0.1'));
        $this->assign('db_port', Env::get('db_port', '3306'));
        $this->assign('db_name', Env::get('db_name', 'tplay'));
        $this->assign('db_username', Env::get('db_username', 'root'));
        $this->assign('db_password', Env::get('db_password', ''));
        $this->assign('db_prefix', Env::get('db_prefix', 'tplay_'));
        return $this->fetch();
    }


    private function initEnvConfig($data)
    {
        $env_str = "app_debug = false
app_trace = false
db_host = {$data['DB_HOST']}
db_port = {$data['DB_PORT']}
db_name = {$data['DB_NAME']}
db_username = {$data['DB_USER']}
db_password = {$data['DB_PWD']}
db_prefix = {$data['DB_PREFIX']}";

        if (false == file_put_contents(ROOT_PATH . ".env", $env_str)) {
            $this->error('创建env配置文件失败，请检查目录权限');
        }
    }

    public function createData()
    {
        if ($this->request->isPost()) {
            $data = $this->request->param();
            $validate = new \think\Validate([
                ['DB_TYPE|数据库类型', 'require|eq:mysql'],
                ['DB_HOST|数据库地址', 'require'],
                ['DB_PORT|数据库端口', 'require'],
                ['DB_USER|数据库用户名', 'require'],
//                ['DB_PWD|数据库密码', 'require'],
                ['DB_NAME|数据库名字', 'require'],
                ['DB_PREFIX|表前缀', 'require'],
                ['username|管理员账户', 'require'],
                ['password|密码', 'require|confirm'],
            ]);
            if (!$validate->check($data)) {
                $this->error('提交失败：' . $validate->getError());
            }

            // create .env
            $this->initEnvConfig($data);

            // connect db
            $link = @new mysqli("{$data['DB_HOST']}:{$data['DB_PORT']}", $data['DB_USER'], $data['DB_PWD']);
            $error = $link->connect_error;
            if (!is_null($error)) {
                // 转义防止和alert中的引号冲突
                $error = addslashes($error);
                $this->error('数据库链接失败:' . $error);
            }
            $link->query("SET NAMES 'utf8'");
            if ($link->server_info < 5.0) {
                $this->error('请将您的mysql升级到5.0以上');
            }

            if (!$link->select_db($data['DB_NAME'])) {
                //创建库
                $create_sql = 'CREATE DATABASE IF NOT EXISTS ' . $data['DB_NAME'] . ' DEFAULT CHARACTER SET utf8;';
                if (!$link->query($create_sql)) {
                    $this->error('数据库链接失败');
                }
                $link->select_db($data['DB_NAME']);
            }

            // 导入sql
            if (file_exists(APP_PATH . 'install/data/db.sql')) {
                $tplay_sql = file_get_contents(APP_PATH . 'install/data/db.sql');
            } else {
                $tplay_sql = file_get_contents(APP_PATH . 'install/data/tplay.sql');
            }

            $search = [
                "tplay_",
                "USE `tplay`",
                "CREATE DATABASE IF NOT EXISTS `tplay`",
            ];
            $replace = [
                $data['DB_PREFIX'],
                "USE `" . $data['DB_NAME'] . "`",
                "CREATE DATABASE IF NOT EXISTS `" . $data['DB_NAME'] . "`",
            ];
            $sql_array = preg_split("/;[\r\n]+/", str_replace($search, $replace, $tplay_sql));
            foreach ($sql_array as $k => $v) {
                if (!empty($v)) {
                    $link->query($v);
                }
            }

            // create install.lock
            $salt = random_string();
            if (false == file_put_contents(ROOT_PATH . "install.lock", "安装鉴定文件，请勿删除，勿修改，勿泄露此文件！！！此次安装时间：" . date('Y-m-d H:i:s', time()) . " - {$salt}")) {
                $this->error('创建安装鉴定文件失败，请检查目录权限');
            }

            // update admin password
            $link->query("UPDATE `{$data['DB_PREFIX']}admin` SET `name` = '{$data['username']}',`password` = '" . password($data['password']) . "' WHERE `id` = 1");
            $link->close();

            $this->success('安装成功');
        }
    }
}

