<?php

namespace APP\program\admin\user;

use APP\DI;
use APP\program\admin\Setting;
use APP\program\CuteDB;
use Exception;
use LyApi\tools\Config;
use Medoo\Medoo;

/**
 * LyApi - Admin System
 * 用户数据库操作
 */

class Database
{

    public static $dbPath = LyApi . '/data/database/user/';

    // 初始化插件数据库
    public static function initDB($uid)
    {

        $db_connect = Setting::dbConnect();

        if (!$db_connect->has("users", ['id' => $uid])) {
            return false;
        }

        $name = $db_connect->get('users', 'username', ['id' => $uid]);

        if (!is_dir(self::$dbPath . $name)) {
            try {
                return mkdir(self::$dbPath . $name);
            } catch (Exception $e) {
                return false;
            }
        }

        return true;
    }

    // 打开 CuteDB
    public static function openDB($name,$user = null){
        $db = new CuteDB();

        if($user == null){
            $user = $_SESSION['username'];
        }else{
            $db_connect = Setting::dbConnect();
            if($db_connect->has('users',['id' => $user])){
                $user = $db_connect->get('users','username',['id' => $user]);
            }else{
                return null;
            }
        }

        $db->open(self::$dbPath . $user . '/' . $name);
        return $db;
    }

}
