<?php
define('TUSHARE_API_TOKEN', '1bc28452ba375da19320cda845ae6307578964cb3ae473d0dc702aea');

function get_db_config() {
    return [
        'host' => 'localhost',
        'username' => 'myquant',
        'password' => '_H(lU1_fF*9baRTp',
        'database' => 'myquant',
        'charset' => 'utf8mb4'
    ];
}

function get_mysqli_connection() {
    $db_config = get_db_config();
    $mysqli = new mysqli(
        $db_config['host'],
        $db_config['username'],
        $db_config['password'],
        $db_config['database']
    );

    if ($mysqli->connect_error) {
        die("Connection failed: " . $mysqli->connect_error);
    }

    $mysqli->set_charset($db_config['charset']);
    return $mysqli;
}

/**
 * 参数化查询，防止SQL注入。返回mysqli_result或false。
 * @param mysqli $mysqli
 * @param string $sql 带 ? 占位符的SQL
 * @param array $params 参数值数组
 * @return \mysqli_result|false
 */
function db_query($mysqli, $sql, $params = []) {
    $stmt = $mysqli->prepare($sql);
    if (!$stmt) return false;
    if ($params) {
        $types = str_repeat('s', count($params));
        $stmt->bind_param($types, ...$params);
    }
    $stmt->execute();
    $result = $stmt->get_result();
    $stmt->close();
    return $result;
}

/**
 * 统一JSON响应格式
 * @param mixed $data 响应数据
 * @param string $status ok|error
 * @param string $message 错误信息
 */
function jsonResponse($data = null, $status = 'ok', $message = '') {
    $response = ['status' => $status];
    if ($data !== null) $response['data'] = $data;
    if ($message) $response['message'] = $message;
    echo json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    exit();
}