<?php
require_once __DIR__ . '/../includes/db.php';
$bolId = $_GET['id'] ?? null;
if (!$bolId) return;

/* TEMPLATE FIELDS */
$fields = $pdo->query("
SELECT * FROM bol_fields
WHERE template_id = 1
ORDER BY sort_order,id
")->fetchAll(PDO::FETCH_ASSOC);

/* VALUES */
$stmt = $pdo->prepare("SELECT field_id,value FROM bol_values WHERE bol_id=?");
$stmt->execute([$bolId]);
$values = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

/* PRESETS */
$presets = $pdo->query("
SELECT field_id,name
FROM bol_value_presets
ORDER BY name
")->fetchAll(PDO::FETCH_ASSOC);
$presetsByField=[];
foreach($presets as $p){ $presetsByField[$p['field_id']][]=$p; }

function mm2px($mm){ return $mm * 96 / 25.4; }
?>

<h4 class="mt-3">Bill of Lading – Editor</h4>

<!-- TOOLBAR -->
<div class="mb-2 d-flex gap-2 align-items-center">
  <button class="btn btn-sm btn-outline-secondary" onclick="zoomOut()">−</button>
  <button class="btn btn-sm btn-outline-secondary" onclick="zoomIn()">+</button>
  <button class="btn btn-sm btn-outline-secondary" onclick="zoomReset()">100%</button>
  <button class="btn btn-sm btn-outline-secondary" onclick="zoomFit()">Fit</button>

  <input id="copies" type="number" min="1" value="1"
         class="form-control form-control-sm ms-3" style="width:80px">

  <button class="btn btn-sm btn-success" onclick="printPDF()">Print PDF</button>

  <button class="btn btn-sm btn-outline-danger ms-auto"
          onclick="resetDocument()">Reset</button>
</div>

<div class="d-flex gap-3">

<!-- CANVAS -->
<div class="border bg-light p-3" style="overflow:auto;flex:1">
  <div id="canvas"
       style="
         position:relative;
         width:794px;height:1123px;
         background:url('/smproduce/templates/BILL_OF_LADING_BG.png') no-repeat;
         background-size:contain;
         background-color:#fff;
         transform-origin:top left;
         border:1px solid #ccc
       ">

<?php foreach($fields as $f):
  $val = $values[$f['id']] ?? '';
?>
<div class="bol-field"
     data-id="<?= $f['id'] ?>"
     data-type="<?= $f['field_type'] ?>"
     data-value="<?= htmlspecialchars($val,ENT_QUOTES) ?>"
     onclick="selectField(this)"
     style="
       position:absolute;
       left:<?= mm2px($f['x_mm']) ?>px;
       top:<?= mm2px($f['y_mm']) ?>px;
       width:<?= mm2px($f['width_mm']) ?>px;
       height:<?= mm2px($f['height_mm']) ?>px;
       border:1px dashed rgba(0,0,0,.25);
       background:rgba(255,255,255,.85);
       padding:2px;
       cursor:pointer;
     ">
  <?= htmlspecialchars($val) ?>
</div>
<?php endforeach; ?>

  </div>
</div>

<!-- RIGHT EDITOR -->
<div style="width:320px;border:1px solid #ddd;padding:12px;background:#fff">
  <h6>Field editor</h6>

  <label class="form-label">Value</label>
  <textarea id="fe_value" class="form-control mb-2"
            onchange="saveValue()"></textarea>

  <div id="presetBox" class="mb-2 d-none">
    <label class="form-label">Preset</label>
    <div class="input-group input-group-sm">
      <select id="fe_preset" class="form-select"
              onchange="applyPreset()"></select>
      <a class="btn btn-outline-secondary"
         target="_blank"
         href="/smproduce/pages/bol_presets.php">+</a>
    </div>
  </div>
</div>

</div>

<script>
const bolId = <?= json_encode($bolId) ?>;
let zoom = 1;
let activeField = null;

/* ZOOM */
function applyZoom(){
  document.getElementById('canvas').style.transform = `scale(${zoom})`;
}
function zoomIn(){ zoom += 0.1; applyZoom(); }
function zoomOut(){ zoom = Math.max(0.2, zoom - 0.1); applyZoom(); }
function zoomReset(){ zoom = 1; applyZoom(); }
function zoomFit(){
  const wrap = document.getElementById('canvas').parentElement;
  zoom = wrap.clientWidth / 794;
  applyZoom();
}
applyZoom();

/* SELECT FIELD */
function selectField(el){
  document.querySelectorAll('.bol-field').forEach(f=>f.style.outline='');
  el.style.outline = '2px solid #2563eb';
  activeField = el;

  fe_value.value = el.dataset.value;

  if(el.dataset.type === 'preset'){
    presetBox.classList.remove('d-none');
    fe_preset.innerHTML = '<option></option>';
<?php foreach($presetsByField as $fid=>$list): ?>
    if(<?= $fid ?> == el.dataset.id){
<?php foreach($list as $p): ?>
      fe_preset.innerHTML += `<option><?= htmlspecialchars($p['name']) ?></option>`;
<?php endforeach; ?>
    }
<?php endforeach; ?>
  } else {
    presetBox.classList.add('d-none');
  }
}

/* SAVE */
function saveValue(){
  if(!activeField) return;
  const v = fe_value.value;
  activeField.dataset.value = v;
  activeField.innerText = v;

  fetch('/smproduce/pages/save_bol_value.php',{
    method:'POST',
    headers:{'Content-Type':'application/json'},
    body:JSON.stringify({
      bol_id: bolId,
      field_id: activeField.dataset.id,
      value: v
    })
  });
}

/* PRESET */
function applyPreset(){
  fe_value.value = fe_preset.value;
  saveValue();
}

/* RESET */
function resetDocument(){
  if(!confirm('Reset document?')) return;
  fetch('/smproduce/pages/reset_bol_document.php',{
    method:'POST',
    headers:{'Content-Type':'application/json'},
    body:JSON.stringify({ bol_id: bolId })
  }).then(()=>location.reload());
}

/* PRINT */
function printPDF(){
  const c = document.getElementById('copies').value || 1;
  window.open(
    '/smproduce/pages/preview_bol_pdf.php?bol_id='+bolId+'&copies='+c,
    '_blank'
  );
}
</script>
