<?php
// +----------------------------------------------------------------------
// | Minishop [ Easy to handle for Micro businesses ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016 http://www.qasl.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: tangtanglove <dai_hang_love@126.com> <http://www.ixiaoquan.com>
// +----------------------------------------------------------------------

namespace app\install\controller;

use think\Controller;
use think\Request;
use think\Db;

/**
 * 安装模块
 * @author  tangtnglove <dai_hang_love@126.com>
 */
class Index extends Controller
{
    /**
     * 初始化方法
     * @author tangtanglove
     */
    protected function _initialize()
    {
        // 检测程序安装
        if (is_file(APP_PATH . 'install/data/install.lock')) {
            echo '程序已经安装！重新安装请删除application/install/data/install.lock文件!';
			echo '<br>';
			$upurl=URL('install/update/index');
			echo '<a href="'.$upurl.'">更新版本</a>';			
            exit();
        }
    }

    /**
     * 安装模块默认方法
     * 前提:安装协议
     * @author tangtanglove
     */
    public function index()
    {
    	      
        session('step',0);
        session('error',false);
        return $this->fetch();
    }

    /**
     * 第一步：环境检测
     * @author vaey
     * @return [type] [description]
     */
    public function step1()
    {
        if(session('step')!=0 && session('step')!=2){
            $this->redirect('index/index');
        }
        session('error',false);
        //环境检测
        $env = check_env();
        //函数检测
        $fun = check_fun();
        //文件目录检测
        $dirfile = check_dirfile();

        $this->assign('env',$env);
        $this->assign('fun',$fun);
        $this->assign('dirfile',$dirfile);
        

        session('step',1);
        return $this->fetch();
    }

    /**
     * 第二步：创建数据库
     * @author vaey
     * @return [type] [description]
     */
    public function step2($db=null,$admin=null)
    {
        //判断请求类型
      
        if(request()->isPost()){
            //检测管理员信息
            if(!is_array($admin) || empty($admin[0]) || empty($admin[1]) || empty($admin[3])){
                return $this->error('请填写完整管理员信息!');
            } else if($admin[2] != $admin[3]){
                return $this->error('确认密码和密码不一致');
            } elseif(!filter_var($admin[0], FILTER_VALIDATE_EMAIL)){
                return $this->error('请填写正确的管理员邮箱');
            } else {
                $info = array();
                list($info['email'],$info['name'], $info['password'], $info['repassword'])= $admin;
                //缓存管理员信息
                session('admin_info', $info);
            }
            //检测数据库配置
            if(!is_array($db) || empty($db[0]) ||  empty($db[1]) || empty($db[2]) || empty($db[3])){
                return $this->error('请填写完整的数据库配置');
            } else {
                $DB = array();
                list($DB['type'], $DB['hostname'], $DB['database'], $DB['username'], $DB['password'],
                     $DB['hostport'], $DB['prefix']) = $db;

                //缓存数据库配置
                session('db_config', $DB);

                //创建数据库
                $dbname = $DB['database'];
                unset($DB['database']);
                $db  = Db::connect($DB);
				$isdb=$db->execute('SELECT * FROM information_schema.schemata WHERE schema_name="'.$dbname.'"');
				//return $this->success('OK',url('index/step3',['access'=>'success']));
                
                if($isdb){
                	return $this->success('OK',url('index/step3',['access'=>'success']));
                    
                }else{
                	$sql = "CREATE DATABASE IF NOT EXISTS `{$dbname}` DEFAULT CHARACTER SET utf8";
                    if(!$db->execute($sql)){
                        return $this->error($db->getError());
                        exit();
                    }else{
                        return $this->success('OK',url('index/step3',['access'=>'success']));
                    }
                }
            }

            //跳转到数据库安装页面
            // $this->redirect('index/step3',['access'=>'success']);
        }else{
            if(session('error')){
                return $this->error('环境检测未通过，请调整环境后重试');
            }
            $step = session('step');
            if($step !=1 && $step != 2){
                return $this->redirect('index/step1');
            }
            session('step',2);
            return $this->fetch();
        }
    } 

    /**
     * 第三步：安装数据表，创建配置文件
     * @author vaey
     * @return [type] [description]
     */
    public function step3()
    {
        $access = input('access');
        if($access!='success'){
            return $this->redirect('index/step2');
        }
        if(session('step')!=2){
            return $this->redirect('index/step2');
        }
        session('step',3);
        echo $this->fetch();
        
        $dbconfig = session('db_config');
        $db = Db::connect($dbconfig); 
        $prefix = $dbconfig['prefix'];		
        //创建数据表
        create_tables($db, $dbconfig['prefix']);        
		//写入配置文件
        write_config($dbconfig);        	
		//写入扩展配置        
		copy_config(config('upfile'));
        //注册创始人信息
        register_administrator($db, $dbconfig['prefix']);	
        
    }

    /**
     * 第四步：安装完成
     * @author vaey
     * @return [type] [description]
     */
    public function step4()
    {
        if(session('step')!=3){
           return $this->redirect('index/step2');
        }
        //写入安装锁文件
        file_put_contents(APP_PATH.'install/data/install.lock', 'lock');
        session('step',null);
        session('error',null);
        $host = $_SERVER["HTTP_HOST"]; //主机
        $name = $_SERVER['SCRIPT_NAME'];//地址
        $admin_path = str_replace("install.php", "admin.php", $name);
        $index_path = str_replace("install.php", "index.php", $name);
        $admin_url = "http://".$host.$admin_path;
        $index_url = "http://".$host.$index_path;
        $this->assign('admin_url',$admin_url);
        $this->assign('index_url',$index_url);
        return $this->fetch();
    }


}
