<?php
if (session_status() === PHP_SESSION_NONE) session_start();
require_once __DIR__ . '/../includes/db.php';

$data = json_decode(file_get_contents('php://input'), true);

$presetName = trim($data['preset_name'] ?? '');
$fieldKey   = trim($data['field_key'] ?? '');
$value      = (string)($data['value'] ?? '');

if ($presetName === '' || $fieldKey === '') {
  http_response_code(400);
  echo 'Bad Request';
  exit;
}

/*
  IMPORTANT:
  We keep presets in the SAME table used by /pages/bol_presets.php (bol_field_presets).
  To avoid duplicates for the same preset_name+field_key, we delete then insert.
*/
try {
  $pdo->beginTransaction();

  $del = $pdo->prepare("DELETE FROM bol_field_presets WHERE preset_name = ? AND field_key = ?");
  $del->execute([$presetName, $fieldKey]);

  $ins = $pdo->prepare("INSERT INTO bol_field_presets (preset_name, field_key, value) VALUES (?, ?, ?)");
  $ins->execute([$presetName, $fieldKey, $value]);

  $pdo->commit();
  echo 'OK';
} catch (Throwable $e) {
  if ($pdo->inTransaction()) $pdo->rollBack();
  http_response_code(500);
  echo 'DB Error';
}
