<?php
declare(strict_types=1);
require_once __DIR__ . '/_bootstrap.php';

ensure_schema();
$pdo = db();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $input = read_json();
  $category = $input['category'] ?? 'general';
  $data = $input['data'] ?? [];
  if (!is_array($data)) {
    json_response(['success' => false, 'error' => 'Invalid data']);
  }
  $stmt = $pdo->prepare("
    INSERT INTO settings (category, name, value)
    VALUES (?, ?, ?)
    ON DUPLICATE KEY UPDATE value = VALUES(value), updated_at = CURRENT_TIMESTAMP
  ");
  foreach ($data as $key => $value) {
    $stmt->execute([$category, $key, (string)$value]);
  }
  json_response(['success' => true]);
}

$category = $_GET['category'] ?? 'general';
$stmt = $pdo->prepare("SELECT name, value FROM settings WHERE category = ?");
$stmt->execute([$category]);
$settings = $stmt->fetchAll();
$out = [];
foreach ($settings as $row) {
  $out[$row['name']] = $row['value'];
}
json_response(['settings' => $out]);
