<?php
/**
 * POST /api/admin/settings_update.php
 * Body (JSON): { updates: { setting_key: value, ... } }
 * Admin-only. Only known keys are accepted, to prevent this becoming an
 * arbitrary key-value injection point.
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/response.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/settings.php';

only_post_allowed();
require_login();
require_role(['admin']);

const ALLOWED_SETTING_KEYS = [
    'points_per_dollar_spent', 'points_per_new_listing',
    'market_country', 'market_city',
    'oauth_google_client_id', 'oauth_google_client_secret',
    'oauth_facebook_app_id', 'oauth_facebook_app_secret',
    'smtp_host', 'smtp_port', 'smtp_username', 'smtp_password',
    'smtp_encryption', 'smtp_from_email', 'smtp_from_name',
    'adsense_client_id', 'business_trial_days', 'subscriptions_enabled',
];

$input = get_json_input();
$updates = $input['updates'] ?? [];

if (!is_array($updates) || !$updates) {
    send_error('At least one setting update is required.', 422);
}

foreach ($updates as $key => $value) {
    if (!in_array($key, ALLOWED_SETTING_KEYS, true)) {
        send_error("Unknown setting key: $key", 422);
    }
}

if (isset($updates['points_per_dollar_spent']) && (!is_numeric($updates['points_per_dollar_spent']) || $updates['points_per_dollar_spent'] < 0)) {
    send_error('points_per_dollar_spent must be a non-negative number.', 422);
}
if (isset($updates['points_per_new_listing']) && (!is_numeric($updates['points_per_new_listing']) || $updates['points_per_new_listing'] < 0)) {
    send_error('points_per_new_listing must be a non-negative number.', 422);
}

$pdo = Database::connect();
foreach ($updates as $key => $value) {
    set_setting($pdo, $key, trim((string) $value));
}

send_json(true, 'Settings updated.');
