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

$str=explode("|",$_REQUEST['selected']);

function getAsset($i){
    if(!empty($i)){
    $stmt = mysqli_query($GLOBALS['con'],"SELECT `linked`,`desc`,`swl`,`serialnumber`,`plantnumber` FROM `itemdetails` WHERE `itemnumber`=$i") ;
    $item = mysqli_fetch_array($stmt);
    if ($item) {
        $resultArray = [
            'linked' => $item['linked'],
            'desc' => $item['desc'],
            'swl' => $item['swl'],
            'serialnumber' => $item['serialnumber'],
            'plantnumber' => str_replace('"', '', $item['plantnumber'])
        ];
        $jsonResult = json_encode($resultArray);
        return $jsonResult;
    } else {
        return false;
    }
}
}
?>
<div class="row">
    <div class="text-end">
        <a id="filterchain" href="javascript:void(0)" class="btn btn-secondary btn-sm" onclick="filterList('chain','asc')">Sort by chain <i class="fad fa-chevron-up"></i></a>
        <a id="filterdesc" href="javascript:void(0)" class="btn btn-secondary btn-sm" onclick="filterList('desc','asc')">Sort by Desc <i class="fad fa-chevron-up"></i></a>
        <a id="filterswl" href="javascript:void(0)" class="btn btn-secondary btn-sm" onclick="filterList('swl','asc')">Sort by SWL <i class="fad fa-chevron-up"></i></a>
        <a id="filterserial" href="javascript:void(0)" class="btn btn-secondary btn-sm" onclick="filterList('serial','asc')">Sort by serial <i class="fad fa-chevron-up"></i></a>
        <a id="filterplant" href="javascript:void(0)" class="btn btn-secondary btn-sm" onclick="filterList('plant','asc')">Sort by plant <i class="fad fa-chevron-up"></i></a>
    </div>
</div>

<div class="row mt-2">
    <div id="sortDisplay"></div>
</div>

<div class="row">
    <div class="col-12  bg-info text-light rounded">
        <div class="row">
            <div class="col-2">Chain A</div>
            <div class="col-8">
                <div class="row">
                    <div class="col-4">Description</div>
                    <div class="col-2">SWL</div>
                    <div class="col-3">Serial Number</div>
                    <div class="col-3">Plant Number</div>
                </div>
            </div>
            <div class="col-2 text-right"></div>
        </div>

    </div>
</div>
<div class="row">
    <div class="col-12" style="overflow: auto; max-height:500px">
        <ul id="dF" class="selectorData list-group list" style="padding:5px 0 50px 0">
            <?php 
            $c = -1;
            $count = 1;
            foreach($str as $items) {
                $item = explode('-', $items);
                $itemdata = json_decode(getAsset($item[1]), true);
                $linkdata = explode(":", $itemdata['linked']);
                if ($itemdata['swl'] == "") $itemdata['swl'] = '-';
                if ($itemdata['plantnumber'] == "") $itemdata['plantnumber'] = '-';
                if ($itemdata['serialnumber'] == "") $itemdata['serialnumber'] = '-';
                if ($item['linked'] != "") $c++;
                if (!empty($linkdata[0])) $linked = "C".$linkdata[0];
                else $linked = '';
                $data = [
                    'chain' => $linked,
                    'description' => $itemdata['desc'],
                    'serialNumber' => $itemdata['serialNumber'],
                    'plantNumber' => $itemdata['plantNumber'],
                    'count' => $count
                ];
                $jsonData = json_encode($data);
                if(empty($itemdata['desc'])){}
                else{
          
// Build the payload once, then safely embed it
$payload = [
    $linked,
    $itemdata['desc'] ?? '',
    $itemdata['swl'] ?? '',
    $itemdata['serialnumber'] ?? '',
    $itemdata['plantnumber'] ?? '',
    'R' . $count
];

// JSON for JS consumption
$dataString = htmlspecialchars(json_encode($payload, JSON_UNESCAPED_UNICODE), ENT_QUOTES, 'UTF-8');

// Also escape visible text output
$linkedEsc = htmlspecialchars($linked, ENT_QUOTES, 'UTF-8');
$descEsc   = htmlspecialchars($itemdata['desc'] ?? '', ENT_QUOTES, 'UTF-8');
$swlEsc    = htmlspecialchars($itemdata['swl'] ?? '-', ENT_QUOTES, 'UTF-8');
$snEsc     = htmlspecialchars($itemdata['serialnumber'] ?? '-', ENT_QUOTES, 'UTF-8');
$pnEsc     = htmlspecialchars($itemdata['plantnumber'] ?? '-', ENT_QUOTES, 'UTF-8');

// If you output the composite id, escape that too
$itemIdEsc = htmlspecialchars($items, ENT_QUOTES, 'UTF-8');
?>
<li id="RS<?= $count ?>" class="list-group-item btn-block rounded" draggable="true"
    data-item-id="<?= $itemIdEsc ?>"
    data-string='<?= $dataString ?>'>
  <div class="row">
    <div class="col-2"><?= $linkedEsc ?></div>
    <div class="col-8">
      <div class="row">
        <div class="col-4"><?= $descEsc ?></div>
        <div class="col-2"><?= $swlEsc ?></div>
        <div class="col-3"><?= $snEsc ?></div>
        <div class="col-3"><?= $pnEsc ?></div>
      </div>
    </div>
    <div class="col-2">
      <a href="javascript:void(0)" class="up-button float-left"><i class="fad fa-arrow-circle-up fa-2x"></i></a>
      <a href="javascript:void(0)" class="down-button float-end"><i class="fad fa-arrow-circle-down fa-2x"></i></a>
    </div>
  </div>
</li>
            <?php $count++;}}?>
        </ul>
    </div>
