<?php
namespace Core;

/**
 * 数据库连接（MySQL PDO 单例；文件路径模式）
 */
class Db
{
    private static $pdo = null;

    public static function driver(): string
    {
        return App::config('app.driver', 'file');
    }

    public static function pdo(): \PDO
    {
        if (self::$pdo === null) {
            $c = App::config('db.mysql');
            $dsn = "mysql:host={$c['host']};port={$c['port']};dbname={$c['dbname']};charset={$c['charset']}";
            self::$pdo = new \PDO($dsn, $c['user'], $c['pass'], [
                \PDO::ATTR_ERRMODE          => \PDO::ERRMODE_EXCEPTION,
                \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
                \PDO::ATTR_EMULATE_PREPARES   => false,
            ]);
        }
        return self::$pdo;
    }

    public static function fileDir(): string
    {
        $dir = App::config('db.file.dir');
        if (!is_dir($dir)) mkdir($dir, 0755, true);
        return $dir;
    }

    public static function query(string $sql, array $params = []): \PDOStatement
    {
        $st = self::pdo()->prepare($sql);
        $st->execute($params);
        return $st;
    }
}
