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

/*
  Visual Document Editor for Bill of Lading (single template_id = 1)
  - Uses the same PNG background as Templates
  - Field positions come from bol_fields (mm coordinates)
  - Values are stored in bol_values.value (HTML allowed)
*/

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

if ($bolId) {
    $stmt = $pdo->prepare("SELECT * FROM bol_documents WHERE id = ?");
    $stmt->execute([$bolId]);
    $document = $stmt->fetch();
    if (!$document) die('Document not found');
} else {
    // create a new draft document
    $bolId = sprintf(
        '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
        random_int(0,0xffff), random_int(0,0xffff),
        random_int(0,0xffff),
        random_int(0,0x0fff) | 0x4000,
        random_int(0,0x3fff) | 0x8000,
        random_int(0,0xffff),
        random_int(0,0xffff),
        random_int(0,0xffff)
    );

    $pdo->prepare("
        INSERT INTO bol_documents (id, template_id, status, copies, template_code, version_number)
        VALUES (?, 1, 'draft', 1, 'bill_of_lading', 1)
    ")->execute([$bolId]);

    $document = ['copies' => 1, 'status' => 'draft'];
}

/* fields (layout) */
$fields = $pdo->query("
    SELECT id, code, label, field_type, x_mm, y_mm, width_mm, height_mm, is_multiline
    FROM bol_fields
    WHERE template_id = 1
    ORDER BY sort_order
")->fetchAll();

/* values */
$values = [];
$stmt = $pdo->prepare("SELECT field_id, value FROM bol_values WHERE bol_id = ?");
$stmt->execute([$bolId]);
foreach ($stmt as $v) {
    $values[(int)$v['field_id']] = (string)$v['value'];
}

/* presets (set of values keyed by field code) */
$presets = $pdo->query("
    SELECT id, name
    FROM bol_value_presets
    ORDER BY name
")->fetchAll();

$templateBgUrl = '/smproduce/templates/BILL_OF_LADING_BG.png';
?>

<style>
#bolEditorWrap {
  display: grid;
  grid-template-columns: minmax(520px, 1fr) 360px;
  gap: 16px;
  align-items: start;
}
#bolCanvasShell{
  background:#fff;
  border:1px solid rgba(0,0,0,.12);
  border-radius:12px;
  padding:12px;
  overflow:auto;
}
#bolCanvas {
  position: relative;
  display: inline-block;
  line-height: 0;
}
#bolBg {
  display:block;
  max-width:none;
  user-select:none;
}
.bol-field {
  position:absolute;
  border:1px dashed rgba(13,110,253,.65);
  background: rgba(13,110,253,.06);
  padding:2px 4px;
  overflow:hidden;
  cursor: pointer;
  line-height: 1.15;
  font-size: 12px;
}
.bol-field[data-type="checkbox"]{
  display:flex;
  align-items:center;
  justify-content:center;
  font-weight:700;
  font-size:14px;
}
.bol-field.selected{
  border:2px solid #0d6efd;
  background: rgba(13,110,253,.12);
  box-shadow: 0 0 0 2px rgba(13,110,253,.15);
}
#editorPanel{
  background:#fff;
  border:1px solid rgba(0,0,0,.12);
  border-radius:12px;
  padding:12px;
  position: sticky;
  top: 12px;
}
.toolbar{
  display:flex;
  flex-wrap: wrap;
  gap:6px;
}
.toolbar button{
  padding:6px 8px;
  border:1px solid rgba(0,0,0,.15);
  background:#fff;
  border-radius:8px;
  font-size:12px;
}
.toolbar button:hover{ background:#f4f6f8; }
#wordEditor{
  border:1px solid rgba(0,0,0,.15);
  border-radius:10px;
  padding:10px;
  min-height: 160px;
  outline: none;
}
.small-muted{
  font-size: 12px;
  color: rgba(0,0,0,.62);
}
</style>

