<?php
/**
 * Motor de Guardado Universal - Master Core
 * Guarda cualquier configuración en la tabla Web_Settings
 */
header('Content-Type: application/json');
require_once(__DIR__ . '/../config/settings.php');

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

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        foreach ($_POST as $key => $value) {
            // Sanitizamos la llave para evitar problemas de seguridad
            $clean_key = preg_replace('/[^a-zA-Z0-0_]/', '', $key);
            
            // SQL compatible con SQL Server (T-SQL)
            $sql = "IF EXISTS (SELECT 1 FROM Web_Settings WHERE setting_key = :key)
                    BEGIN
                        UPDATE Web_Settings SET setting_value = :val WHERE setting_key = :key
                    END
                    ELSE
                    BEGIN
                        INSERT INTO Web_Settings (setting_key, setting_value) VALUES (:key, :val)
                    END";
            
            $stmt = $pdo->prepare($sql);
            $stmt->execute([
                'key' => $clean_key,
                'val' => $value
            ]);
        }
        echo json_encode(['status' => 'success', 'message' => 'Configuración sincronizada']);
    }
} catch (Exception $e) {
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}