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

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

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

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

/* Load existing values */
$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;
}

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

/* 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)
");

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

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