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

$action = $_GET['action'] ?? '';

try {

  if ($action === 'get') {
    $id = (int)($_GET['id'] ?? 0);
    $stmt = $pdo->prepare("SELECT * FROM bol_value_presets WHERE id=?");
    $stmt->execute([$id]);
    $p = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$p) { echo json_encode(['ok'=>false,'error'=>'Not found']); exit; }

    // pretty JSON for textarea
    $pretty = json_encode(json_decode($p['values_json'], true), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
    echo json_encode(['ok'=>true, 'preset'=>[
      'id'=>$p['id'],
      'name'=>$p['name'],
      'description'=>$p['description'],
      'values_json_pretty'=>$pretty ?: '{}'
    ]]);
    exit;
  }

  if ($action === 'create') {
    $stmt = $pdo->prepare("INSERT INTO bol_value_presets (name, description, values_json) VALUES ('New Preset', '', '{}')");
    $stmt->execute();
    echo json_encode(['ok'=>true, 'id'=>$pdo->lastInsertId()]);
    exit;
  }

  if ($action === 'save') {
    $data = json_decode(file_get_contents('php://input'), true);
    $id = (int)($data['id'] ?? 0);

    $name = trim($data['name'] ?? '');
    if ($name === '') $name = 'Preset';

    $desc = trim($data['description'] ?? '');

    // ensure valid JSON object
    $values = $data['values_json'] ?? [];
    if (!is_array($values)) $values = [];

    $valuesJson = json_encode($values, JSON_UNESCAPED_SLASHES);

    $stmt = $pdo->prepare("
      UPDATE bol_value_presets
      SET name=?, description=?, values_json=?
      WHERE id=?
    ");
    $stmt->execute([$name, $desc, $valuesJson, $id]);

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

  if ($action === 'delete') {
    $data = json_decode(file_get_contents('php://input'), true);
    $id = (int)($data['id'] ?? 0);
    $stmt = $pdo->prepare("DELETE FROM bol_value_presets WHERE id=?");
    $stmt->execute([$id]);
    echo json_encode(['ok'=>true]);
    exit;
  }

  echo json_encode(['ok'=>false,'error'=>'Unknown action']);
} catch (Throwable $e) {
  http_response_code(500);
  echo json_encode(['ok'=>false,'error'=>$e->getMessage()]);
}
