<?php
session_start();
require_once 'config.php';
require_once 'functions.php';
requireLogin();
$user = getConnectedUser($pdo);
requireAdmin($user);

header('Content-Type: application/json');

$changes = json_decode(file_get_contents('php://input'), true);
if (!$changes || !is_array($changes)) {
    echo json_encode(['error' => 'Données invalides']); exit;
}

// Sauvegarder dans admin_config avec clés nommées: droit_<feat_key>_<tier>
try {
    foreach ($changes as $featKey => $tiers) {
        // Valider que c'est un feat_key alphanumérique safe
        if (!preg_match('/^[a-z0-9_]+$/', $featKey)) continue;
        foreach ($tiers as $tier => $val) {
            if (!in_array($tier, ['free','premium','premplus','admin'])) continue;
            $key = 'droit_' . $featKey . '_' . $tier;
            $v   = $val ? '1' : '0';
            $pdo->prepare("INSERT INTO admin_config (config_key, config_value) VALUES (?,?) ON DUPLICATE KEY UPDATE config_value=?")
                ->execute([$key, $v, $v]);
        }
    }
    echo json_encode(['ok' => true, 'saved' => count($changes)]);
} catch (Exception $e) {
    echo json_encode(['error' => $e->getMessage()]);
}
