<?php
if (session_status() === PHP_SESSION_NONE) { session_start(); }
require_once '../includes/sidebar.php';
require_once '../includes/header.php';
?>

<style>
.te-wrap{display:flex;gap:16px}
.left{flex:1}
.right{width:420px}

.canvas{position:relative;border:1px solid #e5e7eb;border-radius:10px;overflow:hidden;background:#fff}
.canvas img{width:100%;display:block;pointer-events:none;user-select:none}
.overlay{position:absolute;inset:0}

.field{
  position:absolute;border:2px dashed rgba(29,78,216,.7);
  background:rgba(29,78,216,.12);
  border-radius:8px;touch-action:none;
}
.field .name{font-size:12px;padding:6px;pointer-events:none;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.handle{position:absolute;background:#1d4ed8}
.handle.w{width:10px;height:100%;right:-5px;top:0;cursor:ew-resize}
.handle.h{height:10px;width:100%;bottom:-5px;left:0;cursor:ns-resize}

.field.active{border-color:#1d4ed8;background:rgba(29,78,216,.18)}

.panel{border:1px solid #e5e7eb;border-radius:10px;background:#fff;padding:12px}
.small{font-size:12px;color:#6b7280}
.rowgap{display:flex;gap:8px}
</style>

<div class="content-wrapper">
<div class="container-fluid">

<div class="d-flex justify-content-between align-items-center mb-3">
  <h1 class="h4 mb-0">PDF Template Editor</h1>
  <div class="d-flex gap-2">
    <select id="templateSelect" class="form-select form-select-sm" style="width:320px"></select>
    <button class="btn btn-sm btn-outline-primary" onclick="loadTemplate()">Load</button>
    <button class="btn btn-sm btn-success" onclick="saveTemplate()">Save (new version)</button>
  </div>
</div>

<div class="te-wrap">
  <div class="left">
    <div class="canvas" id="canvas">
      <img id="pageImg" src="" alt="PDF page">
      <div class="overlay" id="overlay"></div>
    </div>
    <div class="small mt-2">
      Add Field → clicca e trascina. Resize: barra destra (W) / barra sotto (H). Coordinate salvate in percentuale.
    </div>
  </div>

  <div class="right">
    <div class="panel mb-3">
      <div class="rowgap">
        <button class="btn btn-sm btn-primary" onclick="addField()">+ Add field</button>
        <button class="btn btn-sm btn-outline-danger" onclick="deleteField()">Delete</button>
      </div>
      <div class="small mt-2">Seleziona un campo cliccandolo nell’overlay.</div>
    </div>

    <div class="panel">
      <strong>Field properties</strong>
      <div class="mt-2">
        <label class="small">ID (unico)</label>
        <input id="f_id" class="form-control form-control-sm" oninput="updateProp('id', this.value)">
      </div>
      <div class="mt-2">
        <label class="small">Label</label>
        <input id="f_label" class="form-control form-control-sm" oninput="updateProp('label', this.value)">
      </div>
      <div class="mt-2">
        <label class="small">Type</label>
        <select id="f_type" class="form-select form-select-sm" onchange="updateType(this.value)">
          <option value="text">text</option>
          <option value="select">select</option>
          <option value="date">date</option>
          <option value="number">number</option>
          <option value="signature">signature</option>
        </select>
      </div>

      <div class="mt-2" id="presetBox" style="display:none">
        <label class="small">Presets (max 6, uno per riga)</label>
        <textarea id="f_presets" class="form-control form-control-sm" rows="6" oninput="updatePresets(this.value)"></textarea>
      </div>

      <hr>
      <div class="small" id="coordInfo"></div>
    </div>
  </div>
</div>

</div>
</div>

<script>
const templateSelect = document.getElementById('templateSelect');
const pageImg = document.getElementById('pageImg');
const overlay = document.getElementById('overlay');
const canvas = document.getElementById('canvas');

let currentTemplate = null;   // {id, pdf_path, fields[]}
let fields = [];
let activeIndex = -1;

function pct(v){ return (v*100)+'%'; }
function clamp(v,min,max){ return Math.max(min, Math.min(max, v)); }

async function initTemplates(){
  const r = await fetch('/smproduce/api/templates_list.php');
  const j = await r.json();
  templateSelect.innerHTML = '';
  j.templates.forEach(t=>{
    const opt = new Option(`${t.code} — ${t.name}`, t.id);
    templateSelect.add(opt);
  });
}
initTemplates();

async function loadTemplate(){
  const id = templateSelect.value;
  const r = await fetch('/smproduce/api/template_get.php?id=' + id);
  const j = await r.json();
  if (!j.ok) { alert(j.message || 'Load failed'); return; }

  currentTemplate = j.template;
  fields = (currentTemplate.fields || []).map(f=>({...f}));

  // carica immagine pagina 1 (puoi estendere alle multi-page)
  pageImg.src = '/smproduce/utils/pdf_page_png.php?pdf=' + encodeURIComponent(currentTemplate.pdf_path) + '&page=1';

  activeIndex = -1;
  render();
  clearProps();
}

function render(){
  overlay.innerHTML = '';
  fields.forEach((f, idx)=>{
    const el = document.createElement('div');
    el.className = 'field' + (idx===activeIndex ? ' active':'');
    el.dataset.idx = idx;

    el.style.left = pct(f.x);
    el.style.top = pct(f.y);
    el.style.width = pct(f.w);
    el.style.height = pct(f.h);

    el.innerHTML = `
      <div class="name">${escapeHtml(f.label || f.id || 'field')}</div>
      <div class="handle w"></div>
      <div class="handle h"></div>
    `;

    el.addEventListener('pointerdown', (e)=> onPointerDown(e, idx, el));
    overlay.appendChild(el);
  });

  updateCoordInfo();
}

function onPointerDown(e, idx, el){
  setActive(idx);

  const rect = overlay.getBoundingClientRect();
  const f = fields[idx];

  const start = {
    pointerId: e.pointerId,
    mx: e.clientX, my: e.clientY,
    x: f.x, y: f.y, w: f.w, h: f.h,
    mode: e.target.classList.contains('w') ? 'w'
        : e.target.classList.contains('h') ? 'h'
        : 'move',
    el
  };

  el.setPointerCapture(e.pointerId);

  const move = (ev)=>{
    if (ev.pointerId !== start.pointerId) return;
    const dx = (ev.clientX - start.mx) / rect.width;
    const dy = (ev.clientY - start.my) / rect.height;

    if (start.mode === 'move') {
      f.x = clamp(start.x + dx, 0, 1);
      f.y = clamp(start.y + dy, 0, 1);
      start.el.style.left = pct(f.x);
      start.el.style.top = pct(f.y);
    } else if (start.mode === 'w') {
      f.w = clamp(start.w + dx, 0.01, 1);
      start.el.style.width = pct(f.w);
    } else if (start.mode === 'h') {
      f.h = clamp(start.h + dy, 0.01, 1);
      start.el.style.height = pct(f.h);
    }
    updateCoordInfo();
  };

  const stop = ()=>{
    try { el.releasePointerCapture(start.pointerId); } catch {}
    el.removeEventListener('pointermove', move);
    el.removeEventListener('pointerup', stop);
    el.removeEventListener('pointercancel', stop);
  };

  el.addEventListener('pointermove', move);
  el.addEventListener('pointerup', stop);
  el.addEventListener('pointercancel', stop);
}

function setActive(idx){
  activeIndex = idx;
  render();
  fillProps();
}

function addField(){
  fields.push({
    id: 'field_' + (fields.length + 1),
    label: 'New field',
    type: 'text',
    x: 0.1, y: 0.1, w: 0.25, h: 0.05
  });
  setActive(fields.length - 1);
}

function deleteField(){
  if (activeIndex < 0) return;
  fields.splice(activeIndex, 1);
  activeIndex = -1;
  render();
  clearProps();
}

function fillProps(){
  if (activeIndex < 0) return clearProps();
  const f = fields[activeIndex];

  document.getElementById('f_id').value = f.id || '';
  document.getElementById('f_label').value = f.label || '';
  document.getElementById('f_type').value = f.type || 'text';

  const presetBox = document.getElementById('presetBox');
  const ta = document.getElementById('f_presets');
  if (f.type === 'select') {
    presetBox.style.display = 'block';
    ta.value = (f.presets || []).join("\n");
  } else {
    presetBox.style.display = 'none';
    ta.value = '';
  }
  updateCoordInfo();
}

function clearProps(){
  document.getElementById('f_id').value = '';
  document.getElementById('f_label').value = '';
  document.getElementById('f_type').value = 'text';
  document.getElementById('presetBox').style.display = 'none';
  document.getElementById('f_presets').value = '';
  updateCoordInfo();
}

function updateProp(key, val){
  if (activeIndex < 0) return;
  fields[activeIndex][key] = val;
  render();
}

function updateType(val){
  if (activeIndex < 0) return;
  fields[activeIndex].type = val;
  if (val !== 'select') delete fields[activeIndex].presets;
  fillProps();
  render();
}

function updatePresets(text){
  if (activeIndex < 0) return;
  const arr = text.split('\n').map(s=>s.trim()).filter(Boolean).slice(0,6);
  fields[activeIndex].presets = arr;
}

function updateCoordInfo(){
  const el = document.getElementById('coordInfo');
  if (activeIndex < 0) { el.textContent = 'No field selected.'; return; }
  const f = fields[activeIndex];
  el.textContent = `x=${f.x.toFixed(4)} y=${f.y.toFixed(4)} w=${f.w.toFixed(4)} h=${f.h.toFixed(4)}`;
}

async function saveTemplate(){
  if (!currentTemplate) { alert('Load a template first'); return; }

  // validate IDs non vuoti/unici
  const ids = fields.map(f=>f.id).filter(Boolean);
  const dup = ids.find((v,i)=> ids.indexOf(v) !== i);
  if (dup) { alert('Duplicate field id: ' + dup); return; }
  if (ids.length !== fields.length) { alert('Every field must have an ID'); return; }

  const r = await fetch('/smproduce/api/template_save.php', {
    method:'POST',
    headers:{'Content-Type':'application/json'},
    body: JSON.stringify({
      template_id: currentTemplate.id,
      fields: fields,
      created_by: '<?php echo isset($_SESSION["user"]) ? addslashes($_SESSION["user"]) : ""; ?>'
    })
  });

  const j = await r.json().catch(()=> ({}));
  if (!r.ok || !j.ok) { alert(j.message || 'Save failed'); return; }
  alert('Saved. New version: ' + j.version);
}

function escapeHtml(s){
  return String(s).replace(/[&<>"']/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'}[m]));
}
</script>

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