<?php
session_start();
require_once __DIR__ . '/../includes/db.php';
header('Content-Type: application/json');

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

$action   = $data['action'] ?? 'add';
$fieldId  = (int)($data['field_id'] ?? 0);
$name     = isset($data['value']) ? trim((string)$data['value']) : '';
$presetId = (int)($data['preset_id'] ?? 0);

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

try {
    if ($action === 'add') {
        if ($name === '') throw new Exception('Empty preset');
        $stmt = $pdo->prepare("INSERT INTO bol_value_presets (field_id, name) VALUES (?, ?)");
        $stmt->execute([$fieldId, $name]);
        echo json_encode(['ok'=>true]); exit;
    }

    if ($action === 'update') {
        if ($presetId <= 0) throw new Exception('Invalid preset_id');
        if ($name === '') throw new Exception('Empty preset');
        $stmt = $pdo->prepare("UPDATE bol_value_presets SET name=? WHERE id=?");
        $stmt->execute([$name, $presetId]);
        echo json_encode(['ok'=>true]); exit;
    }

    if ($action === 'delete') {
        if ($presetId <= 0) throw new Exception('Invalid preset_id');
        $stmt = $pdo->prepare("DELETE FROM bol_value_presets WHERE id=?");
        $stmt->execute([$presetId]);
        echo json_encode(['ok'=>true]); exit;
    }

    echo json_encode(['ok'=>false,'error'=>'Invalid action']);
} catch (Exception $e) {
    echo json_encode(['ok'=>false,'error'=>$e->getMessage()]);
}
