<?php
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/../includes/header.php';

$id = $_GET['id'] ?? null;

/* carica campi */
$fields = $pdo->query("
  SELECT code, label, field_type
  FROM bol_fields
  WHERE template_id = 1
  ORDER BY sort_order
")->fetchAll(PDO::FETCH_ASSOC);

/* carica preset se edit */
$preset = null;
$values = [];
if($id){
  $stmt = $pdo->prepare("
    SELECT *
    FROM bol_value_presets
    WHERE id = ?
  ");
  $stmt->execute([$id]);
  $preset = $stmt->fetch(PDO::FETCH_ASSOC);
  if(!$preset) die('Preset not found');
  $values = json_decode($preset['values_json'], true) ?: [];
}
?>

<h4><?= $id ? 'Edit' : 'New' ?> Preset</h4>

<form id="presetForm">

<div class="mb-3">
  <label>Name</label>
  <input name="name" class="form-control"
         value="<?= htmlspecialchars($preset['name'] ?? '') ?>" required>
</div>

<div class="mb-3">
  <label>Description</label>
  <textarea name="description" class="form-control"><?= htmlspecialchars($preset['description'] ?? '') ?></textarea>
</div>

<div class="mb-3">
  <label>Preset type</label>
  <select id="presetType" class="form-control">
    <option value="bol">BOL preset (multiple fields)</option>
    <option value="field">Field preset (single field)</option>
  </select>
</div>

<hr>

<div id="fieldsEditor">

<?php foreach($fields as $f):
  $v = $values[$f['code']] ?? '';
?>
<div class="mb-2 field-row" data-code="<?= $f['code'] ?>">
  <label><?= htmlspecialchars($f['label']) ?> (<?= $f['code'] ?>)</label>

<?php if($f['field_type'] === 'date'): ?>
  <input type="date" class="form-control field-input"
         value="<?= htmlspecialchars($v) ?>">
<?php else: ?>
  <input type="text" class="form-control field-input"
         value="<?= htmlspecialchars($v) ?>">
<?php endif; ?>

</div>
<?php endforeach; ?>

</div>

<button class="btn btn-primary mt-3">Save Preset</button>
<a href="bol_presets.php" class="btn btn-secondary mt-3">Back</a>

</form>

<script>
const presetType = document.getElementById('presetType');
const rows = document.querySelectorAll('.field-row');

/* auto-detect type on load */
(function(){
  let filled = 0;
  rows.forEach(r=>{
    if(r.querySelector('.field-input').value.trim()) filled++;
  });
  presetType.value = filled <= 1 ? 'field' : 'bol';
  toggleType();
})();

presetType.onchange = toggleType;

function toggleType(){
  if(presetType.value === 'field'){
    let firstFilled = false;
    rows.forEach(r=>{
      const input = r.querySelector('.field-input');
      if(input.value.trim()){
        if(!firstFilled){
          firstFilled = true;
          r.style.display = '';
        } else {
          r.style.display = 'none';
          input.value = '';
        }
      } else {
        r.style.display = firstFilled ? 'none' : '';
      }
    });
  } else {
    rows.forEach(r=>r.style.display='');
  }
}

presetForm.onsubmit = e=>{
  e.preventDefault();

  const values = {};
  rows.forEach(r=>{
    const v = r.querySelector('.field-input').value.trim();
    if(v){
      values[r.dataset.code] = v;
    }
  });

  fetch('save_bol_preset.php',{
    method:'POST',
    headers:{'Content-Type':'application/json'},
    body:JSON.stringify({
      id:<?= json_encode($id) ?>,
      name:presetForm.name.value,
      description:presetForm.description.value,
      values:values
    })
  }).then(()=>{
    location.href='bol_presets.php';
  });
};
</script>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>
