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

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

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

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

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

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

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

if (!isset($values[$index])) {
    echo json_encode(['ok'=>false,'error'=>'Index not found']);
    exit;
}

$values[$index] = $value;

/* save */
$stmt = $pdo->prepare("
UPDATE bol_value_presets
SET values_json=?
WHERE field_id=?
");

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

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