<?php
include '../managers/menu.php';

if (!UserHasPerm('production_boxing')) {
  StopAndDie();
}

if (isset($_POST["func"])) {
  if (htmlspecialchars($_POST["func"]) == "filter") {

    if (!isset($_COOKIE['maxperpage'])) {
      setcookie("maxperpage", "25", time() + (86400 * 90), "/");
      $maxperpage = "25";
    } else {
      $maxperpage = $_COOKIE['maxperpage'];
    }

    setcookie("maxperpage", strval($maxperpage), time() + (86400 * 90), "/");

    $perpageselect = "<option value='25'>5 db / oszlop</option>
    <option value='50'>10 db / oszlop</option>
    <option value='100'>20 db / oszlop</option>
    <option value='250'>50 db / oszlop</option>
    <option value='500'>100 db / oszlop</option>
    <option value='1000'>200 db / oszlop</option>";
    $perpageselect = str_replace("value='".$maxperpage."'", "value='".$maxperpage."' selected", $perpageselect);

    $json = json_encode(array(
        'perpage' => $perpageselect,
        'result' => 'ok'
    ));

    echo $json;
  } else if (htmlspecialchars($_POST["func"]) == "table") {
    $maxperpage = intval(htmlspecialchars($_POST['perpage'] ?? 25));
    $cpage = intval(htmlspecialchars($_POST['cpage'] ?? 1));
    $item_id = htmlspecialchars(str_replace(' ', '+', $_POST['item_id']) ?? '');
    $category = htmlspecialchars($_POST['category'] ?? '');

    if ($maxperpage < 1) $maxperpage = 25;
    if ($cpage < 1) $cpage = 1;
    setcookie("maxperpage", $maxperpage, time() + 86400*90, "/");
    $maxperpage = $maxperpage / 5;
    $offset = max(0, ($cpage - 1) * $maxperpage);

    $item_filter = '';
    if (!empty($item_id)) {
      $item_filter = " AND item_id LIKE '%" . mysqli_real_escape_string($conn, $item_id) . "%'";
    }

    $tables = ['boxing'];
    $results_by_stage = [];

    $all_items = [];
    for ($stage = 1; $stage <= 2; $stage++) {
      $stage_results = [];
      $union_parts = [];
      foreach ($tables as $t) {
        $union_parts[] = "(SELECT pr_id, item_id, stage, date_start, db_start, '$t' AS category
                            FROM production_{$t}
                            WHERE stage=$stage $item_filter)";
      }
      $sql = "SELECT * FROM (" . implode(" UNION ALL ", $union_parts) . ") AS u";
      $res = mysqli_query($conn, $sql);
      while ($res && $row = mysqli_fetch_assoc($res)) {
        $hasCategoryPerm = UserHasPerm('production_' . $row['category']);
        $hasStagePerm = ($row['stage'] == 1) ? UserHasPerm('production_prep') : UserHasPerm('warehouse_add');
        $rowHasPerm = $hasCategoryPerm && $hasStagePerm;

        $amount_in_wh = 0;
        $item_id_val = $row['item_id'];
        $daily_sql = mysqli_query($conn, "SELECT free_stock FROM statistics_daily WHERE item_id = '$item_id_val'");
        $daily_stat = mysqli_fetch_array($daily_sql);
        if ($daily_stat != null) {
          $amount_in_wh = intval($daily_stat['free_stock']);
        }

        $stage_results[] = [
          'pr_id' => $row['pr_id'],
          'item_id' => $row['item_id'],
          'stage' => intval($row['stage']),
          'category' => $row['category'],
          'db_start' => $row['db_start'],
          'hasperm' => $rowHasPerm,
          'amount_in_wh' => $amount_in_wh
        ];
      }

      usort($stage_results, function($a, $b) {
        return $a['amount_in_wh'] <=> $b['amount_in_wh'];
      });

      $results_by_stage[$stage] = $stage_results;
    }

    $final_results = [];
    $pages_per_stage = [];

    foreach ($results_by_stage as $stage => $stage_data) {
        $total_in_stage = count($stage_data);
        $pages_per_stage[$stage] = $total_in_stage > 0 ? ceil($total_in_stage / $maxperpage) : 1;

        $offset = max(0, ($cpage - 1) * $maxperpage);
        $sliced = array_slice($stage_data, $offset, $maxperpage);
        $final_results = array_merge($final_results, $sliced);
    }

    $maxpage = max($pages_per_stage);

    $response = [
      'result' => 'ok',
      'data' => $final_results,
      'cpage' => $cpage,
      'maxpage' => $maxpage
    ];
    echo json_encode($response);
  } else if (htmlspecialchars($_POST["func"]) == "openDetails") {
    $productionId = htmlspecialchars($_POST['productionId'] ?? '');
    $productionId = mysqli_real_escape_string($conn, $productionId);

    $sql = "SELECT * FROM production_boxing WHERE pr_id = '$productionId'";
    $result = mysqli_query($conn, $sql);
    if (!$result) {
      echo json_encode(['result' => 'Adatbázis hiba']);
      exit;
    }

    $data = [];
    while ($row = mysqli_fetch_assoc($result)) {
      $data[] = $row;
    }

    echo json_encode(['result' => 'ok', 'data' => $data]);

  } else if (htmlspecialchars($_POST["func"]) == "SearchTable") {
    $maxperpage = intval(htmlspecialchars($_POST["perpage"]));
    $cpage = intval(htmlspecialchars($_POST["cpage"]));

    $start_datetime = htmlspecialchars($_POST["start_datetime"]);
    $end_datetime = htmlspecialchars($_POST["end_datetime"]);
    $item_id = htmlspecialchars(str_replace(' ', '+', $_POST['item_id']));

    $addquery = "";
    $isfirst = true;

    if ($cpage == 0) {
      $cpage = 1;
    }
    setcookie("maxperpage", $maxperpage, time() + (86400 * 90), "/");

    if ($start_datetime != "") {
      $timestamp = strtotime($start_datetime);

      $addquery = $addquery." WHERE date_warehouseend > '".$timestamp."'";
      $isfirst = false;

    }

    if ($end_datetime != "") {
      $timestamp = strtotime($end_datetime);

      if ($isfirst) {
        $addquery = $addquery." WHERE date_warehouseend < '".$timestamp."'";
        $isfirst = false;
      } else {
        $addquery = $addquery." and date_warehouseend < '".$timestamp."'";
      }
    }

    if ($item_id != "") {
      if ($isfirst) {
        $addquery = $addquery." WHERE item_id LIKE '%".$item_id."%'";
        $isfirst = false;
      } else {
        $addquery = $addquery." and item_id LIKE '%".$item_id."%'";
      }
    }

    if ($isfirst) {
      $addquery = $addquery." WHERE stage = 0";
      $isfirst = false;
    } else {
      $addquery = $addquery." and stage = 0";
    }

    $table = "production_boxing";

    $sql = mysqli_query($conn,"SELECT COUNT(*) FROM ".$table.$addquery);
    $count = mysqli_fetch_array($sql)[0];

    $addquery = $addquery." ORDER BY date_warehouseend DESC";

    $maxpage = ceil($count / $maxperpage);
    if (!($cpage >= 1 && $cpage <= $maxpage)) {
      $cpage = 1;
    }

    $limit = ($cpage - 1) * $maxperpage;

    $responseStr = '';

    $query = "SELECT pr_id, item_id, db_revenue, date_start, date_warehouseend FROM $table".$addquery." LIMIT $limit, $maxperpage";
    if ($result = $conn->query($query)) {
      while ($c_prod = $result->fetch_assoc()) {

        if ($responseStr != "") {
          $responseStr .= "|%|";
        }
        $responseStr .= $c_prod['item_id'].'/!/'.date("Y. m. d.", $c_prod['date_start']).'/!/'.date("Y. m. d.", $c_prod['date_warehouseend']).'/!/'.$c_prod['db_revenue'].'/!/'.$c_prod['pr_id'];
      }
    }

    echo '{"result": "ok", "data": "'.$responseStr.'", "maxpage": "'.$maxpage.'", "cpage": "'.$cpage.'"}';

  } else if (htmlspecialchars($_POST["func"]) == "RefreshDbStart") {
    $productionId = htmlspecialchars($_POST['productionId'] ?? '');
    $productionId = mysqli_real_escape_string($conn, $productionId);

    $item_id = "";

    $sql = "SELECT item_id FROM production_boxing WHERE pr_id = '$productionId'";
    $result = mysqli_query($conn, $sql);
    if (!$result) {
      echo json_encode(['result' => 'Adatbázis hiba']);
      exit;
    }
    $item_id = mysqli_fetch_assoc($result)['item_id'];

    $annual_result = mysqli_query($conn, "SELECT * FROM statistics_annual WHERE item_id = '$item_id' AND year = (SELECT MAX(year) FROM statistics_annual WHERE item_id = '$item_id') LIMIT 1");
    $statistics_annual = mysqli_fetch_assoc($annual_result);

    $sql = mysqli_query($conn,"SELECT warehouse_total, warehouse_box FROM statistics_daily WHERE item_id = '$item_id'");
    $statistics_daily = mysqli_fetch_array($sql);

    $sql = mysqli_query($conn,"SELECT * FROM system_params");
    $system_params = [];
    while ($row = mysqli_fetch_assoc($sql)) {
      $system_params[$row['param_key']] = $row['param_value'];
    }

    $in_foil_warehouse = intval($statistics_daily['warehouse_total']) - intval($statistics_daily['warehouse_box']);
    $daily_consumption = ($statistics_annual["total_consumption"] ?? $system_params["default_total_consumption"]) / 365;
    $need_to_box = intval($system_params['box_holding']) * $daily_consumption - intval($statistics_daily['warehouse_box']);

    $min_db = min(max(5, ceil($need_to_box)), $in_foil_warehouse);

    $sql = mysqli_query($conn,"UPDATE production_boxing SET db_start = '$min_db' WHERE pr_id = '$productionId'");
    echo json_encode(['result' => 'ok', 'db_start' => $min_db]);

  }

  exit();
}


