<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

require '../../../config/db.php';

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

$data = json_decode(file_get_contents("php://input"), true);

if (empty($data)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'No data provided.']);
    exit();
}

try {
    // TODO: Add Admin Authentication Check here

    $sql = "INSERT INTO site_config (setting_key, setting_value) VALUES (:key, :value) ON DUPLICATE KEY UPDATE setting_value = :value";
    $stmt = $pdo->prepare($sql);

    foreach ($data as $key => $value) {
        // Whitelist allowed keys for security
        $allowedKeys = ['diamond_exchange_rate', 'min_withdrawal_diamonds', 'withdrawal_fee_percent', 'sales_fee_percent', 'chat_unlock_fee_percent', 'subscription_fee_percent', 'chest_item_fee_percent', 'marketplace_category_fees', 'site_name', 'maintenance_mode'];
        
        if (in_array($key, $allowedKeys)) {
            $stmt->bindValue(':key', $key);
            $stmt->bindValue(':value', $value);
            $stmt->execute();
        }
    }

    echo json_encode(['success' => true, 'message' => 'Settings saved successfully.']);

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
?>
