<?php
// save_market_config.php
session_start();
require_once(__DIR__ . '/../config/settings.php');

// Validación de seguridad (Igual que en tu index.php)
$masterAdmin = $db_settings['admin_user'] ?? 'Admin';
if (!isset($_SESSION['logged_in']) || $_SESSION['user_id'] !== $masterAdmin) {
    echo json_encode(['status' => 'error', 'message' => 'No autorizado']);
    exit;
}

try {
    $dsn = "dblib:host={$db_settings['host']};dbname={$db_settings['name']};charset=UTF8";
    $pdo = new PDO($dsn, $db_settings['user'], $db_settings['pass']);

    // Lista de campos a guardar
    $configs = [
        'market_active' => $_POST['market_active'],
        'market_max_stats' => $_POST['market_max_stats'],
        'market_full_val' => $_POST['market_full_val'],
        'market_reset_val' => $_POST['market_reset_val'],
        'market_min_resets' => $_POST['market_min_resets'],
        'market_tax' => $_POST['market_tax']
    ];

    foreach ($configs as $key => $value) {
        $stmt = $pdo->prepare("IF EXISTS (SELECT 1 FROM Web_Settings WHERE setting_key = ?) 
                               UPDATE Web_Settings SET setting_value = ? WHERE setting_key = ?
                               ELSE 
                               INSERT INTO Web_Settings (setting_key, setting_value) VALUES (?, ?)");
        $stmt->execute([$key, $value, $key, $key, $value]);
    }

    echo json_encode(['status' => 'success']);
} catch (Exception $e) {
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}