<?php
$host = 'localhost';
$user = '名';
$pass = '密码';
$db = '名';

// 开启错误报告
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

$conn = mysqli_connect($host, $user, $pass, $db);
mysqli_set_charset($conn, 'utf8mb4');

if (!$conn) {
    die("连接失败: " . mysqli_connect_error());
}

// 安全过滤函数
function safe($conn, $str) {
    return mysqli_real_escape_string($conn, trim($str));
}

// 检查表是否存在，不存在则创建
$check_table = mysqli_query($conn, "SHOW TABLES LIKE 'categories'");
if (mysqli_num_rows($check_table) == 0) {
    // 创建分类表
    mysqli_query($conn, "CREATE TABLE IF NOT EXISTS categories (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(100) NOT NULL UNIQUE,
        sort_order INT DEFAULT 0,
        create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    
    // 插入默认分类
    $default_categories = ['破解修改', '科学上网', '娱乐游戏', '实用工具', '系统美化'];
    foreach ($default_categories as $cat) {
        $cat_safe = mysqli_real_escape_string($conn, $cat);
        mysqli_query($conn, "INSERT IGNORE INTO categories (name) VALUES ('$cat_safe')");
    }
}

// 检查apps表字段
$result = mysqli_query($conn, "SHOW COLUMNS FROM apps LIKE 'download_count'");
if (mysqli_num_rows($result) == 0) {
    mysqli_query($conn, "ALTER TABLE apps ADD COLUMN download_count INT DEFAULT 0");
}

$result = mysqli_query($conn, "SHOW COLUMNS FROM apps LIKE 'created_at'");
if (mysqli_num_rows($result) == 0) {
    mysqli_query($conn, "ALTER TABLE apps ADD COLUMN created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP");
}

?>