<div class="d-flex justify-content-between align-items-center mb-3">
  <div>
    <h4 class="mb-0">Bill of Lading – Document</h4>
    <div class="small-muted">Document ID: <span class="font-monospace"><?= htmlspecialchars($bolId) ?></span></div>
  </div>
  <div class="d-flex gap-2">
    <a href="/smproduce/pages/bill_of_lading.php" class="btn btn-outline-secondary btn-sm">Back to list</a>
    <a href="/smproduce/pages/generate_bol_pdf.php?id=<?= urlencode($bolId) ?>" class="btn btn-outline-primary btn-sm">Preview / Print PDF</a>
  </div>
</div>

<form id="bolSaveForm" method="post" action="/smproduce/pages/save_bol_document.php">
  <input type="hidden" name="bol_id" value="<?= htmlspecialchars($bolId) ?>">

  <div id="bolEditorWrap">
    <!-- Canvas -->
    <div id="bolCanvasShell">
      <div id="bolCanvas">
        <img id="bolBg" src="<?= htmlspecialchars($templateBgUrl) ?>" alt="BOL template">
        <?php foreach ($fields as $f): 
            $fid = (int)$f['id'];
            $htmlVal = $values[$fid] ?? '';
            // For checkbox, normalize to X or empty
            $displayVal = ($f['field_type'] === 'checkbox') ? (($htmlVal === '1' || $htmlVal === 'X') ? 'X' : '') : $htmlVal;
        ?>
          <div class="bol-field"
               data-field-id="<?= $fid ?>"
               data-code="<?= htmlspecialchars($f['code']) ?>"
               data-label="<?= htmlspecialchars($f['label']) ?>"
               data-type="<?= htmlspecialchars($f['field_type']) ?>"
               data-x-mm="<?= htmlspecialchars($f['x_mm']) ?>"
               data-y-mm="<?= htmlspecialchars($f['y_mm']) ?>"
               data-w-mm="<?= htmlspecialchars($f['width_mm']) ?>"
               data-h-mm="<?= htmlspecialchars($f['height_mm']) ?>"
               title="<?= htmlspecialchars($f['label']) ?>">
            <?= $displayVal ?>
          </div>
          <textarea name="fields[<?= $fid ?>]" id="fieldInput<?= $fid ?>" style="display:none;"><?= htmlspecialchars($htmlVal) ?></textarea>
        <?php endforeach; ?>
      </div>
    </div>

    <!-- Inspector -->
    <div id="editorPanel">
      <div class="mb-3">
        <label class="form-label">Field</label>
        <select id="fieldSelect" class="form-select">
          <option value="">— Select a field —</option>
          <?php foreach ($fields as $f): ?>
            <option value="<?= (int)$f['id'] ?>"><?= htmlspecialchars($f['label']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>

      <div class="mb-2 d-flex justify-content-between align-items-center">
        <div class="small-muted" id="fieldMeta">Select a field to edit.</div>
      </div>

      <div id="presetBlock" class="mb-3" style="display:none;">
        <label class="form-label">Preset</label>
        <select id="presetSelect" class="form-select">
          <option value="">— Select preset —</option>
          <?php foreach ($presets as $p): ?>
            <option value="<?= (int)$p['id'] ?>"><?= htmlspecialchars($p['name']) ?></option>
          <?php endforeach; ?>
          <option value="__new__">+ Add new preset…</option>
        </select>
        <div class="small-muted mt-2">
          Presets are sets of values for multiple fields. Creating a new preset will add it to the preset list; you can fill it in under “Presets”.
          <a href="/smproduce/pages/bol_presets.php" target="_blank">Open Presets</a>
        </div>
      </div>

      <div id="wordBlock">
        <div class="toolbar mb-2">
          <button type="button" data-cmd="bold"><b>B</b></button>
          <button type="button" data-cmd="italic"><i>I</i></button>
          <button type="button" data-cmd="underline"><u>U</u></button>
          <button type="button" data-cmd="strikeThrough"><s>S</s></button>
          <button type="button" data-cmd="insertUnorderedList">• List</button>
          <button type="button" data-cmd="insertOrderedList">1. List</button>
          <button type="button" data-cmd="justifyLeft">Left</button>
          <button type="button" data-cmd="justifyCenter">Center</button>
          <button type="button" data-cmd="justifyRight">Right</button>
          <button type="button" id="clearFmt">Clear</button>
        </div>
        <div id="wordEditor" contenteditable="true"></div>
        <div class="small-muted mt-2">
          Tip: click a field on the document to edit it here. Formatting is saved and will be rendered into the PDF.
        </div>
      </div>

      <hr>

      <div class="mb-3">
        <label class="form-label">Copies</label>
        <input type="number" class="form-control" name="copies" id="copiesInput" min="1" value="<?= (int)($document['copies'] ?? 1) ?>">
      </div>

      <div class="d-grid gap-2">
        <button class="btn btn-primary" type="submit">Save</button>
        <a class="btn btn-outline-primary" href="/smproduce/pages/generate_bol_pdf.php?id=<?= urlencode($bolId) ?>">Preview / Print PDF</a>
      </div>
    </div>
  </div>
</form>

<script>
(function(){
  const MM_W = 210, MM_H = 297; // A4
  const bg = document.getElementById('bolBg');
  const canvas = document.getElementById('bolCanvas');
  const fields = Array.from(document.querySelectorAll('.bol-field'));
  const fieldSelect = document.getElementById('fieldSelect');
  const presetBlock = document.getElementById('presetBlock');
  const presetSelect = document.getElementById('presetSelect');
  const wordEditor = document.getElementById('wordEditor');
  const fieldMeta = document.getElementById('fieldMeta');
  const clearFmt = document.getElementById('clearFmt');

  let currentField = null;

  function pxScale(){
    const w = bg.naturalWidth || bg.clientWidth;
    const h = bg.naturalHeight || bg.clientHeight;
    return { sx: w / MM_W, sy: h / MM_H, w, h };
  }

  function positionFields(){
    const {sx, sy, w, h} = pxScale();
    canvas.style.width = w + 'px';
    canvas.style.height = h + 'px';

    fields.forEach(el=>{
      const x = parseFloat(el.dataset.xMm || '0') * sx;
      const y = parseFloat(el.dataset.yMm || '0') * sy;
      const ww = parseFloat(el.dataset.wMm || '0') * sx;
      const hh = parseFloat(el.dataset.hMm || '0') * sy;
      el.style.left = x + 'px';
      el.style.top = y + 'px';
      el.style.width = ww + 'px';
      el.style.height = hh + 'px';
    });
  }

  function deselect(){
    fields.forEach(f=>f.classList.remove('selected'));
    currentField = null;
    fieldSelect.value = '';
    presetBlock.style.display = 'none';
    wordEditor.innerHTML = '';
    wordEditor.setAttribute('contenteditable','false');
    fieldMeta.textContent = 'Select a field to edit.';
  }

  function selectFieldById(id){
    const el = fields.find(f => String(f.dataset.fieldId) === String(id));
    if(!el){ deselect(); return; }

    fields.forEach(f=>f.classList.remove('selected'));
    el.classList.add('selected');
    currentField = el;
    fieldSelect.value = id;

    const type = el.dataset.type || 'text';
    const label = el.dataset.label || '';
    const code = el.dataset.code || '';
    fieldMeta.textContent = `${label}  (${code})`;

    if(type === 'preset'){
      presetBlock.style.display = 'block';
      wordEditor.innerHTML = '';
      wordEditor.setAttribute('contenteditable','false');

      // preset field stores preset id (as plain value)
      const ta = document.getElementById('fieldInput' + id);
      const current = (ta ? ta.value : '');
      if(current) presetSelect.value = current;
      else presetSelect.value = '';
    } else if(type === 'checkbox'){
      presetBlock.style.display = 'none';
      wordEditor.setAttribute('contenteditable','false');
      wordEditor.innerHTML = '<div class="small-muted">Checkbox field. Click the field on the document to toggle.</div>';
    } else {
      presetBlock.style.display = 'none';
      wordEditor.setAttribute('contenteditable','true');

      const ta = document.getElementById('fieldInput' + id);
      wordEditor.innerHTML = ta ? ta.value : '';
      // focus
      setTimeout(()=>wordEditor.focus(), 0);
    }
  }

  function commitEditor(){
    if(!currentField) return;
    const id = currentField.dataset.fieldId;
    const type = currentField.dataset.type || 'text';
    const ta = document.getElementById('fieldInput' + id);
    if(!ta) return;

    if(type === 'preset'){
      ta.value = presetSelect.value === '__new__' ? '' : presetSelect.value;
      currentField.innerHTML = ''; // don't render preset id on canvas
      return;
    }
    if(type === 'checkbox'){
      // stored as 1/0
      ta.value = (ta.value === '1') ? '0' : '1';
      currentField.textContent = (ta.value === '1') ? 'X' : '';
      return;
    }

    const html = wordEditor.innerHTML || '';
    ta.value = html;
    currentField.innerHTML = html;
  }

  // Click on canvas field
  fields.forEach(el=>{
    el.addEventListener('click', (e)=>{
      e.preventDefault();
      selectFieldById(el.dataset.fieldId);
    });
    if((el.dataset.type || '') === 'checkbox'){
      el.addEventListener('dblclick', (e)=>{
        e.preventDefault();
        selectFieldById(el.dataset.fieldId);
        commitEditor();
      });
    }
  });

  fieldSelect.addEventListener('change', ()=>{
    if(!fieldSelect.value) return deselect();
    selectFieldById(fieldSelect.value);
  });

  // Toolbar commands (execCommand)
  document.querySelectorAll('.toolbar button[data-cmd]').forEach(btn=>{
    btn.addEventListener('click', ()=>{
      if(!currentField) return;
      const type = currentField.dataset.type || 'text';
      if(type === 'preset' || type === 'checkbox') return;
      document.execCommand(btn.dataset.cmd, false, null);
      commitEditor();
    });
  });

  clearFmt.addEventListener('click', ()=>{
    if(!currentField) return;
    const type = currentField.dataset.type || 'text';
    if(type === 'preset' || type === 'checkbox') return;
    // remove formatting
    document.execCommand('removeFormat', false, null);
    document.execCommand('unlink', false, null);
    commitEditor();
  });

  // Update on typing
  wordEditor.addEventListener('input', ()=>{
    commitEditor();
  });

  // Preset selection
  presetSelect.addEventListener('change', async ()=>{
    if(!currentField) return;
    if(presetSelect.value === '__new__'){
      const name = prompt('Preset name (will be created empty; edit values under Presets):', 'New Preset');
      if(!name){
        presetSelect.value = '';
        return;
      }
      try{
        const res = await fetch('/smproduce/pages/bol_presets_api.php?action=create', {method:'POST'});
        const json = await res.json();
        if(!json.ok) throw new Error(json.error || 'Failed');
        const id = json.id;

        // Rename preset immediately
        await fetch('/smproduce/pages/bol_presets_api.php?action=save', {
          method:'POST',
          headers:{'Content-Type':'application/json'},
          body: JSON.stringify({ id, name, description:'', values_json: {} })
        });

        // Add option to dropdown
        const opt = document.createElement('option');
        opt.value = id;
        opt.textContent = name;
        presetSelect.insertBefore(opt, presetSelect.querySelector('option[value="__new__"]'));
        presetSelect.value = id;
        commitEditor();
      } catch(e){
        alert('Could not create preset: ' + e.message);
        presetSelect.value = '';
      }
      return;
    }
    commitEditor();
  });

  // Ensure correct positioning after image load
  if(bg.complete) positionFields();
  else bg.addEventListener('load', positionFields);

  // Save: ensure the selected field commits
  document.getElementById('bolSaveForm').addEventListener('submit', ()=>{
    commitEditor();
  });

  // Default: select first field for convenience? No.
})();
</script>

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