</div>
<div class="row mt-2">
    <div class="col-12">
        <input type="hidden" class="form-control" id="newOrder">
        <a class="btn btn-info btn-block" onClick="commit()">Commit changes and sort order</a>
    </div>
</div>

<div id="debugger" style="border-radius: 5px; background: #fff; padding:10px; position:absolute; top:-80px; left:-350px; width:300px; height:700px; display:none">
    <p></p>
</div>

<script>
(function(){
  const dF = document.getElementById('dF');
  if (!dF) return;

  // Make all rows draggable
  const makeDraggable = () => {
    dF.querySelectorAll('li').forEach(li => li.setAttribute('draggable', 'true'));
  };
  makeDraggable();

  // ---------- DnD ----------
  dF.addEventListener('dragstart', function(e){
    const li = e.target.closest('li');
    if (!li) return;
    e.dataTransfer.effectAllowed = 'move';
    e.dataTransfer.setData('text/plain', li.dataset.itemId || '');
    li.classList.add('dragging');
    li.style.backgroundColor = '#585858';
    li.style.color = '#FFF';
    li.style.opacity = '1';
  });

  dF.addEventListener('dragend', function(e){
    const li = e.target.closest('li');
    if (!li) return;
    li.classList.remove('dragging');
    li.style.color = '';
    li.style.backgroundColor = '';
    li.style.opacity = '';
    updateOrder();
  });

  dF.addEventListener('dragover', function(e){
    e.preventDefault();
    const draggingItem = dF.querySelector('.dragging');
    if (!draggingItem) return;
    const afterElement = getDragAfterElement(dF, e.clientY);
    if (afterElement == null) dF.appendChild(draggingItem);
    else dF.insertBefore(draggingItem, afterElement);
  });

  dF.addEventListener('drop', function(e){
    e.preventDefault();
    // Nothing extra required; DOM already updated in dragover
    updateOrder();
  });

  function getDragAfterElement(container, mouseY){
    const els = [...container.querySelectorAll('li:not(.dragging)')];
    let closest = {offset: Number.NEGATIVE_INFINITY, element: null};
    for (const child of els){
      const box = child.getBoundingClientRect();
      const offset = mouseY - box.top - box.height / 2;
      if (offset < 0 && offset > closest.offset){
        closest = {offset, element: child};
      }
    }
    return closest.element;
  }

  // ---------- Up / Down buttons ----------
  dF.addEventListener('click', function(e){
    if (e.target.closest('.up-button')) {
      const li = e.target.closest('li');
      const prev = li?.previousElementSibling;
      if (li && prev && prev.tagName === 'LI') {
        highlightRow(li);
        setTimeout(() => {
          dF.insertBefore(li, prev);
          updateOrder();
        }, 150);
      }
    }
    if (e.target.closest('.down-button')) {
      const li = e.target.closest('li');
      const next = li?.nextElementSibling;
      if (li && next && next.tagName === 'LI') {
        highlightRow(li);
        setTimeout(() => {
          dF.insertBefore(next, li);
          updateOrder();
        }, 150);
      }
    }
  });

  function highlightRow(row){
    row.style.backgroundColor = '#585858';
    row.style.color = '#FFF';
    setTimeout(() => {
      row.style.transition = 'background-color 0.6s ease, color 0.6s ease';
      row.style.backgroundColor = '';
      row.style.color = '';
      setTimeout(() => { row.style.transition = ''; }, 700);
    }, 150);
  }

  // ---------- Sorting UI (primary/secondary) ----------
  let currentSort = { primary: {column:null, order:null}, secondary: {column:null, order:null} };

  function resetFilters(){
    currentSort = { primary: {column:null, order:null}, secondary: {column:null, order:null} };
    document.querySelectorAll('.btn-secondary i').forEach(icon => { icon.className = 'fad fa-chevron-up'; });
    displayCurrentSort();
    updateOrder();
  }

  // MDB modal event (plus Bootstrap fallback)
  const sortBox = document.getElementById('sortBox');
  if (sortBox){
    sortBox.addEventListener('shown.mdb.modal', resetFilters);
    sortBox.addEventListener('shown.bs.modal', resetFilters);
  }

  window.filterList = function(column, order){
    if (!currentSort.primary.column){
      currentSort.primary = {column, order};
    } else if (currentSort.primary.column === column){
      currentSort.primary.order = order;
    } else if (!currentSort.secondary.column || currentSort.secondary.column === column){
      currentSort.secondary = {column, order};
    }
    performSorting();
    updateSortButtons(column, order);
    displayCurrentSort();
    updateOrder();
  };

  function performSorting(){
    const items = [...dF.querySelectorAll('li')];
    const sorted = items.sort((a, b) => {
      const sa = getCell(a, currentSort.primary.column);
      const sb = getCell(b, currentSort.primary.column);
      let result = compareVals(sa, sb);
      if (currentSort.primary.order === 'desc') result *= -1;
      if (result === 0 && currentSort.secondary.column){
        const s2a = getCell(a, currentSort.secondary.column);
        const s2b = getCell(b, currentSort.secondary.column);
        result = compareVals(s2a, s2b);
        if (currentSort.secondary.order === 'desc') result *= -1;
      }
      return result;
    });
    dF.innerHTML = '';
    sorted.forEach(li => dF.appendChild(li));
    makeDraggable();
  }

  function getCell(li, column){
    const arr = JSON.parse(li.getAttribute('data-string') || '[]');
    const idx = getColumnIndex(column);
    return normalizeValue(arr[idx] ?? '');
  }

  function getColumnIndex(column){
    switch(column){
      case 'chain': return 0;
      case 'desc':  return 1;
      case 'swl':   return 2;
      case 'serial':return 3;
      case 'plant': return 4;
      default:      return 0;
    }
  }

  function normalizeValue(v){
    const s = String(v).trim();
    if (s !== '' && !isNaN(Number(s))) return s.padStart(20,'0');
    return s.toLowerCase();
  }

  function compareVals(a, b){
    if (a === b) return 0;
    return a < b ? -1 : 1;
  }

  function updateSortButtons(column, order){
    document.querySelectorAll('.btn-secondary i').forEach(icon => { icon.className = 'fad fa-chevron-up'; });
    const btn = document.getElementById(`filter${column}`);
    if (!btn) return;
    const icon = btn.querySelector('i');
    if (icon) icon.className = (order === 'asc') ? 'fad fa-chevron-up' : 'fad fa-chevron-down';
    btn.setAttribute('onclick', `filterList('${column}','${order === 'asc' ? 'desc' : 'asc'}')`);
  }

  function displayCurrentSort(){
    const el = document.getElementById('sortDisplay');
    if (!el) return;
    el.innerHTML = '';
    if (currentSort.primary.column){
      el.innerHTML = `
        <nav aria-label="breadcrumb">
          <ol class="breadcrumb">
            <li class="breadcrumb-item">
              <div class="input-group">
                <div class="form-control">Primary Sort: ${capitalize(currentSort.primary.column)} (${currentSort.primary.order.toUpperCase()})</div>
                <button class="btn btn-sm btn-dark" onclick="clearSort('primary')"><i class="fad fa-trash-can-undo"></i></button>
              </div>
            </li>
            ${currentSort.secondary.column ? `
            <li class="breadcrumb-item">
              <div class="input-group">
                <div class="form-control">Secondary Sort: ${capitalize(currentSort.secondary.column)} (${currentSort.secondary.order.toUpperCase()})</div>
                <button class="btn btn-sm btn-dark" onclick="clearSort('secondary')"><i class="fad fa-trash-can-undo"></i></button>
              </div>
            </li>` : ''}
          </ol>
        </nav>`;
    }
  }

  window.clearSort = function(type){
    if (type === 'primary'){
      currentSort = { primary:{column:null,order:null}, secondary:{column:null,order:null} };
      displayCurrentSort();
      updateOrder();
      return;
    }
    if (type === 'secondary'){
      currentSort.secondary = {column:null, order:null};
      performSorting();
      displayCurrentSort();
      updateOrder();
    }
  };

  function capitalize(w){ return w ? w.charAt(0).toUpperCase() + w.slice(1) : ''; }

  // ---------- Order capture ----------
  function updateOrder(){
    const order = Array.from(dF.children).map(li => li.getAttribute('data-item-id')).join('|');
    const input = document.getElementById('newOrder');
    if (input) input.value = order;
    const dbg = document.getElementById('debugger');
    if (dbg && dbg.querySelector('p')) dbg.querySelector('p').textContent = order;
  }
  window.updateOrder = updateOrder;

  // ---------- Commit ----------
  window.commit = function(){
    killModal('multiBox');
    killModal('sortBox');
    const neworder = document.getElementById('newOrder')?.value || '';
    genPack(neworder, '<?= $_REQUEST['errordel']?>', '<?= $_REQUEST['forceGen']?>', '<?= $_REQUEST['hse']?>', '<?= $_REQUEST['chainMode']?>');
  };

  // Initial state
  document.addEventListener('DOMContentLoaded', function(){
    updateOrder();
  });
})();
</script>


<style>
.dragging {
    opacity: 0.5;
}

#dF li {
    cursor: pointer
}
</style>