<?php
/**
 * Copyright: Shanghai NuLang Network Technology Co., Ltd.
 * Faith: Some things do not need others to understand.
 * Project: CoverCMS <Your world, your ambition>
 * License: http://www.svipplus.cn/license/
 * Author: The Rain° <rain@svipplus.cn>
 * File: DefaultController.php
 * Time: 11:24
 */

namespace app\install\controller;


use app\common\toolKit\CacheKit;
use app\common\toolKit\CommonKit;
use Symfony\Component\Filesystem\Filesystem;
use think\Controller;

class DefaultController extends Controller
{
    private $version;

    public function _initialize()
    {
        $version = require_once ROOT_PATH . 'vendor' . DS . 'covercms' . DS . 'framework' . DS . 'src' . DS . 'version.php';
        $this->version = $version;
    }

    public function indexAction()
    {
        $license_agreement = file_get_contents(ROOT_PATH . 'resources' . DS . 'asset' . DS . 'install' . DS . 'data' . DS . 'license.txt');
        $this->assign([
            'license_agreement' => $license_agreement,
            'version' => $this->version
        ]);
        return $this->fetch();
    }

    public function checkAction()
    {
        $this->redirect('info');
    }

    public function infoAction()
    {
        if (request()->isPost()) {
        }
        $this->assign([
            'version' => $this->version
        ]);
        return $this->fetch();
    }

    public function DatabaseAction()
    {
        if (request()->isPost()) {
            $dataFromPost = $_POST;
            $dbms = 'mysql';
            $host = $dataFromPost['dbhost'];
            $dbName = $dataFromPost['dbname'];
            $user = $dataFromPost['dbuser'];
            $pass = $dataFromPost['dbpw'];
            $dsn = "$dbms:host=$host;dbname=$dbName";
            try {
                $dbh = new \PDO($dsn, $user, $pass, [
                    \PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true
                ]);

                if (empty(trim($dataFromPost['manager'])) || empty(trim($dataFromPost['manager_pwd'])) || empty(trim($dataFromPost['manager_ckpwd']))) {
                    return json(['state' => 'fail', 'message' => '管理员账号或密码配置不正确']);
                }
                if ($dataFromPost['manager_pwd'] !== $dataFromPost['manager_ckpwd']) {
                    return json(['state' => 'fail', 'message' => '两次密码输入不匹配']);
                }
                $password = password_hash(config('cloud.secret') . $dataFromPost['manager_pwd'], PASSWORD_BCRYPT);
                $siteRoot = request()->domain() . request()->root();
                if (request()->root() !== '/') {
                    $siteRoot .= '/';
                }
                $replaceP = addcslashes(addcslashes($siteRoot, '/'), '/');
                $baseLocal = "http://localhost/niukou/";
                $local = addcslashes(addcslashes($baseLocal, '/'), '/');
                $sqlFile = file_get_contents(ROOT_PATH . 'resources' . DS . 'asset' . DS . 'install' . DS . 'data' . DS . 'db.sql');
                $sqlFile = str_replace($local, $replaceP, $sqlFile);
                $sqlFile = str_replace($baseLocal, $siteRoot, $sqlFile);
                $sqlFile = str_replace('{%coverprise_manager%}', $dataFromPost['manager'], $sqlFile);
                $sqlFile = str_replace('{%coverprise_manager_pwd%}', $password, $sqlFile);
                $sqlFile = str_replace('{%coverprise_manager_email%}', $dataFromPost['manager_email'], $sqlFile);
                $sqlFile = str_replace('{%coverprise_manager_create%}', time(), $sqlFile);
                $sqlFile = str_replace('{%coverprise_manager_update%}', time(), $sqlFile);
                $dealtSql = $this->sql_split($sqlFile, trim($dataFromPost['dbprefix']));
                if (is_array($dealtSql)) {
                    foreach ($dealtSql as $sql) {
                        if (trim($sql) != '') {
                            $dbh->exec($sql);
                        }
                    }
                } else {
                    $dbh->exec($dealtSql);
                }
                $databaseConfigFile = APP_PATH . 'database.php';
                $databaseConfig = file_get_contents($databaseConfigFile);
                $databaseConfig = str_replace('{%coverprise_host%}', $dataFromPost['dbhost'], $databaseConfig);
                $databaseConfig = str_replace('{%coverprise_dbname%}', $dataFromPost['dbname'], $databaseConfig);
                $databaseConfig = str_replace('{%coverprise_dbuser%}', $dataFromPost['dbuser'], $databaseConfig);
                $databaseConfig = str_replace('{%coverprise_dbpwd%}', $dataFromPost['dbpw'], $databaseConfig);
                $databaseConfig = str_replace('{%coverprise_dbpre%}', $dataFromPost['dbprefix'], $databaseConfig);
                @file_put_contents($databaseConfigFile, $databaseConfig);
                return json(['state' => 'success', 'referer' => url('finish')]);
            } catch (\PDOException $e) {
                return json(['state' => 'fail', 'message' => $e->getMessage()]);
            }
        }
    }

    public function finishAction()
    {
        CacheKit::updateSiteCache();
        CacheKit::updateCategoryCache();
        CacheKit::updateManagerCache();
        $baseUrl = 'http://coverprise.svipplus.com/api/provider/sta?d='.request()->host().'&i='.request()->ip().'&o='.PHP_OS.'&php_v='.PHP_VERSION.'&c='.time();
        CommonKit::request($baseUrl,[],[]);
        $this->assign([
            'version' => $this->version,
        ]);
        return $this->fetch();
    }

    private function sql_split($sql, $r_tablepre = '', $s_tablepre = 'cv_')
    {
        global $tablepre;
        $r_tablepre = $r_tablepre ? $r_tablepre : $tablepre;
        if ($r_tablepre != $s_tablepre) $sql = str_replace($s_tablepre, $r_tablepre, $sql);
        $sql = str_replace("\r", "\n", $sql);
        $ret = array();
        $num = 0;
        $queriesarray = explode(";\n", trim($sql));
        unset($sql);
        foreach ($queriesarray as $query) {
            $ret[$num] = '';
            $queries = explode("\n", trim($query));
            $queries = array_filter($queries);
            foreach ($queries as $query) {
                $str1 = substr($query, 0, 1);
                if ($str1 != '#' && $str1 != '-') $ret[$num] .= $query;
            }
            $num++;
        }
        return $ret;
    }

}