<?php
declare(strict_types=1);
namespace app\index\controller;
use aphp\core\Jump;

class Install
{
    use Jump;

    public function index()
    {
        if ($this->isPost()) {
            $db = db();
            if ($db->hasTable('user')) {
                file_put_contents(ROOT_PATH.'/backup/install.lock', date('Y-m-d H:i:s'));
                $this->error('检测已安装，可进入后台还原。');
            }
            $path = input('post.path', '', 'clear_html');
            if (empty($path)) {
                $this->error('请输入备份文件夹名');
            }
            if (!is_dir(ROOT_PATH . '/backup/'.$path)) {
                $this->error('备份文件夹不存在');
            }
            $glob = @glob(ROOT_PATH . '/backup/'.$path.'/*.sql');
            sort($glob);
            foreach ($glob as $file) {
                $data = file_get_contents($file);
                $data = mb_convert_encoding($data, 'UTF-8', 'auto');
                $sqlList = explode('-- <fen> --', $data);
                if (count($sqlList) > 1) {
                    array_pop($sqlList);
                }
                foreach ($sqlList as $sql) {
                    $db->execute($sql);
                }
                usleep(100000);
            }
            file_put_contents(ROOT_PATH.'/backup/install.lock', date('Y-m-d H:i:s'));
            $this->success('安装成功!默认管理员：admin 密码：admin(或1)', 'index/index');
        }
        return view();
    }
}