<?php 
require_once __DIR__ . '/security.php';

$jsonInput = json_decode(file_get_contents('php://input'), true);
if (is_array($jsonInput)) {
    foreach ($jsonInput as $key => $value) {
        $_REQUEST[$key] = $value;
    }
}

$tenant = enrep_tenant_segment();
if($tenant !== '' && file_exists('../../'.$tenant.'/config.php')){require_once('../../'.$tenant.'/config.php');}
if(file_exists('/config.php')){require_once('/config.php');}
if (!isset($GLOBALS['con']) || !($GLOBALS['con'] instanceof mysqli)) {
    enrep_fail(400, 'Tenant config not found');
}
enrep_require_user();
require_once(__DIR__ . '/deliveryModules/reportListHelpers.php');

$str = delivery_report_list_tokens($_REQUEST['selected'] ?? '');
$errordelJson = delivery_report_list_json($_REQUEST['errordel'] ?? '');
$forceGenValue = $_REQUEST['forceGen'] ?? '';
$hseValue = $_REQUEST['hse'] ?? '';
$chainModeValue = $_REQUEST['chainMode'] ?? '';

function getAsset($i){
    $i = (int)$i;
    if($i > 0){
    $stmt = $GLOBALS['con']->prepare("SELECT `linked`,`desc`,`swl`,`serialnumber`,`plantnumber` FROM `itemdetails` WHERE `itemnumber`=? LIMIT 1");
    if (!$stmt) {
        return false;
    }
    $stmt->bind_param('i', $i);
    $stmt->execute();
    $res = $stmt->get_result();
    $stmt->close();
    $item = mysqli_fetch_array($res);
    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</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);
                if (!is_array($itemdata)) {
                    continue;
                }
                $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{
            ?>
            <?php
            $payload = [
                $linked,
                $itemdata['desc'] ?? '',
                $itemdata['swl'] ?? '',
                $itemdata['serialnumber'] ?? '',
                $itemdata['plantnumber'] ?? '',
                'R' . $count
            ];
            $dataString = htmlspecialchars(json_encode($payload, JSON_UNESCAPED_UNICODE), ENT_QUOTES, 'UTF-8');
            $itemIdEsc = htmlspecialchars($items, ENT_QUOTES, 'UTF-8');
            $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');
            ?>
            <li id="RS<?php echo (int)$count?>" class="list-group-item btn-block rounded" draggable="true" data-item-id="<?php echo $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 rows draggable
  function makeDraggable(){
    dF.querySelectorAll('li').forEach(li => li.setAttribute('draggable','true'));
  }
  makeDraggable();

  // ---- Drag & Drop ----
  dF.addEventListener('dragstart', 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', e => {
    const li = e.target.closest('li');
    if (!li) return;
    li.classList.remove('dragging');
    li.style.backgroundColor = '';
    li.style.color = '';
    li.style.opacity = '';
    updateOrder();
  });

  dF.addEventListener('dragover', e => {
    e.preventDefault();
    const dragging = dF.querySelector('.dragging');
    if (!dragging) return;
    const after = getAfter(dF, e.clientY);
    if (!after) dF.appendChild(dragging);
    else dF.insertBefore(dragging, after);
  });

  dF.addEventListener('drop', e => {
    e.preventDefault();
    updateOrder();
  });

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

  // ---- Up / Down buttons ----
  dF.addEventListener('click', e => {
    if (e.target.closest('.up-button')){
      const li = e.target.closest('li');
      const prev = li?.previousElementSibling;
      if (li && prev && prev.tagName === 'LI'){
        highlight(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'){
        highlight(li);
        setTimeout(() => { dF.insertBefore(next, li); updateOrder(); }, 150);
      }
    }
  });

  function highlight(row){
    row.style.backgroundColor = '#585858';
    row.style.color = '#FFF';
    setTimeout(() => {
      row.style.transition = 'background-color .6s ease,color .6s ease';
      row.style.backgroundColor = '';
      row.style.color = '';
      setTimeout(() => { row.style.transition=''; }, 650);
    }, 120);
  }

  // ---- Sorting UI ----
  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(i => i.className = 'fad fa-chevron-up');
    displayCurrentSort();
    updateOrder();
  }

  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 a1 = getCell(a, currentSort.primary.column);
      const b1 = getCell(b, currentSort.primary.column);
      let r = cmp(a1,b1);
      if (currentSort.primary.order === 'desc') r *= -1;
      if (r === 0 && currentSort.secondary.column){
        const a2 = getCell(a, currentSort.secondary.column);
        const b2 = getCell(b, currentSort.secondary.column);
        r = cmp(a2,b2);
        if (currentSort.secondary.order === 'desc') r *= -1;
      }
      return r;
    });
    dF.innerHTML = '';
    sorted.forEach(li => dF.appendChild(li));
    makeDraggable();
  }

  function getCell(li, column){
    const arr = safeJson(li.getAttribute('data-string'));
    const idx = getIdx(column);
    return normalize(arr[idx] ?? '');
  }

  function safeJson(s){
    try { return JSON.parse(s || '[]'); } catch(e){ return []; }
  }

  function getIdx(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 normalize(v){
    const s = String(v).trim();
    if (s !== '' && !isNaN(Number(s))) return s.padStart(20,'0');
    return s.toLowerCase();
  }

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

  function updateSortButtons(column, order){
    document.querySelectorAll('.btn-secondary i').forEach(i => i.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: ${cap(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: ${cap(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 cap(w){ return w ? w.charAt(0).toUpperCase()+w.slice(1) : ''; }

  // ---- Order capture ----
  function updateOrder(){
    const order = JSON.stringify(Array.from(dF.children).map(li => li.getAttribute('data-item-id')).filter(Boolean));
    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 || '';
    singleContinue(neworder, <?= json_encode($errordelJson) ?>, <?= json_encode($forceGenValue) ?>, <?= json_encode($hseValue) ?>, <?= json_encode($chainModeValue) ?>);
  };

  document.addEventListener('DOMContentLoaded', updateOrder);
})();
</script>


<style>
.dragging {
    opacity: 0.5;
}

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