<?php

namespace install\models;

use Yii;
use yii\base\Model;

class InstallForm extends Model
{
    public $dbhost;
    public $dbusername;
    public $dbpassword;
    public $dbname;
    public $dbpre;
    public $dbport;


    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            // name, email, subject and body are required
            [['dbhost', 'dbusername','dbpassword', 'dbname','dbpre','dbport'], 'required'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'dbhost' => '数据库主机',
            'dbusername' => '数据库用户名',
            'dbpassword' => '数据库密码',
            'dbname' => '数据库名称',
            'dbpre' => '数据表前缀',
            'dbport' => '数据库端口',
        ];
    }
    public function check_conn(){
        try{
            $conn=new \mysqli($this->dbhost,$this->dbusername,$this->dbpassword,$this->dbname,$this->dbport);  
            if(!$conn){
                return array('status'=>0,'msg'=>'数据库连接失败');
            } 
            return array('status'=>1); 
        }catch(\Exception $e){
            return array('status'=>0,'msg'=>$e->getMessage());
        }
    }
    public function writeDbinfo(){
        $content = "<?php\nreturn [\n";
        $content .= "'components' => [\n";
        $content .= "'db' => [\n";
        $content .= "'class' => 'yii\db\Connection',\n";
        $content .= "'dsn' => 'mysql:host=".$this->dbhost.";dbname=".$this->dbname."',\n";
        $content .= "'username' => '".$this->dbusername."',\n";
        $content .= "'password' => '".$this->dbpassword."',\n";
        $content .= "'charset' => 'utf8',\n";
        $content .= "'tablePrefix'=>'".$this->dbpre."',\n";
        $content .= "],\n";
        $content .= "],\n";
        $content .= "];";
        file_put_contents(COMMON_CONF_PATH.'db.php',$content);
        return true;
    }
}
