<?php
// api/save_settings.php
session_start();
require_once '../includes/config.php';
require_once '../includes/auth.php';
requireAdmin();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: ../index.php?tab=settings');
    exit;
}

$existing = loadConfig();
$fields = [
    'ft_host','ft_port','ft_user','ft_pass','ft_api_key',
    'ar_client_id','ar_client_secret','ar_site_id','ar_region',
    'sl_host','sl_grpc_port','sl_token',
    'alert_email','thresh_cpu','thresh_ap','thresh_latency',
    'ship_name','admin_user','admin_pass','anthropic_key',
];

$newData = $existing;
foreach ($fields as $f) {
    if (isset($_POST[$f]) && $_POST[$f] !== '') {
        $newData[$f] = trim($_POST[$f]);
    }
}

if (saveConfigFile($newData)) {
    writeLog('Pengaturan disimpan oleh admin');
    header('Location: ../index.php?tab=settings&saved=1');
} else {
    header('Location: ../index.php?tab=settings&error=save_failed');
}
exit;
