<?php
require_once "auth.php";
require_once '../db/config.php';
$db = db();

$admin_id = $_SESSION['admin_id'] ?? 1; // Fallback to 1 if not set, but auth.php should ensure it's set

$message = "";
$error = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['settings'])) {
        foreach ($_POST['settings'] as $name => $value) {
            $stmt = $db->prepare("INSERT INTO settings (name, value) VALUES (?, ?) ON DUPLICATE KEY UPDATE value = ?");
            $stmt->execute([$name, $value, $value]);
        }
        $message = "系统设置已成功更新。";
    }

    if (isset($_POST['change_password'])) {
        $old_pass = $_POST['old_password'];
        $new_pass = $_POST['new_password'];
        $confirm_pass = $_POST['confirm_password'];

        $stmt = $db->prepare("SELECT password FROM admins WHERE id = ?");
        $stmt->execute([$admin_id]);
        $admin = $stmt->fetch();

        if ($new_pass !== $confirm_pass) {
            $error = "两次输入的新密码不一致。";
        } elseif (!password_verify($old_pass, $admin['password'])) {
            $error = "旧密码错误。";
        } else {
            $hashed = password_hash($new_pass, PASSWORD_DEFAULT);
            $stmt = $db->prepare("UPDATE admins SET password = ? WHERE id = ?");
            $stmt->execute([$hashed, $admin_id]);
            $message = "管理密码已成功修改。";
        }
    }

    if (isset($_FILES['logo']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK) {
        $ext = pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION);
        $filename = 'logo_' . time() . '.' . $ext;
        $target = '../assets/images/' . $filename;
        
        if (!is_dir('../assets/images')) {
            mkdir('../assets/images', 0775, true);
        }

        if (move_uploaded_file($_FILES['logo']['tmp_name'], $target)) {
            $logo_url = 'assets/images/' . $filename;
            $stmt = $db->prepare("INSERT INTO settings (name, value) VALUES ('site_logo', ?) ON DUPLICATE KEY UPDATE value = ?");
            $stmt->execute([$logo_url, $logo_url]);
            $message = "LOGO 已成功上传。";
        } else {
            $error = "LOGO 上传失败。";
        }
    }
}

$settings_res = $db->query("SELECT * FROM settings")->fetchAll();
$settings = [];
foreach($settings_res as $s) $settings[$s['name']] = $s['value'];

