<?php
/**
 * 炎酷CMS - 数据库核心（PDO）
 * 所有 SQL 使用预处理语句，表名通过 DB_PREFIX 常量拼接。
 */
defined('YKCMS') or exit('Access Denied');

// 加载安装时生成的配置文件
$YK_CFG_FILE = dirname(__DIR__) . '/data/config.php';
if (!is_file($YK_CFG_FILE)) {
    // 未安装，跳转安装程序
    if (is_file(dirname(__DIR__) . '/public/install.php')) {
        header('Location: install.php');
    }
    exit('System not installed.');
}
$YK_CFG = require $YK_CFG_FILE;

define('DB_PREFIX', $YK_CFG['db_prefix']);
define('PWD_SALT', $YK_CFG['pwd_salt']);

/**
 * 获取 PDO 单例连接
 * @return PDO
 */
function db() {
    static $pdo = null;
    global $YK_CFG;
    if ($pdo === null) {
        $dsn = 'mysql:host=' . $YK_CFG['db_host'] . ';port=' . $YK_CFG['db_port']
             . ';dbname=' . $YK_CFG['db_name'] . ';charset=utf8mb4';
        $pdo = new PDO($dsn, $YK_CFG['db_user'], $YK_CFG['db_pass'], array(
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES   => false,
        ));
    }
    return $pdo;
}

/**
 * 查询多行
 * @return array
 */
function db_all($sql, $args = array()) {
    $stmt = db()->prepare($sql);
    $stmt->execute($args);
    return $stmt->fetchAll();
}

/**
 * 查询单行
 * @return array|null
 */
function db_one($sql, $args = array()) {
    $stmt = db()->prepare($sql);
    $stmt->execute($args);
    $row = $stmt->fetch();
    return $row === false ? null : $row;
}

/**
 * 查询单个值
 */
function db_val($sql, $args = array()) {
    $stmt = db()->prepare($sql);
    $stmt->execute($args);
    return $stmt->fetchColumn();
}

/**
 * 执行写操作，返回影响行数
 */
function db_exec($sql, $args = array()) {
    $stmt = db()->prepare($sql);
    $stmt->execute($args);
    return $stmt->rowCount();
}

/**
 * 插入并返回自增 ID
 */
function db_insert($sql, $args = array()) {
    $stmt = db()->prepare($sql);
    $stmt->execute($args);
    return db()->lastInsertId();
}
