<?php
$tenant = $_REQUEST['tenant'] ?? '';
if($tenant !== '' && file_exists('../../../'.$tenant.'/config.php')){require_once('../../../'.$tenant.'/config.php');}
if(file_exists('/config.php')){require_once('/config.php');}

$type = $_REQUEST['type'] ?? '';
$uid  = 'notes_' . bin2hex(random_bytes(4)); // instance namespace
$itemnumber = (int)($_REQUEST['itemnumber'] ?? 0);
$locnumber = (int)($_REQUEST['locnumber'] ?? 0);

if ($type === "locations") {
    $stmt2 = $GLOBALS['con']->prepare("SELECT `locname`,`locnotes` FROM `locations` WHERE `locnumber`=?") or die(mysqli_error($GLOBALS['con']));
    $stmt2->bind_param('i', $locnumber);
    $stmt2->execute(); $in = $stmt2->get_result(); $stmt2->close();
    $d = $in ? mysqli_fetch_array($in) : [];
    if (!is_array($d)) $d = [];
    $note  = str_replace('$#39;', "'", (string)($d['locnotes'] ?? ''));
    $title = $d['locname'] ?? '';
    $mode  = 'location';
} else { // itemdetails
    $stmt2 = $GLOBALS['con']->prepare("SELECT `desc`,`itemnotes` FROM `itemdetails` WHERE `itemnumber`=?") or die(mysqli_error($GLOBALS['con']));
    $stmt2->bind_param('i', $itemnumber);
    $stmt2->execute(); $in = $stmt2->get_result(); $stmt2->close();
    $d = $in ? mysqli_fetch_array($in) : [];
    if (!is_array($d)) $d = [];
    $note  = str_replace('$#39;', "'", (string)($d['itemnotes'] ?? ''));
    $title = $d['desc'] ?? '';
    $mode  = 'item';
}
$noteEdit = preg_replace('/<br\s*\/?>/i', "\n", $note);
?>
<style>
  #<?= $uid ?> .notes-display {
    max-height: 45vh;
    overflow: auto;
    white-space: normal;
  }

  #<?= $uid ?> .notes-display-content {
    overflow-wrap: anywhere;
  }
</style>

<div id="<?= $uid ?>" class="notes-root" data-mode="<?= htmlspecialchars($mode) ?>"
     data-item="<?= $itemnumber ?>"
     data-location="<?= $locnumber ?>"
     data-type="<?= htmlspecialchars($type) ?>">

  <div class="note note-light mb-3 notes-display" id="<?= $uid ?>_display">
    <div class="small text-muted text-uppercase mb-1"><?= $mode === 'item' ? 'Item Notes' : 'Location Notes' ?></div>
    <div class="notes-display-content">
      <?= trim($note) !== '' ? nl2br(htmlspecialchars($note, ENT_QUOTES, 'UTF-8')) : '<span class="text-muted">No notes recorded.</span>' ?>
    </div>
  </div>

  <div class="mb-3" id="<?= $uid ?>_editor" style="display:none;">
    <label class="form-label" for="<?= $uid ?>_textarea">Notes</label>
    <textarea class="form-control" id="<?= $uid ?>_textarea" rows="7"><?= htmlspecialchars($noteEdit, ENT_QUOTES, 'UTF-8') ?></textarea>
  </div>

  <div class="d-flex justify-content-end gap-2">
    <button type="button" id="<?= $uid ?>_toggle" class="btn btn-secondary btn-sm">
      <i class="fad fa-pencil"></i> <span>Edit</span>
    </button>
    <button type="button" class="btn btn-info btn-sm" id="<?= $uid ?>_save" style="display:none;">
      <i class="fad fa-save"></i> Save Changes
    </button>
  </div>
</div>

<script>
(() => {
  const uid = "<?= $uid ?>";
  const root = document.getElementById(uid);
  if (!root) return;

  // Cache instance elements
  const display = document.getElementById(uid + "_display");
  const editor  = document.getElementById(uid + "_editor");
  const toggle  = document.getElementById(uid + "_toggle");
  const toggleText = toggle ? toggle.querySelector('span') : null;
  const saveBtn = document.getElementById(uid + "_save");
  const ta      = document.getElementById(uid + "_textarea");
  const mode    = root.dataset.mode; // 'item' or 'location'
  const type    = root.dataset.type;
  const item    = root.dataset.item;
  const location= root.dataset.location;

  // Helper: header subtitle element in this modal (optional)
  const sa = root.closest('.modal-content')?.querySelector('.modal-header .sa') || null;

  // Reset view on init
  function resetView() {
    editor.style.display = "none";
    display.style.display = "block";
    if (toggleText) toggleText.textContent = "Edit";
    if (saveBtn) saveBtn.style.display = "none";
    if (sa) sa.textContent = (mode === 'item') ? 'Item Notes' : 'Location Notes';
  }

  function doToggle() {
    const editing = editor.style.display === "block";
    if (editing) {
      editor.style.display = "none";
      display.style.display = "block";
      if (toggleText) toggleText.textContent = "Edit";
      if (saveBtn) saveBtn.style.display = "none";
      if (sa) sa.textContent = (mode === 'item') ? 'Item Notes' : 'Location Notes';
    } else {
      editor.style.display = "block";
      display.style.display = "none";
      if (toggleText) toggleText.textContent = "Cancel";
      if (saveBtn) saveBtn.style.display = "";
      if (sa) sa.textContent = (mode === 'item') ? 'Item Notes - Edit' : 'Location Notes - Edit';
      ta.focus();
    }
  }

  function escapeHtml(value) {
    return String(value ?? '')
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#039;');
  }

  function renderNotes(value) {
    const text = String(value || '');
    if (text.trim() === '') return '<span class="text-muted">No notes recorded.</span>';
    return escapeHtml(text).replace(/\n/g, '<br>');
  }

  async function saveNotes() {
    const notes = ta.value;
    try {
      const res = await fetch(ROOT_URL + '/forms/elements/asset_notes.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: new URLSearchParams({
          notes: notes,
          tenant: TENANT_URL,
          item: item,
          location: location,
          type: type
        })
      });
      const text = await res.text();
      if (!res.ok || !/^success\b/i.test(text.trim())) {
        throw new Error(text || 'Save failed');
      }
      display.querySelector('.notes-display-content').innerHTML = renderNotes(notes);
      editor.style.display = "none";
      display.style.display = "block";
      if (toggleText) toggleText.textContent = "Edit";
      if (saveBtn) saveBtn.style.display = "none";
      showResponse('success', 'Your notes have been saved successfully');
    } catch(e) {
      showResponse('danger', 'Save failed. Try again.');
    }
  }

  // Bind per-instance handlers
  toggle.addEventListener('click', doToggle);
  saveBtn.addEventListener('click', saveNotes);

  // Ensure clean initial state every time content is injected
  resetView();

  // Optional: when this modal is shown again, re-reset the view
  const modal = root.closest('.modal');
  if (modal) {
    modal.addEventListener('shown.mdb.modal', resetView, { once: false });
  }
})();
</script>