$WarehouseLocSelect = '<option value="-1">-- Bármely --</option>';
$query = "SELECT DISTINCT location FROM warehouse_structure ORDER BY location ASC";
if ($result = $conn->query($query)) {
  while ($warehouse = $result->fetch_assoc()) {
    $WarehouseLocSelect = $WarehouseLocSelect.'<option value="'.$warehouse["location"].'">'.$warehouse["location"].'</option>';
  }
}
?>

<!DOCTYPE html>
<html lang="hu" dir="ltr">
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="../css/panel.css">
    <script src="../js/feather-icons.js"></script>
    <title>Kezelőfelület</title>
  </head>
  <style>
    .accordion { border: 1px solid #ccc; border-radius: 4px; overflow: hidden; margin-bottom: 30px; }
    .accordion .AppSection { border-bottom: 1px solid #ccc; }
    .accordion .AppSection:last-child { border-bottom: none; }
    .accordion .AppSection .header {
      background: #f7f7f7;
      padding: 12px;
      cursor: pointer;
      user-select: none;
    }
    .accordion .AppSection .header.active { background: #e2e2e2; }
    .accordion .AppSection .information {
      max-height: 0;
      overflow: hidden;
      transition: max-height .3s ease;
      padding: 0 12px;
    }

    button[title]:not([title=""]):disabled {
      cursor: url(../img/CheckCircle.cur),not-allowed;
    }
    .icon {
      position: relative;
      color: var(--panelcolor);
      margin-left: 15px;
      cursor: pointer;
      float: right;
    }
    .icon svg {
      transition: 0.2s;
      filter: drop-shadow(0px 0px 2px #8c8c8c4d);
      width: 24px;
      height: 24px;
    }
    .icon.info svg {
      width: 16px;
      height: 16px;
    }
    .icon:hover svg {
      filter: drop-shadow(0px 0px 5px #8c8c8ce6);
    }
    .icon:active svg {
      filter: drop-shadow(0px 0px 3px #8c8c8ce6);
      opacity: 0.8;
    }

    .kanban-card.highlight {
      background-color: color-mix(in srgb, #FF4D00 5%, #ffffff 95%);
      border: 1px solid;
      border-left: 4px solid;
      border-color: #FF4D00;
    }
  </style>
  <body>
    <?php echo $menuhtml;?>
    <div class="window closed" id="win">
      <div class="topbar">
        <p id="wintitle">Title</p>
        <div class="btn fullscrn" onclick="fullscrn();" id="fullscrnbtn"></div>
        <div class="btn close" onclick="closewin();"></div>
      </div>
      <div class="wapp" id="winapp"><div id="errorDIV"></div></div>
      <div class="loading" id="winloading"></div>
    </div>
    <div class="loadingBG" id="loadingBG"><img src="../img/loading.gif"></div>
    <div class="content">
      <div id="errorDIV" style="z-index: 100; top: 50px; position: fixed; width: calc(100% - 260px);"></div>

      <!-- Tartalmi rész kezdete -->

      <h1>Termékdobozolás</h1>

      <div style="width: 100%; min-height: 85px;">
        <div style="display: inline; float: left;">
          <p>Cikkszám: </p>
          <input type="text" id="filter-item_id" placeholder="Cikkszám..." value="" onkeydown="if (event.keyCode == 13) {SendFilter();}" autocomplete="off" style="width: 147px; height: 17px;">
        </div><div style="display: inline; float: left; padding-left: 15px;">
          <p>Oldalanként: </p>
          <select id="filter-perpage" onchange="SendFilter();"><option value="25">5 db / oszlop</option></select>
        </div><div style="display: inline; float: left; padding-left: 15px;">
          <p style="color: #f5f5f5;">: </p>
          <button onclick="SendFilter();">Szűrés</button>
        </div>
      </div>

      <br clear="all">
        <div style="border-top: solid 1px rgb(211,220,228); width: calc(100% - 15px); height: 0px; margin-top: 15px;"></div>
      <br clear="all">

      <div class="kanban-board">

        <div class="kanban-column" id="production_prep"><div class="column-header">Előkészítés</div></div>
        <div class="kanban-column" id="warehouse_add"><div class="column-header">Raktározás</div></div>

      </div>

      <br clear="all">
      <div>
        <p style="text-align: center; padding-bottom: 30px; color: #333333;"><span onclick="left();" style="cursor: pointer;"><&nbsp;&nbsp;&nbsp;&nbsp;</span><span id="cpage">0</span> / <span id="maxpage">0</span><span onclick="right();" style="cursor: pointer;">&nbsp;&nbsp;&nbsp;&nbsp;></span></p>
      </div>


      <div style="display: <?php echo (UserHasPerm('production_statistics')) ? 'unset' : 'none'?>">

        <br clear="all">
        <div style="border-top: solid 1px rgb(211,220,228); width: 100%; height: 0px; margin-top: 15px;"></div>
        <p style="color: rgb(211,220,228);">Lezárt dobozolási folyamatok áttekintése</p>
        <br clear="all">

        <div style="width: 100%; min-height: 85px;">
          <div style="display: inline; float: left;">
            <p>Cikkszám: </p>
            <input type="text" id="search_filter-item_id" placeholder="Cikkszám..." onkeydown="if (event.keyCode == 13) {SearchSendFilter();}" autocomplete="off" style="width: 147px; height: 17px;">
          </div><div style="display: inline; float: left; padding-left: 15px;">
            <p>Lezárás időtartam kezdet: </p>
            <input type="datetime-local" id="search_filter-start_datetime" onchange="SearchSendFilter();" >
          </div><div style="display: inline; float: left; padding-left: 15px;">
            <p>Lezárás időtartam vége: </p>
            <input type="datetime-local" id="search_filter-end_datetime" onchange="SearchSendFilter();">
          </div><div style="display: inline; float: left; padding-left: 15px;">
            <p>Oldalanként: </p>
            <select id="search_filter-perpage" onchange="SearchSendFilter();"><option value="25">25 db / oldal</option></select>
          </div><div style="display: inline; float: left; padding-left: 15px;">
            <p style="color: #f5f5f5;">: </p>
            <button onclick="SearchSendFilter();">Szűrés</button>
          </div>
        </div>

        <br clear="all">
        <div style="border-top: solid 1px rgb(211,220,228); width: 100%; height: 0px; margin-top: 15px;"></div>
        <br clear="all">

        <div style="width: 100%; margin-left: 10px; margin-top: 10px; display: inline; float: left;">
          <div class="tables" style="width: 100%">
            <table id="search_table">
              <thead>
                <tr style="top: 0px; position: sticky; z-index: 1;">
                  <th>Cikkszám</th>
                  <th>Kezdési dátum</th>
                  <th>Lezárás dátum</th>
                  <th>Dobozolt darabszám <small style="opacity: 0.8;"><small>Dobozszám</small></small></th>
                  <th style="width: 100px;">Adatlap</th>
                </tr>
              </thead>
            <tbody>
            </tbody>
          </table>
          </div>
        </div>

        <br clear="all">
        <div>
          <p style="text-align: center; padding-bottom: 50px; color: #333333;"><span onclick="SearchLeft();" style="cursor: pointer;"><&nbsp;&nbsp;&nbsp;&nbsp;</span><span id="search_cpage">0</span> / <span id="search_maxpage">0</span><span onclick="SearchRight();" style="cursor: pointer;">&nbsp;&nbsp;&nbsp;&nbsp;></span></p>
        </div>

      </div>

      <br clear="all"><br><br>

      <!-- Tartalmi rész vége -->

    </div>
    <script src="../js/default.js" type="text/javascript"></script>
    <script type="text/javascript">

    function LoadFilter() {
      const body = 'func=filter';
      get_POST_information("boxing.php", body, function(text) {
        let response = JSON.parse(text);
        if (response.result == "ok") {
          document.getElementById('filter-perpage').innerHTML = response.perpage;
          LoadTable();
        } else {
          GenerateAlerts("error", response.result);
        }
      }, function() {
        GenerateAlerts("error", "Hálózati hiba!");
      });
    }
    function SendFilter() {
      document.getElementById('cpage').innerHTML = '1';
      LoadTable();
    }
    function left() {
      var cpage = document.getElementById("cpage").innerHTML;
      if ((parseInt(cpage) - 1) >= 1) {
        document.getElementById("cpage").innerHTML = parseInt(cpage) - 1;
        LoadTable();
      }
    }
    function right() {
      var cpage = document.getElementById("cpage").innerHTML;
      var maxpage = document.getElementById("maxpage").innerHTML;
      if ((parseInt(cpage) + 1) <= parseInt(maxpage)) {
        document.getElementById("cpage").innerHTML = parseInt(cpage) + 1;
        LoadTable();
      }
    }
    function LoadTable() {
      Loading();
      var item_id = document.getElementById('filter-item_id').value;
      var perpage = document.getElementById("filter-perpage").value;
      var cpage = document.getElementById("cpage").innerHTML;

      const body = 'func=table&perpage=' + perpage + '&cpage=' + cpage + '&item_id=' + encodeURIComponent(item_id).replace(/%20/g, '+');

      get_POST_information("boxing.php", body, function(text) {
        Loading(false);
        let response = JSON.parse(text);
        if (response.result == "ok") {
          document.getElementById("cpage").innerHTML = response.cpage;
          document.getElementById("maxpage").innerHTML = response.maxpage;

          const stageHeaders = {
            1: 'Előkészítés',
            2: 'Raktározás'
          };
          const stageContainers = {
            1: 'production_prep',
            2: 'warehouse_add'
          };

          for (let i = 1; i <= 2; i++) {
            const container = document.getElementById(stageContainers[i]);
            if (container) {
              container.innerHTML = '';
              const headerEl = document.createElement('div');
              headerEl.className = 'column-header';
              headerEl.textContent = stageHeaders[i];
              container.appendChild(headerEl);
            }
          }

          response.data.forEach(item => {
            const stage = parseInt(item.stage);
            const containerId = stageContainers[stage];
            const container = document.getElementById(containerId);

            if (container) {
              const cardElement = document.createElement('div');
              cardElement.className = 'kanban-card';
              cardElement.style.borderLeftColor = '#B0916E';
              if (item.hasperm == false) {
                cardElement.style.opacity = '0.5';
                cardElement.style.boxShadow = 'unset';
              }

              var icon = '';
              if (item.amount_in_wh < 1) {
                icon = `<i class="icon info" title='Nincs szabad raktáron a cikkszámból!' style="color: #FF4D00;"><i data-feather='alert-octagon'></i></i>`;
              }

              if (item.amount_in_wh < 0) {
                cardElement.className += ' highlight';
              }

              cardElement.innerHTML = `
                <div class="card-title">Cikkszám: ${item.item_id} ${icon}</div>
                <div class="card-subtitle">
                  <span class="subtitle-left" style="color: #B0916E;"></span>
                  <span class="subtitle-right"><span style="color: #B0916E;">${item.db_start}</span> <span style="opacity: 0.8; font-size: 12px;">pár</span></span>
                </div>
                <button class="card-button" onclick="openDetails('${item.pr_id}', '${item.category}')">Részletek</button>
              `;

              container.appendChild(cardElement);
            }

            feather.replace();
          });

        } else {
          GenerateAlerts("error", response.result);
        }
      }, function() {
        Loading(false);
        GenerateAlerts("error", "Hálózati hiba!");
      });

    }
    LoadFilter();

    var CurrentProductionId = '';
    var CurrentItemID = '';

    var max_amount = 0;
    var current_amount = 0;

    var IsNoWarehouse = false;
    var IsWarehouse = false;
    function openDetails(productionId) {
      CurrentProductionId = productionId;
      openwin();
      wintitle.innerHTML = "Gyártási folyamat";
      winapp.innerHTML = '<div id="errorDIV"></div>';
      const filePath = '../managers/template/boxing_prod.html';

      const body = 'func=openDetails&productionId=' + productionId;
      get_POST_information("boxing.php", body, function(text) {
        let response = JSON.parse(text);
        if (response.result == "ok") {

          fetch(filePath, { cache: 'no-store' })
            .then(response => {
              if (!response.ok) throw new Error('Nem sikerült betölteni a template-et.');
              return response.text();
            })
            .then(templateHtml => {
              const tempDiv = document.createElement('div');
              var EditedHTML = templateHtml;

              Object.keys(response.data[0]).forEach(key => {
                const val = response.data[0][key];
                if (val != null) {
                  if (/^\d{10}$/.test(val)) {
                    const d = new Date(+val * 1000);
                    EditedHTML = EditedHTML.replaceAll('$[' + key + ']', `${d.getFullYear()}.${('0'+(d.getMonth()+1)).slice(-2)}.${('0'+d.getDate()).slice(-2)}. ${('0'+d.getHours()).slice(-2)}:${('0'+d.getMinutes()).slice(-2)}:${('0'+d.getSeconds()).slice(-2)}`);
                  } else EditedHTML = EditedHTML.replaceAll('$[' + key + ']', val);
                } else EditedHTML = EditedHTML.replaceAll('$[' + key + ']', '');
              });

              EditedHTML = EditedHTML.replaceAll('$[filter-location]', `<?php echo $WarehouseLocSelect;?>`);

              tempDiv.innerHTML = EditedHTML;
              IsNoWarehouse = false;
              IsWarehouse = false;
              Object.keys(response.data[0]).forEach(key => {
                const els = tempDiv.querySelectorAll('#' + key);
                const val = response.data[0][key];
                els.forEach(el => {

                  if (['INPUT','TEXTAREA','SELECT'].includes(el.tagName)) {
                    el.value = val;
                  } else {
                    if (/^\d{10}$/.test(val)) {
                      const d = new Date(+val * 1000);
                      el.textContent = `${d.getFullYear()}.${('0'+(d.getMonth()+1)).slice(-2)}.${('0'+d.getDate()).slice(-2)}. ${('0'+d.getHours()).slice(-2)}:${('0'+d.getMinutes()).slice(-2)}:${('0'+d.getSeconds()).slice(-2)}`;
                    } else el.textContent = val;
                  }

                  if (key == "date_warehouseend" && !(val == null || val.length < 1)) {
                    IsNoWarehouse = true;
                  }
                  if (key == "date_start" && !(val == null || val.length < 1)) {
                    IsWarehouse = true;
                  }
                  if (key == "item_id") {
                    CurrentItemID = val;
                  } else if (key == "db_start") {
                    max_amount = parseInt(val);
                  } else if (key == "db_revenue") {
                    current_amount = parseInt(val);
                  }
                });
              });

              while (tempDiv.firstChild) winapp.appendChild(tempDiv.firstChild);

              if (IsNoWarehouse) {
                document.getElementById("WarehouseAdd").style.display = 'none';
              }

              const allFilled = inputs => inputs.every(i => i.value.trim() !== '');

              function updateVisibility() {
                const sections = Array.from(document.querySelectorAll('.AppSection'));
                const first = sections[0];
                const startHidden = first.querySelector('input#date_start[type="hidden"]');
                if (!startHidden || !startHidden.value.trim()) {
                  sections.forEach((s, i) => {
                    s.style.display = i === 0 ? '' : 'none';
                  });
                  return;
                }
                let allow = true;
                sections.forEach((section, idx) => {
                  if (idx === 0) {
                    section.style.display = '';
                    return;
                  }
                  if (!allow) {
                    section.style.display = 'none';
                    return;
                  }
                  const endHidden = section.querySelector('input[type="hidden"][id^="date_"][id$="end"]');
                  const prependHidden = section.querySelector('input#date_prepend[type="hidden"]');
                  const orderedHidden = document.querySelector('input#ordered[type="hidden"]');

                  section.style.display = '';

                  if (prependHidden) {
                    if (orderedHidden && !orderedHidden.value.trim()) allow = false;
                  }
                  if (endHidden && !endHidden.value.trim()) allow = false;
                });
              }

              function openFirstEmptySpan() {
                const sections = Array.from(document.querySelectorAll('.AppSection'));
                let first = null;
                for (const section of sections) {
                  const span = section.querySelector('.header span');
                  if (span && span.textContent.trim() === '') {
                    first = section;
                    break;
                  }
                }
                if (first) {
                  const hdr = first.querySelector('.header');
                  const cnt = first.querySelector('.information');
                  document.querySelectorAll('.AppSection').forEach(s => {
                    s.querySelector('.header').classList.remove('active');
                    if (s.querySelector('.information')) {
                      s.querySelector('.information').style.maxHeight = null;
                      s.querySelector('.information').style.padding = null;
                    }
                  });
                  hdr.classList.add('active');
                  if (cnt) {
                    cnt.style.maxHeight = cnt.scrollHeight + 'px';
                    cnt.style.padding = '12px';
                  }
                }
              }

              document.querySelectorAll('.AppSection').forEach(section => {
                const inputs = Array.from(section.querySelectorAll('input:not([type="hidden"]), textarea, select')).filter(el => !el.closest('#WarehouseAdd'));
                const hiddens = Array.from(section.querySelectorAll('input[type="hidden"]')).filter(el => !el.closest('#WarehouseAdd'));
                const startHidds = hiddens.filter(h => h.id.includes('date_') && !h.id.endsWith('end'));
                const stopHidds = hiddens.filter(h => h.id.includes('date_') && h.id.endsWith('end'));
                const specialIDs = ['date_start','ordered','date_warehouseend','date_revenue'];

                function setLocked(lock) {
                  inputs.forEach(i => {
                    i.disabled = lock;
                    i.readOnly = lock;
                  });
                }

                function update() {
                  const filled = allFilled(inputs);
                  const specialHidden = specialIDs
                    .map(id => section.querySelector(`input#${id}[type="hidden"]`))
                    .find(h => h && !h.closest('#WarehouseAdd'));
                  if (specialHidden) {
                    const btn = section.querySelector(`#${specialHidden.id}_btn`);
                    if (specialHidden.value.trim() !== '') {
                      setLocked(true);
                      if (btn) btn.disabled = true;
                    } else {
                      setLocked(false);
                      if (btn) btn.disabled = !filled;
                    }
                    updateVisibility();
                    return;
                  }

                  const started = startHidds.some(h => h.value.trim() !== '');
                  startHidds.forEach(h => {
                    const btn = section.querySelector(`#${h.id}_btn`);
                    if (btn) btn.disabled = started;
                  });
                  setLocked(!started);

                  stopHidds.forEach(h => {
                    const btn = section.querySelector(`#${h.id}_btn`);

                    if (h.value.trim() != '') {
                      if (btn) btn.disabled = true;
                      setLocked(true);
                    } else if (!inputs.length) {
                      if (btn) btn.disabled = !started;
                    } else {
                      if (btn) btn.disabled = !started || !filled;
                    }
                  });


                  updateVisibility();
                }

                inputs.forEach(i => {
                  i.readOnly = false;
                  i.oninput = update;
                  i.onkeydown = update;
                });

                const hdr = section.querySelector('.header');
                const cnt = section.querySelector('.information');
                hdr.addEventListener('click', () => {
                  document.querySelectorAll('.AppSection').forEach(s => {
                    s.querySelector('.header').classList.remove('active');
                    s.querySelector('.information').style.maxHeight = null;
                    s.querySelector('.information').style.padding = null;
                  });
                  hdr.classList.add('active');
                  cnt.style.maxHeight = cnt.scrollHeight + 'px';
                  cnt.style.padding = '12px';
                });

                update();

                document.getElementById("filter-amount").value = (max_amount - current_amount);
              });

              updateVisibility();
              openFirstEmptySpan();
              feather.replace();
              if (!IsNoWarehouse && IsWarehouse) {
                SearchWarehouse();
                CheckCanEnd();
              }
            })
            .catch(err => {
              GenerateAlerts("error", 'Hiba a betöltéskor: ' + err.message);
            });

        }
      }, function() {
        GenerateAlerts("error", "Hálózati hiba!");
      });
    }
    function CheckCanEnd() {
      if (!IsNoWarehouse && IsWarehouse) {
        if (max_amount <= current_amount) {
          document.getElementById("date_warehouseend_btn").disabled = false;
        } else {
          document.getElementById("date_warehouseend_btn").disabled = true;
        }
      }
    }

    async function SendUpdateProductionParameter(productionId, json) {
      try {
        const formData = new FormData();
        formData.append('func', 'UpdateProdPar');
        formData.append('productionId', productionId);
        formData.append('category', 'boxing');
        formData.append('data', JSON.stringify(json));

        const response = await fetch('production.php', {
          method: 'POST',
          body: formData
        });

        const result = await response.text();
        return result;
      } catch (error) {
        console.error('Hiba:', error);
        return null;
      }
    }
    function UpdateProductionParameter(dataArray, silent = false) {
      if (!silent) { Loading(); }
      SendUpdateProductionParameter(CurrentProductionId, dataArray).then(result => {
        if (result == "ok" || result == "reload - ok") {
          if (!silent) {
            openDetails(CurrentProductionId);
            Loading(false);
            if (result == "reload - ok") {
              SendFilter();
            }
          }
        } else {
          GenerateAlerts("error", result);

          if (result == "Nem lehet ennyi pár terméket bedobozolni! Nincs elegendő pár a fóliás raktárban.") {
            RefreshDbStart(CurrentProductionId);
          } else {
            if (!silent) { Loading(false); }
          }
        }
      });
    }

    function ProdStart() {
      const dataArray = [
        {name: "item_id", value: document.querySelector('input[id="item_id"]').value },
        {name: "db_start", value: document.querySelector('input[id="db_start"]').value },
        {name: "date_start", value: "$[TIMESTAMP]"},
        {name: "stage", value: '2' },
      ];
      UpdateProductionParameter(dataArray);
    }
    function WarehouseEnd() {
      const dataArray = [
        {name: "stage", value: '0' },
        {name: "date_warehouseend", value: "$[TIMESTAMP]"}
      ];
      UpdateProductionParameter(dataArray);

      RefreshDailyStat();
    }

    function RefreshDbStart(productionId) {
      const body = 'func=RefreshDbStart&productionId=' + productionId;
      get_POST_information("boxing.php", body, function(text) {
        let response = JSON.parse(text);
        if (response.result == "ok") {
          GenerateAlerts("info", "Ajánlott mennyiség (" + response.db_start + ") frissítve!");
          Loading(false);
          openDetails(productionId);
        } else {
          GenerateAlerts("error", response.result);
        }
      }, function() {
        GenerateAlerts("error", "Hálózati hiba!");
      });
    }

    var InSavingProgress = [];
    /* Raktározás */
    function SearchWarehouse() {
      Loading();

      var item_id = CurrentItemID;
      var amount = document.getElementById("filter-amount").value;

      if ((max_amount - current_amount) < parseInt(amount)) {
        GenerateAlerts("warning", "Nem szükséges ennyi dobozt eltenni!");
        Loading(false);
        return;
      }

      if (parseInt(amount) == 0) {
        Loading(false);
        return;
      }

      const amountNum = parseInt(amount);
      const manualPickData = [
        {
          item_id: item_id,
          amount: amountNum,
          primary_source: 1,
          amount_type: 0
        }
      ];

      var needs = [];
      var CanCompleteAmount = 0;
      const order_body = 'func=Generatepicking_list&manual_pick=' + JSON.stringify(manualPickData);
      get_POST_information("wh_orders.php", order_body, function(text) {
        let response = JSON.parse(text);
        if (response.result == "ok") {
          document.getElementById("result_div").style.display = "unset";
          document.getElementById("result_div").style.visibility = "visible";
          var table = document.getElementById('table').getElementsByTagName('tbody')[0];
          table.innerHTML = "";

          response.all_picking_lists.forEach(function(group) {
            group.picking_list.forEach(function(item) {
              if (String(item.wid).charAt(0) == "F" && item.type == "foil") {

                var RowID = "RowID:" + item.item_id + "-" + item.amount + "-" + MD5(item.location) + "-" + String(item.pos).toString().replace(/\n/g, '') + "-" + MD5(group.overal_order_id);

                var BlankRow = table.insertRow();
                var newBlankCell = BlankRow.insertCell(0);
                newBlankCell.colSpan = 4;
                newBlankCell.setAttribute('style', 'background-color: var(--bgcolor); border: none;');

                var newRow = table.insertRow();
                var newCell_ItemID = newRow.insertCell(0);
                var newCell_Pos = newRow.insertCell(1);
                var newCell_Amount = newRow.insertCell(2);
                var newCell_Action = newRow.insertCell(3);

                newRow.id = RowID;

                newCell_ItemID.innerHTML = item.item_id;
                newCell_ItemID.setAttribute('style', 'text-align: center; background-color: #f2f2f2; border: none; color: #818181; width: 100px;');

                newCell_Pos.innerHTML = item.pos;
                newCell_Pos.setAttribute('style', 'cursor: pointer; font-weight: bold; padding: 8px 16px;');
                newCell_Pos.title = item.location + ' / ' + item.pos;
                newCell_Pos.setAttribute('ondblclick', 'CreateAlertBox("Raktár hely", "<p>"+ this.title +"</p>");');

                newCell_Amount.innerHTML = item.amount;
                newCell_Amount.setAttribute('style', 'font-weight: bold; padding: 8px 16px;');

                newCell_Action.innerHTML = `<span style="opacity: 0.8"> - </span>`;

                var NewNeeds = {
                  RowID: RowID,
                  Amount: item.amount,
                  wid: String(item.wid).replace(/F/g, "")
                }

                CanCompleteAmount += parseInt(item.amount);

                needs.push(NewNeeds);
              }
            });
          });

          if (needs.length != 0) {
            GenerateWarehouseAdd(CanCompleteAmount, needs);
          } else {
            Loading(false);
            GenerateAlerts("info", "Nincs fóliás raktárban elegendő a kisedéshez!");
          }

        } else {
          Loading(false);
          GenerateAlerts("error", response.message);
        }
      }, function() {
        Loading(false);
        GenerateAlerts("error", "Hálózati hiba!");
      });

    }
    function GenerateWarehouseAdd(amount, needs) {
      var item_id = CurrentItemID;
      var location = document.getElementById("filter-location").value;

      const body = 'func=SearchWarehouse&item_id=' + encodeURIComponent(item_id).replace(/%20/g, '+') + '&location=' + encodeURIComponent(location).replace(/%20/g, '+') + '&amount=' + amount;
      get_POST_information("wh_add.php", body, function(text) {
        let response = JSON.parse(text);
        Loading(false);
        if (response.result == "ok") {

          const data = response.toplace;
          data.forEach(item => {
              const position = item.position;
              var PlaceCode = item.warehouse_code + NumberToABC(position.split(":")[0]) + padWithZero(position.split(":")[1]);
              const placedAmount = parseInt(item.placed);

              let remainingFromItem = placedAmount;

              while (needs.length > 0 && remainingFromItem > 0) {
                if (needs[0].Amount >= remainingFromItem) {
                  needs[0].Amount -= remainingFromItem;
                  createNewRow(item, remainingFromItem, position, PlaceCode, needs[0], item_id);
                  remainingFromItem = 0;

                  if (needs[0].Amount == 0) {
                    needs.shift();
                  }
                } else {
                  const currentNeed = { ...needs[0] };
                  createNewRow(item, needs[0].Amount, position, PlaceCode, currentNeed, item_id);
                  remainingFromItem -= needs[0].Amount;
                  needs.shift();
                }
              }
          });


          if (response.amount_left != 0) {
            GenerateAlerts("warning", "Nem sikerült elhelyezni " + response.amount_left + " elemet!", false);
          }

          setTimeout(() => {
            document.getElementById('WarehouseSection').style.maxHeight = document.getElementById('WarehouseSection').scrollHeight + 'px';
            console.log(document.getElementById('WarehouseSection').scrollHeight);
          }, 5);

        } else {
          GenerateAlerts("error", response.result);
        }
      }, function() {
        Loading(false);
        GenerateAlerts("error", "Hálózati hiba!");
      });
    }
    function createNewRow(item, amount, position, PlaceCode, motherNeed, item_id) {
      var MotherRowID = String(motherNeed.RowID).slice(6);
      const SearchRow = document.querySelector(`#RowID\\:${CSS.escape(MotherRowID)}`);

      var newRow = document.createElement('tr');
      var newCell_ItemID = newRow.insertCell(0);
      var newCell_Pos = newRow.insertCell(1);
      var newCell_Amount = newRow.insertCell(2);
      var newCell_Action = newRow.insertCell(3);

      var RowID = item_id+'-'+amount+'-'+item.warehouse_id+'-'+position+'-'+motherNeed.wid;
      newRow.id = RowID;

      newCell_ItemID.innerHTML = item_id;
      newCell_ItemID.setAttribute('style', 'text-align: center; background-color: #f2f2f2; border: none; color: #818181; width: 100px;');

      newCell_Pos.innerHTML = `<span>↳</span> ${PlaceCode}`;
      newCell_Pos.style.cursor = "pointer";
      newCell_Pos.title = item.warehouse_loc + " / " + item.warehouse_name + " / " + NumberToABC(position.split(":")[0]) + ":" + padWithZero(position.split(":")[1]);
      newCell_Pos.setAttribute('ondblclick', 'CreateAlertBox("Raktár hely", "<p>"+ this.title +"</p>");');
      newCell_Pos.style.padding = "8px 16px";

      newCell_Amount.innerHTML = amount;
      newCell_Amount.style.padding = "8px 16px";

      newCell_Action.innerHTML = `<span style='color: var(--panelcolor); cursor: pointer;' onclick='PlaceIntoWarehouse("${item_id}", "${amount}", "${item.warehouse_id}", "${position}", "${RowID}", "${motherNeed.wid}")'>Elhelyeztem</span>`;

      if (SearchRow) {
        SearchRow.parentNode.insertBefore(newRow, SearchRow.nextSibling);
      }
    }
    function PlaceIntoWarehouse(item_id, placed, warehouse_id, position, RowID = "", FoilWID) {
      if (InSavingProgress.includes(RowID)) {
        GenerateAlerts("info", "Mentés folyamatban...");
      } else {
        InSavingProgress.push(RowID);
        var reason = encodeURIComponent("Production#boxing" + "#" + CurrentProductionId).replace(/%20/g, '+');
        const body = 'func=PlaceIntoWarehouse&item_id=' + encodeURIComponent(item_id).replace(/%20/g, '+') + '&placed=' + placed + '&warehouse_id=' + warehouse_id + '&position=' + position + '&reason=' + reason;

        get_POST_information("wh_add.php", body, function(text) {
          let response = JSON.parse(text);
          if (response.result == "ok") {
            if (RowID != "") {
              const index = InSavingProgress.indexOf(RowID);
              if (index > -1) {
                InSavingProgress.splice(index, 1);
              }
              document.getElementById(RowID).classList.add('strike-row');
              EditFoilItem(-placed, -placed, FoilWID);
              current_amount += parseInt(placed);
              document.getElementById('db_revenue').innerHTML = current_amount;
              document.getElementById("filter-amount").value = (max_amount - current_amount);
              CheckCanEnd();
            }
          } else {
            GenerateAlerts("error", response.result);
          }
        }, function() {
          Loading(false);
          GenerateAlerts("error", "Hálózati hiba!");
        });
      }
    }

    function EditFoilItem(left, right, wid) {
      const body = 'func=EditFoilItem&left=' + left + '&right=' + right + '&wid=' + wid;
      get_POST_information("warehouse.php", body, function(text) {
        let response = JSON.parse(text);
        if (response.result != "ok") {
          GenerateAlerts("error", response.result);
        }
      }, function() {
        GenerateAlerts("error", "Hálózati hiba!");
      });
    }

    /* Katalógus lekérő */
    function OpenCatalogue(title, parameters) {
      const body = 'func=OpenCatalogue&param=' + encodeURIComponent(parameters).replace(/%20/g, '+') + '&item_id=' + encodeURIComponent(CurrentItemID).replace(/%20/g, '+');
      get_POST_information("production.php", body, function(text) {
        let response = JSON.parse(text);
        if (response.result == "ok") {

          var html = ``;
          response.response_arr.forEach(function(item) {
            html += `<p><b>${item.name}</b>:<br> <span style="color: var(--panelcolor);">${item.value}</span></p>`;
          });

          CreateAlertBox(title, html);

        } else {
          GenerateAlerts("error", response.result);
        }
      }, function() {
        GenerateAlerts("error", "Hálózati hiba!");
      });
    }

    /* Folyamatos mentés */
    function SaveSingleParam(name, id) {
      const dataArray = [ {name: name, value: document.querySelector('input[id="' + id + '"]').value } ];
      UpdateProductionParameter(dataArray, true);
    }

    function RefreshDailyStat() {
      get_POST_information("../managers/statistics.php?type=daily&item_id=" + encodeURIComponent(CurrentItemID).replace(/%20/g, '+'), '', function(text) {

      }, function() {
        GenerateAlerts("error", "Hálózati hiba!");
      });
    }

    /* Lezártak keresője */
    function SearchLoadFilter() {
      const body = 'func=filter';
      get_POST_information("wh_remove.php", body, function(text) {
        let response = JSON.parse(text);
        if (response.result == "ok") {
          document.getElementById('search_filter-perpage').innerHTML = response.perpage;
          SearchLoadTable();
        } else {
          GenerateAlerts("error", response.result);
        }
      }, function() {
        GenerateAlerts("error", "Hálózati hiba!");
      });
    }
    function SearchSendFilter() {
      document.getElementById('search_cpage').innerHTML = '1';
      SearchLoadTable();
    }
    function SearchLeft() {
      var cpage = document.getElementById("search_cpage").innerHTML;
      if ((parseInt(cpage) - 1) >= 1) {
        document.getElementById("search_cpage").innerHTML = parseInt(cpage) - 1;
        SearchLoadTable();
      }
    }
    function SearchRight() {
      var cpage = document.getElementById("search_cpage").innerHTML;
      var maxpage = document.getElementById("search_maxpage").innerHTML;
      if ((parseInt(cpage) + 1) <= parseInt(maxpage)) {
        document.getElementById("search_cpage").innerHTML = parseInt(cpage) + 1;
        SearchLoadTable();
      }
    }

    function SearchLoadTable() {
      Loading();
      var item_id = document.getElementById("search_filter-item_id").value;
      var start_datetime = document.getElementById("search_filter-start_datetime").value;
      var end_datetime = document.getElementById("search_filter-end_datetime").value;

      var perpage = document.getElementById("search_filter-perpage").value;
      var cpage = document.getElementById("search_cpage").innerHTML;

      const body = 'func=SearchTable&perpage=' + perpage + '&cpage=' + cpage + '&item_id=' + encodeURIComponent(item_id).replace(/%20/g, '+') + '&start_datetime=' + encodeURIComponent(start_datetime).replace(/%20/g, '+') +'&end_datetime=' + encodeURIComponent(end_datetime).replace(/%20/g, '+');
      get_POST_information("boxing.php", body, function(text) {
        Loading(false);
        let response = JSON.parse(text);
        if (response.result == "ok") {
          var table = document.getElementById('search_table').getElementsByTagName('tbody')[0];
          table.innerHTML = "";
          document.getElementById("search_cpage").innerHTML = response.cpage;
          document.getElementById("search_maxpage").innerHTML = response.maxpage;

          var tableresponse = response.data;
          if (tableresponse != "") {
            if (tableresponse.includes("|%|")) {
              var tablearr = tableresponse.split("|%|");
            } else {
              var tablearr = [tableresponse];
            }
            for (var i = 0; i < tablearr.length; i++) {
              var datas = tablearr[i].split("/!/");

              var newRow = table.insertRow();
              var newCell_1 = newRow.insertCell(0);
              var newCell_2 = newRow.insertCell(1);
              var newCell_3 = newRow.insertCell(2);
              var newCell_4 = newRow.insertCell(3);
              var newCell_5 = newRow.insertCell(4);

              newCell_1.innerHTML = datas[0];
              newCell_2.innerHTML = datas[1];
              newCell_3.innerHTML = datas[2];
              newCell_4.innerHTML = datas[3];
              newCell_5.innerHTML = '<a style="cursor: pointer;" onclick="openDetails(\''+datas[4]+'\')">Részletek</button>';
            }
          }
        } else {
          GenerateAlerts("error", response.result);
        }
      }, function() {
        Loading(false);
        GenerateAlerts("error", "Hálózati hiba!");
      });
    }

    SearchLoadFilter();

    </script>
  </body>
</html>
