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

$fields = $pdo->query("
  SELECT id, label
  FROM bol_fields
  WHERE field_type = 'preset'
  ORDER BY label
")->fetchAll(PDO::FETCH_ASSOC);

include '../includes/header.php';
include '../includes/sidebar.php';
?>

<div class="container-fluid">
  <h3>Preset Manager</h3>
  <p class="text-muted">Presets are grouped by field. Each field can have unlimited preset values.</p>

  <?php foreach ($fields as $f): ?>
    <div class="card mb-3 shadow-sm">
      <div class="card-header d-flex justify-content-between align-items-center">
        <strong><?= htmlspecialchars((string)$f['label']) ?></strong>
        <button type="button" class="btn btn-sm btn-outline-success" onclick="addPreset(<?= (int)$f['id'] ?>)">+ Add preset</button>
      </div>
      <div class="card-body">
        <?php
          $stmt = $pdo->prepare("
            SELECT id, name
            FROM bol_value_presets
            WHERE field_id = ?
            ORDER BY name
          ");
          $stmt->execute([$f['id']]);
          $presets = $stmt->fetchAll(PDO::FETCH_ASSOC);
        ?>

        <?php if (!$presets): ?>
          <div class="text-muted">No presets yet for this field.</div>
        <?php else: ?>
          <?php foreach ($presets as $p): ?>
            <div class="d-flex gap-2 mb-2 align-items-center">
              <input class="form-control form-control-sm"
                     value="<?= htmlspecialchars((string)$p['name']) ?>"
                     onchange="updatePreset(<?= (int)$f['id'] ?>, <?= (int)$p['id'] ?>, this.value)">
              <button type="button" class="btn btn-sm btn-danger"
                      onclick="deletePreset(<?= (int)$f['id'] ?>, <?= (int)$p['id'] ?>)">Delete</button>
            </div>
          <?php endforeach; ?>
        <?php endif; ?>
      </div>
    </div>
  <?php endforeach; ?>
</div>

<script>
function addPreset(fieldId){
  const v = prompt('New preset value:');
  if(!v || !v.trim()) return;

  fetch('/smproduce/pages/preset_save.php', {
    method:'POST',
    headers:{'Content-Type':'application/json'},
    body: JSON.stringify({ action:'add', field_id: fieldId, value: v.trim() })
  })
  .then(r=>r.json())
  .then(j=>{
    if(j.ok) location.reload();
    else alert(j.error || 'Error');
  });
}

function updatePreset(fieldId, presetId, value){
  if(!value || !value.trim()) return;

  fetch('/smproduce/pages/preset_save.php', {
    method:'POST',
    headers:{'Content-Type':'application/json'},
    body: JSON.stringify({ action:'update', field_id: fieldId, preset_id: presetId, value: value.trim() })
  })
  .then(r=>r.json())
  .then(j=>{
    if(!j.ok) alert(j.error || 'Error updating preset');
  });
}

function deletePreset(fieldId, presetId){
  if(!confirm('Delete this preset?')) return;

  fetch('/smproduce/pages/preset_save.php', {
    method:'POST',
    headers:{'Content-Type':'application/json'},
    body: JSON.stringify({ action:'delete', field_id: fieldId, preset_id: presetId })
  })
  .then(r=>r.json())
  .then(j=>{
    if(j.ok) location.reload();
    else alert(j.error || 'Error deleting preset');
  });
}
</script>

<?php include '../includes/footer.php'; ?>
