<?php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';
$user = requireRole([1, 5]); // Admin, HR

try {
$db   = getDB();

// updates arrives as JSON string from URLSearchParams
$rawUpdates = $_POST['updates'] ?? '';
$updates = is_string($rawUpdates) ? (json_decode($rawUpdates, true) ?: []) : (is_array($rawUpdates) ? $rawUpdates : []);
if (empty($updates)) {
    // Single update
    $key = post('key', '');
    $val = post('value', '');
    if ($key) $updates = [['key' => $key, 'value' => $val]];
}

if (empty($updates)) apiError('No updates provided.', 422);

foreach ($updates as $upd) {
    $k = trim($upd['key'] ?? '');
    $v = $upd['value'] ?? '';
    if (!$k) continue;
    $db->prepare("INSERT INTO settings (setting_key, setting_value) VALUES (?,?) ON DUPLICATE KEY UPDATE setting_value=?")
       ->execute([$k, $v, $v]);
}
apiSuccess([], 'Settings saved.');
} catch (PDOException $e) {
    apiError('Database error: ' . $e->getMessage(), 500);
} catch (Exception $e) {
    apiError('Error: ' . $e->getMessage(), 500);
}