<?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>

<div class="mb-2 d-flex gap-2 align-items-center">
  <input id="copies" type="number" min="1" value="1"
         class="form-control form-control-sm" 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 document</button>
</div>

<div class="border p-3 bg-light">
  <div style="position:relative;width:794px;height:1123px;
              background:url('/smproduce/templates/BILL_OF_LADING_BG.png') no-repeat;
              background-size:contain;background-color:#fff;border:1px solid #ccc">

<?php foreach($fields as $f):
  $val = $values[$f['id']] ?? '';
?>
<div 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;
">
<?php if($f['field_type']==='preset'): ?>
  <div class="input-group input-group-sm">
    <select class="form-select"
            onchange="saveValue(<?= $f['id'] ?>,this.value)">
      <option></option>
      <?php foreach($presetsByField[$f['id']]??[] as $p): ?>
        <option <?= $val===$p['name']?'selected':'' ?>>
          <?= htmlspecialchars($p['name']) ?>
        </option>
      <?php endforeach; ?>
    </select>
    <a class="btn btn-outline-secondary"
       target="_blank"
       href="/smproduce/pages/bol_presets.php">+</a>
  </div>
<?php else: ?>
  <input class="form-control form-control-sm"
         value="<?= htmlspecialchars($val) ?>"
         onchange="saveValue(<?= $f['id'] ?>,this.value)">
<?php endif; ?>
</div>
<?php endforeach; ?>

  </div>
</div>

<script>
const bolId = <?= json_encode($bolId) ?>;

function saveValue(fid,val){
  fetch('/smproduce/pages/save_bol_value.php',{
    method:'POST',
    headers:{'Content-Type':'application/json'},
    body:JSON.stringify({bol_id:bolId,field_id:fid,value:val})
  });
}

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

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