<?php
require '../includes/db.php';
include 'includes/header.php'; 
include 'includes/sidebar.php';

// 🔐 (Optional) Add admin session check here
// if (!isset($_SESSION['admin'])) { exit("Unauthorized"); }

$success = "";

// ==========================
// ✅ UPDATE SETTINGS
// ==========================
if ($_POST) {

    foreach ($_POST as $key => $value) {

        $key   = mysqli_real_escape_string($conn, $key);
        $value = mysqli_real_escape_string($conn, $value);

        mysqli_query($conn, "
            INSERT INTO system_settings (setting_key, setting_value)
            VALUES ('$key', '$value')
            ON DUPLICATE KEY UPDATE setting_value='$value'
        ");
    }

    $success = "✅ Settings updated successfully.";
}

// ==========================
// 🔍 LOAD SETTINGS
// ==========================
$res = mysqli_query($conn, "SELECT * FROM system_settings");
$settings = [];

while ($row = mysqli_fetch_assoc($res)) {
    $settings[$row['setting_key']] = $row['setting_value'];
}
?>

    <style>

        .box {
            background: #1e293b;
            padding: 25px;
            border-radius: 12px;
            max-width: 600px;
            margin: auto;
        }
        input {
            width: 100%;
            padding: 10px;
            margin: 8px 0;
            border-radius: 6px;
            border: none;
        }
        button {
            background: #4f46e5;
            color: white;
            padding: 10px;
            border: none;
            border-radius: 6px;
            width: 100%;
        }
        .success {
            background: #16a34a;
            padding: 10px;
            border-radius: 6px;
            margin-bottom: 10px;
        }
        label {
            font-size: 14px;
            color: #94a3b8;
        }
    </style>
</head>
<body>

<div class="box">

    <h2>⚙️ System Settings</h2>

    <?php if ($success): ?>
        <div class="success"><?php echo $success; ?></div>
    <?php endif; ?>

    <form method="POST">

        <!-- DEFAULT AMOUNT -->
        <label>Default BTC Amount</label>
        <input type="text" name="default_amount_btc"
            value="<?php echo $settings['default_amount_btc'] ?? ''; ?>">

        <!-- ACCOUNT FEE -->
        <label>Account Fee (BTC)</label>
        <input type="text" name="account_fee_btc"
            value="<?php echo $settings['account_fee_btc'] ?? ''; ?>">

        <!-- SITE URL -->
        <label>Site URL</label>
        <input type="text" name="site_url"
            value="<?php echo $settings['site_url'] ?? ''; ?>">

        <!-- BTC RATE -->
        <label>BTC Rate (USD)</label>
        <input type="text" name="btc_rate"
            value="<?php echo $settings['btc_rate'] ?? '65000'; ?>">

        <button type="submit">💾 Save Settings</button>

    </form>

</div>
