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

$templateId = 1;

$stmt = $pdo->prepare("
  SELECT *
  FROM bol_fields
  WHERE template_id = ?
  ORDER BY sort_order, id
");
$stmt->execute([$templateId]);
$fields = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

<style>
#editor-layout{
  display:flex;
  gap:16px;
  height:calc(100vh - 160px);
}

#template-canvas-wrap{
  flex:1;
  overflow:auto;
  background:#f1f5f9;
  border:1px solid #d1d5db;
  padding:32px;
  display:flex;
  justify-content:center;
}

#template-canvas{
  position:relative;
  width:794px;
  height:1123px;
  background:url('/smproduce/templates/BILL_OF_LADING_BG.png') no-repeat;
  background-size:contain;
  background-position:top center;
  background-color:#fff;
  transform-origin:top left;
  border:1px solid #e5e7eb;
}

/* FIELD */
.bol-field{
  position:absolute;
  border:1px dashed #2563eb;
  background:rgba(255,255,255,.85);
  padding:2px 4px;
  cursor:move;
  user-select:none;
  box-sizing:border-box;
}
.bol-field.active{ border:2px solid #1d4ed8; }

/* new field */
.bol-field-new{
  border:1px dashed rgba(220,38,38,.6);
  background:rgba(255,255,255,.35);
}

/* resize corner only */
.resize-handle{
  position:absolute;
  width:10px;
  height:10px;
  right:1px;
  bottom:1px;
  cursor:nwse-resize;
  background:rgba(29,78,216,.75);
  border-radius:2px;
}
.resize-handle::after{
  content:'';
  position:absolute;
  right:2px;
  bottom:2px;
  width:6px;
  height:6px;
  border-right:2px solid #fff;
  border-bottom:2px solid #fff;
}
.bol-field-new .resize-handle{opacity:0}
.bol-field-new:hover .resize-handle{opacity:1}

/* panel */
#field-panel{
  width:320px;
  min-width:320px;
  border:1px solid #e5e7eb;
  background:#fff;
  padding:12px;
  position:sticky;
  top:80px;
}

#editor-toolbar{
  display:flex;
  gap:8px;
  flex-wrap:wrap;
  align-items:center;
  margin-bottom:8px;
}
#zoom-indicator{
  margin-left:auto;
  font-size:12px;
  color:#374151;
}
</style>

<h4 class="mb-2">BOL Template Editor</h4>

<div id="editor-toolbar">
  <button id="addField" class="btn btn-sm btn-success">+ Add Field</button>
  <button id="deleteField" class="btn btn-sm btn-danger" disabled>Delete</button>
  <button id="duplicateField" class="btn btn-sm btn-secondary" disabled>Duplicate</button>

  <div class="vr mx-2"></div>

  <label class="form-check-label me-1">Snap</label>
  <!-- SNAP OFF DI DEFAULT -->
  <input type="checkbox" id="snapToggle" class="form-check-input">
  <input type="number" id="snapSize" value="2" min="1"
         class="form-control form-control-sm ms-1" style="width:60px"> mm

  <div class="vr mx-2"></div>

  <button id="fitWidth" class="btn btn-sm btn-outline-secondary">Fit</button>
  <button id="zoomReset" class="btn btn-sm btn-outline-secondary">100%</button>

  <span id="zoom-indicator">100%</span>
</div>

<div id="editor-layout">

  <!-- CANVAS -->
  <div id="template-canvas-wrap">
    <div id="template-canvas">
      <?php foreach($fields as $f): ?>
        <div class="bol-field"
          data-id="<?= (int)$f['id'] ?>"
          data-code="<?= htmlspecialchars($f['code']) ?>"
          data-type="<?= htmlspecialchars($f['field_type']) ?>"
          data-font="<?= htmlspecialchars($f['font_family'] ?? 'helvetica') ?>"
          data-size="<?= htmlspecialchars($f['font_size'] ?? '9') ?>"
          data-color="<?= htmlspecialchars($f['font_color'] ?? '#000000') ?>"
          data-align="<?= htmlspecialchars($f['align'] ?? 'L') ?>"
          data-multiline="<?= (int)($f['is_multiline'] ?? 0) ?>"
          style="
            left:<?= mm2px($f['x_mm']) ?>px;
            top:<?= mm2px($f['y_mm']) ?>px;
            width:<?= mm2px($f['width_mm']) ?>px;
            height:<?= mm2px($f['height_mm']) ?>px;
          ">
          <?= htmlspecialchars($f['label']) ?>
          <div class="resize-handle"></div>
        </div>
      <?php endforeach; ?>
    </div>
  </div>

  <!-- PANEL -->
  <div id="field-panel">
    <h6>Field Properties</h6>

    <label>Label</label>
    <input id="fp_label" class="form-control">

    <label class="mt-2">Code</label>
    <input id="fp_code" class="form-control">

    <label class="mt-2">Type</label>
    <select id="fp_type" class="form-control">
      <option value="text">Text</option>
      <option value="number">Number</option>
      <option value="date">Date</option>
      <option value="preset">Preset</option>
      <option value="checkbox">Checkbox</option>
    </select>

    <label class="mt-2">Font</label>
    <input id="fp_font" class="form-control">

    <label class="mt-2">Font Size</label>
    <input id="fp_size" type="number" step="0.5" class="form-control">

    <label class="mt-2">Color</label>
    <input id="fp_color" type="color" class="form-control">

    <label class="mt-2">Align</label>
    <select id="fp_align" class="form-control">
      <option value="L">Left</option>
      <option value="C">Center</option>
      <option value="R">Right</option>
    </select>

    <div class="form-check mt-2">
      <input type="checkbox" class="form-check-input" id="fp_multiline">
      <label class="form-check-label">Multiline</label>
    </div>
  </div>

</div>

<script src="/smproduce/assets/js/bol_template_editor_full.js?v=<?= time() ?>"></script>

<script>
/* ===== ZOOM ENGINE ===== */
let zoom = 1;
let autoFit = false;

const canvas = document.getElementById('template-canvas');
const wrap   = document.getElementById('template-canvas-wrap');
const zi     = document.getElementById('zoom-indicator');

function applyZoom(){
  canvas.style.transform = `scale(${zoom})`;
  zi.textContent = Math.round(zoom*100)+'%';
}

function fitCanvas(){
  zoom = wrap.clientWidth / 794;
  autoFit = true;
  applyZoom();
}

/* DEFAULT = 100% */
applyZoom();

zoomReset.onclick = () => {
  zoom = 1;
  autoFit = false;
  applyZoom();
};

fitWidth.onclick = () => fitCanvas();

/* CTRL + WHEEL */
wrap.addEventListener('wheel', e=>{
  if(!e.ctrlKey) return;
  e.preventDefault();
  zoom += (e.deltaY < 0 ? 0.05 : -0.05);
  zoom = Math.max(0.2, Math.min(3, zoom));
  autoFit = false;
  applyZoom();
},{passive:false});

/* DOUBLE CLICK */
canvas.addEventListener('dblclick', ()=>{
  autoFit
    ? (zoom=1, autoFit=false, applyZoom())
    : fitCanvas();
});
</script>

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