$unread_msgs = $db->query("SELECT COUNT(*) FROM messages WHERE sender = 'user' AND is_read = 0")->fetchColumn();
$pending_orders = $db->query("SELECT COUNT(*) FROM fiat_orders WHERE status IN ('matching', 'submitting')")->fetchColumn();
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>系统设置 - 管理后台</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        :root { --primary: #f0b90b; --bg: #ffffff; --text: #1e2329; --border: #eaecef; --card-bg: #f9fafb; }
        body { background: #f4f6f9; color: var(--text); font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; margin: 0; }
        .admin-layout { display: flex; min-height: 100vh; }
        .sidebar { width: 250px; background: #ffffff; border-right: 1px solid var(--border); padding: 1.5rem; }
        .main-content { flex: 1; padding: 2rem; background: #ffffff; }
        .menu-item { padding: 12px 15px; color: #474d57; text-decoration: none; display: flex; align-items: center; gap: 12px; border-radius: 8px; margin-bottom: 8px; transition: 0.2s; }
        .menu-item:hover, .menu-item.active { background: #f5f5f5; color: var(--primary); font-weight: bold; }
        .badge { background: #f6465d; color: white; border-radius: 10px; padding: 2px 8px; font-size: 0.7rem; margin-left: auto; }
        
        .card { background: white; border-radius: 12px; border: 1px solid var(--border); padding: 25px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); margin-bottom: 2rem; }
        .form-group { margin-bottom: 20px; }
        .form-group label { display: block; margin-bottom: 8px; font-weight: 600; color: #474d57; }
        input[type="text"], input[type="number"], input[type="password"], select, textarea { width: 100%; padding: 12px; border: 1px solid var(--border); border-radius: 8px; font-size: 1rem; outline: none; box-sizing: border-box; }
        input:focus, textarea:focus { border-color: var(--primary); }
        .btn { padding: 12px 30px; border-radius: 8px; font-weight: bold; cursor: pointer; border: none; transition: 0.2s; }
        .btn-primary { background: var(--primary); color: #000; }
        .btn-primary:hover { opacity: 0.9; }
        
        .logo-preview { max-width: 200px; max-height: 100px; margin-bottom: 15px; border: 1px solid var(--border); padding: 10px; border-radius: 8px; background: #f0f0f0; }
    </style>
</head>
<body>
<div class="admin-layout">
    <div class="sidebar">
        <h2 style="color: var(--primary); margin-bottom: 2rem;">NovaEx Admin</h2>
        <a href="index.php" class="menu-item"><i class="fas fa-home"></i> 仪表盘</a>
        <a href="users.php" class="menu-item"><i class="fas fa-users"></i> 用户管理</a>
        <a href="agents.php" class="menu-item"><i class="fas fa-user-shield"></i> 代理管理</a>
        <a href="kyc.php" class="menu-item"><i class="fas fa-id-card"></i> KYC 审核</a>
        <a href="chat.php" class="menu-item">
            <i class="fas fa-comments"></i> 客服管理
            <?php if($unread_msgs > 0 || $pending_orders > 0): ?><span class="badge"><?php echo ($unread_msgs + $pending_orders); ?></span><?php endif; ?>
        </a>
        <a href="options_orders.php" class="menu-item"><i class="fas fa-clock"></i> 秒合约</a>
        <a href="spot_orders.php" class="menu-item"><i class="fas fa-exchange-alt"></i> 现货交易</a>
        <a href="futures_orders.php" class="menu-item"><i class="fas fa-file-contract"></i> 合约交易</a>
        <a href="orders.php" class="menu-item"><i class="fas fa-wallet"></i> 充值记录</a>
        <a href="withdrawals.php" class="menu-item"><i class="fas fa-hand-holding-usd"></i> 提现记录</a>
        <a href="settings.php" class="menu-item active"><i class="fas fa-cog"></i> 系统设置</a>
        <a href="logout.php" class="menu-item"><i class="fas fa-sign-out-alt"></i> 退出登录</a>
    </div>

    <div class="main-content">
        <h1 style="margin-bottom: 30px;">系统设置</h1>
        
        <?php if($message): ?>
            <div style="background: #e6fcf5; color: #00c087; padding: 15px; border-radius: 8px; margin-bottom: 20px; border: 1px solid #00c087;"><i class="fas fa-check-circle"></i> <?php echo $message; ?></div>
        <?php endif; ?>
        <?php if($error): ?>
            <div style="background: #fff5f5; color: #f6465d; padding: 15px; border-radius: 8px; margin-bottom: 20px; border: 1px solid #f6465d;"><i class="fas fa-exclamation-circle"></i> <?php echo $error; ?></div>
        <?php endif; ?>

        <div class="card">
            <h3>修改登录密码</h3>
            <form method="POST">
                <input type="hidden" name="change_password" value="1">
                <div class="form-group">
                    <label>当前密码</label>
                    <input type="password" name="old_password" required placeholder="请输入当前管理员密码">
                </div>
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                    <div class="form-group">
                        <label>新密码</label>
                        <input type="password" name="new_password" required placeholder="请输入新密码">
                    </div>
                    <div class="form-group">
                        <label>确认新密码</label>
                        <input type="password" name="confirm_password" required placeholder="请再次输入新密码">
                    </div>
                </div>
                <button type="submit" class="btn btn-primary">更新管理密码</button>
            </form>
        </div>

        <div class="card">
            <h3>站点配置 (LOGO / 图标)</h3>
            <form method="POST" enctype="multipart/form-data">
                <div class="form-group">
                    <label>当前 LOGO</label>
                    <?php if(isset($settings['site_logo'])): ?>
                        <img src="../<?php echo $settings['site_logo']; ?>" class="logo-preview" alt="Logo">
                    <?php else: ?>
                        <div class="logo-preview" style="display: flex; align-items: center; justify-content: center; color: #ccc;">未设置 LOGO</div>
                    <?php endif; ?>
                    <input type="file" name="logo" accept="image/*">
                    <p style="font-size: 0.8rem; color: #707a8a; margin-top: 5px;">建议尺寸: 200x60 像素。上传后将同步更新前端 LOGO 和网站图标。</p>
                </div>
                <button type="submit" class="btn btn-primary">上传并更新 LOGO</button>
            </form>
        </div>

        <form method="POST">
            <div class="card">
                <h3>1. 交易与胜率控制</h3>
                <div class="form-group">
                    <label>全局胜率控制 (%)</label>
                    <input type="number" name="settings[win_rate]" value="<?php echo $settings['win_rate'] ?? 70; ?>" min="0" max="100">
                </div>
            </div>

            <div class="card">
                <h3>2. 价格操纵控制</h3>
                <div class="form-group">
                    <label>价格控制模式</label>
                    <select name="settings[price_control]">
                        <option value="0" <?php echo ($settings['price_control'] ?? '0') == '0' ? 'selected' : ''; ?>>实时行情 (API 自动同步)</option>
                        <option value="1" <?php echo ($settings['price_control'] ?? '0') == '1' ? 'selected' : ''; ?>>强制控价 (所有用户看到指定价格)</option>
                    </select>
                </div>
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                    <div class="form-group">
                        <label>BTC 指定价格 ($)</label>
                        <input type="number" name="settings[manual_btc_price]" value="<?php echo $settings['manual_btc_price'] ?? 0; ?>" step="0.01">
                    </div>
                    <div class="form-group">
                        <label>BTC 插针价格 ($)</label>
                        <input type="number" name="settings[pin_btc_price]" value="<?php echo $settings['pin_btc_price'] ?? 0; ?>" step="0.01">
                    </div>
                </div>
            </div>

            <div class="card">
                <h3>3. 客服与公告</h3>
                <div class="form-group">
                    <label>客服自动问候语</label>
                    <textarea name="settings[chat_greeting]" rows="3"><?php echo $settings['chat_greeting'] ?? '您好！欢迎咨询 NovaEx 官方客服。'; ?></textarea>
                </div>
                <div class="form-group">
                    <label>系统公告内容 (简体中文)</label>
                    <input type="text" name="settings[announcement_zh]" value="<?php echo $settings['announcement_zh'] ?? ''; ?>" placeholder="首页顶部公告...">
                </div>
            </div>

            <div style="text-align: right;">
                <button type="submit" class="btn btn-primary" style="font-size: 1.1rem; padding: 15px 60px;">保存所有系统设置</button>
            </div>
        </form>
    </div>
</div>
</body>
</html>