<?php
session_start();
require_once __DIR__ . '/../includes/db.php';

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

$fieldId = (int)($data['field_id'] ?? 0);
$value   = trim($data['value'] ?? '');

if ($fieldId <= 0 || $value === '') {
    echo json_encode(['ok'=>false,'error'=>'Invalid data']);
    exit;
}

/* get field label */
$f = $pdo->prepare("SELECT label FROM bol_fields WHERE id=?");
$f->execute([$fieldId]);
$field = $f->fetch(PDO::FETCH_ASSOC);

if (!$field) {
    echo json_encode(['ok'=>false,'error'=>'Field not found']);
    exit;
}

/* load existing presets */
$stmt = $pdo->prepare("
    SELECT values_json
    FROM bol_value_presets
    WHERE field_id=?
");
$stmt->execute([$fieldId]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);

$values = [];
if ($row && $row['values_json']) {
    $values = json_decode($row['values_json'], true) ?: [];
}

/* avoid duplicates */
if (!in_array($value, $values, true)) {
    $values[] = $value;
}

/* insert or update */
$stmt = $pdo->prepare("
INSERT INTO bol_value_presets (field_id, name, values_json)
VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE
  values_json = VALUES(values_json),
  name = VALUES(name)
");

$stmt->execute([
    $fieldId,
    $field['label'],
    json_encode($values, JSON_UNESCAPED_UNICODE)
]);

echo json_encode(['ok'=>true]);
