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

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

if ($type === "locations") {
    $stmt2 = $GLOBALS['con']->prepare("SELECT `locname`,`locnotes` FROM `locations` WHERE `locnumber`=?") or die(mysqli_error($GLOBALS['con']));
    $stmt2->bind_param('i', $_REQUEST['locnumber']);
    $stmt2->execute(); $in = $stmt2->get_result(); $stmt2->close();
    $d = mysqli_fetch_array($in);
    $note  = $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', $_REQUEST['itemnumber']);
    $stmt2->execute(); $in = $stmt2->get_result(); $stmt2->close();
    $d = mysqli_fetch_array($in);
    $note  = $d['itemnotes'] ?? '';
    $title = $d['desc'] ?? '';
    $mode  = 'item';
}
$noteEdit = str_replace('<br>', "\n", $note);
?>
<div id="<?= $uid ?>" class="notes-root" data-mode="<?= htmlspecialchars($mode) ?>"
     data-item="<?= isset($_REQUEST['itemnumber']) ? (int)$_REQUEST['itemnumber'] : 0 ?>"
     data-location="<?= isset($_REQUEST['locnumber']) ? (int)$_REQUEST['locnumber'] : 0 ?>"
     data-type="<?= htmlspecialchars($type) ?>">

  <div class="col-md-12 mb-2" id="<?= $uid ?>_display">
    <?= nl2br($note) ?>
  </div>

  <div class="text-end mb-2">
    <a id="<?= $uid ?>_toggle" class="btn btn-secondary">Edit</a>
  </div>

  <div class="form-group row mb-2" id="<?= $uid ?>_editor" style="display:none;">
    <div class="col-12">
      <label class="control-label" for="<?= $uid ?>_textarea"><strong>Notes</strong></label>
      <textarea class="form-control" id="<?= $uid ?>_textarea" rows="5"><?= htmlspecialchars($noteEdit) ?></textarea>
    </div>
    <div class="col-12 mt-3 text-center">
      <a class="btn btn-success" id="<?= $uid ?>_save">Save Changes</a>
    </div>
  </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 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";
    toggle.textContent = "Edit";
    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";
      toggle.textContent = "Edit";
      if (sa) sa.textContent = (mode === 'item') ? 'Item Notes' : 'Location Notes';
    } else {
      editor.style.display = "block";
      display.style.display = "none";
      toggle.textContent = "Cancel Edit";
      if (sa) sa.textContent = (mode === 'item') ? 'Item Notes - Edit' : 'Location Notes - Edit';
    }
  }

  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(); // unused, retained for debugging if needed
      display.innerHTML = notes.replace(/\n/g, "<br>");
      editor.style.display = "none";
      display.style.display = "block";
      toggle.textContent = "Edit";
      showResponse('success', 'Your notes have been saved successfully');
    } catch(e) {
      showResponse('danger', 'Save failed. Try again.');
    }
  }

  // Bind per-instance handlers
  toggle.addEventListener('click', doToggle);
  document.getElementById(uid + "_save").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>
