<?php
require_once __DIR__ . '/../config/config.php';

// 连接到数据库
try {
    $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    if ($conn->connect_error) {
        die("数据库连接失败: " . $conn->connect_error);
    }
    
    // 设置字符集
    $conn->set_charset("utf8mb4");
    
    // 检查admin表是否存在，不存在则创建
    $check_table = $conn->query("SHOW TABLES LIKE 'admin'");
    if (!$check_table || $check_table->num_rows == 0) {
        $create_table = "CREATE TABLE IF NOT EXISTS admin (
            id INT AUTO_INCREMENT PRIMARY KEY,
            username VARCHAR(50) NOT NULL,
            password VARCHAR(255) NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;";
        
        if ($conn->query($create_table) === TRUE) {
            echo "admin表创建成功<br>";
        } else {
            die("创建admin表失败: " . $conn->error);
        }
    }
    
    // 设置新密码
    $new_username = 'admin';
    $new_password = 'admin123'; // 设置您想要的新密码
    $hashed_password = hash('sha256', $new_password . SALT);
    
    // 检查用户是否存在
    $check_user = $conn->query("SELECT id FROM admin WHERE username = '$new_username'");
    
    if ($check_user && $check_user->num_rows > 0) {
        // 更新现有用户
        $sql = "UPDATE admin SET password = '$hashed_password' WHERE username = '$new_username'";
        $message = "管理员密码已重置<br>";
    } else {
        // 创建新用户
        $sql = "INSERT INTO admin (username, password) VALUES ('$new_username', '$hashed_password')";
        $message = "新管理员账户已创建<br>";
    }
    
    if ($conn->query($sql) === TRUE) {
        echo $message;
        echo "用户名: " . $new_username . "<br>";
        echo "新密码: " . $new_password . "<br>";
        echo "<a href='login.php'>返回登录页面</a>";
    } else {
        echo "操作失败: " . $conn->error;
    }
    
    $conn->close();
    
} catch (Exception $e) {
    die("发生错误: " . $e->getMessage());
}
?>
