<?php

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

if (!(UserHasPerm('return_goods'))) {
  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'>25 db / oldal</option>
    <option value='50'>50 db / oldal</option>
    <option value='100'>100 db / oldal</option>
    <option value='250'>250 db / oldal</option>
    <option value='500'>500 db / oldal</option>
    <option value='1000'>1000 db / oldal</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"]) == "LoadTable") {
    $maxperpage = intval(htmlspecialchars($_POST["perpage"]));
    $cpage = intval(htmlspecialchars($_POST["cpage"]));

    $name = htmlspecialchars($_POST["name"]);
    $track_id = htmlspecialchars($_POST["track_id"]);
    $item_id = htmlspecialchars(str_replace(' ', '+', $_POST['item_id']));
    $date = htmlspecialchars($_POST["date"]);
    $is_saved = htmlspecialchars($_POST["is_saved"]);

    $addquery = "";
    $isfirst = true;

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

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

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

    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 ($date != "") {
      if ($isfirst) {
        $addquery = $addquery." WHERE DATE(FROM_UNIXTIME(return_date)) = '".$date."'";
        $isfirst = false;
      } else {
        $addquery = $addquery." and DATE(FROM_UNIXTIME(return_date)) = '".$date."'";
      }
    }

    if ($is_saved != "") {
      if ($is_saved == "1") {
        if ($isfirst) {
          $addquery = $addquery." WHERE is_saved = '1'";
          $isfirst = false;
        } else {
          $addquery = $addquery." and is_saved = '1'";
        }
      } else {
        if ($isfirst) {
          $addquery = $addquery." WHERE COALESCE(is_saved, 0) != 1";
          $isfirst = false;
        } else {
          $addquery = $addquery." and COALESCE(is_saved, 0) != 1";
        }
      }
    }

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

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

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

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

    $responseStr = '';

    $query = "SELECT return_id, name, COALESCE(NULLIF(order_id,''), pack_id) as the_id, item_id, return_date, is_saved FROM return_goods".$addquery." LIMIT $limit, $maxperpage";
    if ($result = $conn->query($query)) {
      while ($c_prod = $result->fetch_assoc()) {

        if ($responseStr != "") {
          $responseStr .= "|%|";
        }
        $responseStr .= $c_prod['return_id'].'/!/'.$c_prod['name'].'/!/'.$c_prod['the_id'].'/!/'.$c_prod['item_id'].'/!/'.date("Y. m. d.", $c_prod['return_date']).'/!/'.$c_prod['is_saved'];
      }
    }

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

  } else if (htmlspecialchars($_POST["func"]) == "CreateReturn") {
    $name = 'temp_'.bin2hex(random_bytes(24));
    $sql = mysqli_query($conn,"INSERT INTO return_goods(name) VALUES ('$name')");
    $rid = mysqli_insert_id($conn);

    $json = json_encode(array(
        'return_id' => $rid,
        'result' => 'ok'
    ));

    echo $json;
  } else if (htmlspecialchars($_POST["func"]) == "OpenRetun") {
    $rid = htmlspecialchars($_POST["return_id"]);

    $sql = mysqli_query($conn,"SELECT * FROM return_goods WHERE return_id = '$rid'");
    $data = mysqli_fetch_array($sql);

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

    echo $json;
  } else if (htmlspecialchars($_POST["func"]) == "AutoSaveReturn") {
    $return_id = htmlspecialchars($_POST["return_id"]);
    $param = htmlspecialchars($_POST["param"]);
    $value = htmlspecialchars($_POST["value"]);

    $params = ['name', 'item_id', 'pack_id', 'order_id', 'return_reason', 'is_withdraw', 'cancellation_invoice', 'is_scrap', 'is_warehoused', 'reason', 'note', 'return_date', 'is_saved'];
    if (!(!empty($param) && in_array($param,$params))) {
      echo json_encode(array('result' => 'Hibás paraméter lett megadva!'));
      exit();
    }

    if ($param == "return_date" && $value != "") {
      $value = strtotime($value);
    }

    if ($param == "item_id" && $value != "") {
      $sql = mysqli_query($conn,"SELECT item_id FROM pr_parameters WHERE item_id = '$value'");
      $data = mysqli_fetch_array($sql);
      if ($data != null) {
        $value = $data['item_id'];
      } else {
        echo json_encode(array('result' => 'Nem létező cikkszámot adott meg!'));
        exit();
      }
    }

    if ($return_id != "") {
      $sql = mysqli_query($conn,"UPDATE return_goods SET $param='$value' WHERE return_id = '$return_id'");
    } else {
      $sql = mysqli_query($conn, "INSERT INTO return_goods($param) VALUES ('$value')");
      $return_id = mysqli_insert_id($conn);
    }

    echo json_encode(array('result' => 'ok', 'return_id' => $return_id));

  } else if (htmlspecialchars($_POST["func"]) == "SaveReturn") {
    $return_id = htmlspecialchars($_POST["return_id"]);

    $name = htmlspecialchars($_POST["name"]);
    $return_date = htmlspecialchars($_POST["return_date"]);
    $item_id = htmlspecialchars($_POST["item_id"]);
    $pack_id = htmlspecialchars($_POST["pack_id"]);
    $order_id = htmlspecialchars($_POST["order_id"]);
    $return_reason = htmlspecialchars($_POST["return_reason"]);
    $is_withdraw = htmlspecialchars($_POST["is_withdraw"]);
    $cancellation_invoice = htmlspecialchars($_POST["cancellation_invoice"]);
    $is_scrap = htmlspecialchars($_POST["is_scrap"]);
    $is_warehoused = htmlspecialchars($_POST["is_warehoused"]);
    $reason = htmlspecialchars($_POST["reason"]);
    $note = htmlspecialchars($_POST["note"]);

    if ($return_date != "") {
      $return_date = strtotime($return_date);
    }

    if ($item_id != "") {
      $sql = mysqli_query($conn,"SELECT item_id FROM pr_parameters WHERE item_id = '$item_id'");
      $data = mysqli_fetch_array($sql);
      if ($data != null) {
        $item_id = $data['item_id'];
      } else {
        echo json_encode(array('result' => 'Nem létező cikkszámot adott meg!'));
        exit();
      }
    }

    if ($return_id == "") {
      $sql = mysqli_query($conn, "INSERT INTO return_goods(name) VALUES ('$name')");
      $return_id = mysqli_insert_id($conn);
    }

    $sql = mysqli_query($conn,"UPDATE return_goods SET
      name = '$name',
      item_id = '$item_id',
      pack_id = '$pack_id',
      order_id = '$order_id',
      return_reason = '$return_reason',
      is_withdraw = '$is_withdraw',
      cancellation_invoice = '$cancellation_invoice',
      is_scrap = '$is_scrap',
      is_warehoused = '$is_warehoused',
      reason = '$reason',
      note = '$note'
    WHERE return_id = '$return_id'");

    if ($return_date != "") {
      $sql = mysqli_query($conn,"UPDATE return_goods SET return_date = $return_date WHERE return_id = '$return_id'");
    } else {
      $sql = mysqli_query($conn,"UPDATE return_goods SET return_date = NULL WHERE return_id = '$return_id'");
    }

    echo json_encode(array('result' => 'ok', 'return_id' => $return_id));

  }

  exit();
}

?>

<!DOCTYPE html>
<html lang="hu" dir="ltr">
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="../css/panel.css">
    <title>Kezelőfelület</title>
  </head>
  <style>
    details .arrow {
      margin-right: 8px;
      display:inline-block;
      width:11px;
      transition:transform 0.3s;
      transform:rotate(90deg);
    }
    details[open] .arrow {
      transform:rotate(180deg);
    }
  </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>Visszáru</h1>

      <div style="width: 100%; min-height: 85px;">
        <div style="display: inline; float: left;">
          <p>Neve: </p>
          <input type="text" id="filter-name" placeholder="Neve..." onkeydown="if (event.keyCode == 13) {SendFilter();}" autocomplete="off" style="width: 147px; height: 17px;">
        </div><div style="display: inline; float: left; padding-left: 15px;">
          <p>Csomag / Rendelés szám</p>
          <input type="text" id="filter-track_id" placeholder="Csomag / Rendelés szám..." onkeydown="if (event.keyCode == 13) {SendFilter();}" autocomplete="off" style="width: 147px; height: 17px;">
        </div><div style="display: inline; float: left; padding-left: 15px;">
          <p>Cikkszám</p>
          <input type="text" id="filter-item_id" placeholder="Cikkszám..." onkeydown="if (event.keyCode == 13) {SendFilter();}" autocomplete="off" style="width: 147px; height: 17px;">
        </div><div style="display: inline; float: left; padding-left: 15px;">
          <p>Dátum kiválasztása: </p>
          <input type="date" id="filter-date" style="height: 17px" onchange="SendFilter();">
        </div><div style="display: inline; float: left; padding-left: 15px;">
          <p>Lezárt elemek: </p>
          <select id="filter-is_saved" onchange="SendFilter();">
            <option value="0">Elrejtése</option>
            <option value="">Megjelenítése</option>
            <option value="1">Csak lezártak</option>
          </select>
        </div><div style="display: inline; float: left; padding-left: 15px;">
          <p>Oldalanként: </p>
          <select id="filter-perpage" onchange="SendFilter();"><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="SendFilter();">Szűrés</button>
        </div>

        <div style="display: inline; float: right; padding-right: 15px;">
          <p style="color: #f5f5f5;">: </p>
          <button onclick="CreateReturn();">Új visszáru</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 style="width: calc(100% - 6px); margin-left: 11px; margin-top: 2px; display: inline; float: left;">
        <div class="tables" style="width: 100%">
          <table id="table">
            <thead>
              <tr style="top: 0px; position: sticky; z-index: 1;">
                <th>Neve</th>
                <th>Rendelés / Csomag szám</th>
                <th>Cikkszám</th>
                <th>Dátum</th>
                <th style="width: 150px;">Megnyitás</th>
              </tr>
            </thead>

            <tbody></tbody>
          </table>
        </div>
      </div>

      <br clear="all">
      <div>
        <p style="text-align: center; padding-bottom: 50px; 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>

      <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("return_goods.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();
      }
    }
    LoadFilter();

    function LoadTable(silent = false) {
      if (!silent) Loading();
      var name = document.getElementById("filter-name").value;
      var track_id = document.getElementById("filter-track_id").value;
      var item_id = document.getElementById("filter-item_id").value;
      var date = document.getElementById("filter-date").value;
      var is_saved = document.getElementById("filter-is_saved").value;

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

      const body = 'func=LoadTable&perpage=' + perpage + '&cpage=' + cpage + '&name=' + encodeURIComponent(name).replace(/%20/g, '+') + '&track_id=' + encodeURIComponent(track_id).replace(/%20/g, '+') +'&item_id=' + encodeURIComponent(item_id).replace(/%20/g, '+') + '&date=' + date + '&is_saved=' + is_saved;
      get_POST_information("return_goods.php", body, function(text) {
        if (!silent) Loading(false);
        let response = JSON.parse(text);
        if (response.result == "ok") {
          var table = document.getElementById('table').getElementsByTagName('tbody')[0];
          table.innerHTML = "";
          document.getElementById("cpage").innerHTML = response.cpage;
          document.getElementById("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[1];
              newCell_2.innerHTML = datas[2];
              newCell_3.innerHTML = datas[3];
              newCell_4.innerHTML = datas[4];
              newCell_5.innerHTML = '<a style="cursor: pointer;" onclick="OpenRetun(\''+datas[0]+'\')">Részletek</button>';

              if (datas[5] != '1') {
                newCell_1.innerHTML += `<img style="margin-left: 10px; height: 20px; position: absolute;" title="Folyamatban van" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAACXBIWXMAAAsTAAALEwEAmpwYAAAEiklEQVR4nNVZS6gbVRg+txWfdSFY66NSF2nnnIlWsIsKinXloyKIiIqgu9qnVRe6Ufj/pL2IiGBBxasbUVwYBIteM/8/LQRFBBeFtvahIL6Wor2P+ijWGvkniTdzMpPMTCaZ+MGBXObMme8753+eq1TuaE4ZoFc18I585o0VzSmD9JpBbhqgf+LJJZ03VnSR6oxIcknnjRURpCLJJZ2XEXqvd1Xk4sEH+OfSvvoFapJx/fTBVbECkJsO0CNqkrEe+Ip+AgzQ52qSUZqur+wrALmpwbtJ/Z+gkQ8MEjWOoYGP6SpvSC3AAN1XNHmzJOKz1AI2QeM8DfzTRAhA/jK1gOAUkJ4rmrwJBj2U3bmBzxS/+82pTAJap8DvFSnAhQO3qmGwrsK3FCYA+IOhyHedwqGxmw7QX6bqr81FgEbaUoCAV1Re2AAfXayBT42NPNLcOmhcrvKE7MgYT+AZlTdcoJJBPjcG8t+vgcaFahQwwH4OBBc0UE0DP24qvFFyjfQbYqYOeNeV99C1IyE/bH2kgb8V0kJUFYZabblG+jEVecnkwM+6UDtfTQI0EiQnT9+Vq3SjmhgALJPuLKGAIy7MXhm1TAnqqzXyTo3sGeSTGug3Ge3fdWnyZU7u/F3krUl3Poq8A/7VBnlGI51NsM45DfyOXDjk1vjbyUwD70/6vlPhew3wYqaoVfHuGVqARno3RB7pdNKQp4F2DZVDgP8e6u7I7JldI4uEBfDTiXc+grwGPuwiPVGu+mb9S3yJDBfqrgHeLf4TKSLrSbjAD1jkj0tIHUhebL7HbOhPKQ4lIMS+CLAs8De7mQKaz+QTBvzNCRz3DxcaK0LvIb1lkzfAt8V+p8IbNfg3d/7WFX+TLUIDvZFagBATZ0rTfEgY7DU72tLvEsEgfSV3pQbo7a5N2G6tcXbt3oPXpBahgR4LFo8tFWhXhOOGbL6f2ZiW7Xc243kr9xy11srm0Br4Do30qUb+3RYgracloN79XBw2bt3SdH2l9ABtcj+sfvmLi0Li0H/SOu1ZNWoYpG+6PyrRJnYu8Jtdu/uw/TyITuENOzl6AVb0sR28A7k27Aqzh6KuUJwX919qncCiygJJXOKsATngRY38oVP1nGEEGPA3Bw1820ENeo+ORICQ18i/RiSkU1EZ2QB/ndSENHj3d0RIoLD9xVS98tAmFOx8fASq9ZBC+sTatd391tfdIoL53oNLz+gp65sfZxHQrxBb6BXAO605R/pmX7UkQm6j/+uLa7XlQX4IJ8Tt+QoAmo+u+cNls5QHg77jVPw7b3hh9rIlUbzDTmRSoqQWIA4ba0LI70eKRp6xzOiMlAcqIRzwbu8tJfj11OSDxaqeE3m5BfRLXPcU/PcTaN4WYcQE+pmT9N6y8zZ5pDnpS1RWBJEIqNauixZk5we1flIC2zWRaQk/GmTYqlduldKNFfK75bC2zbfKaVPhu1URaO9mrwhMOORd8LYVQj50EoMqWozyL5pzge5SkwC5sNVI+5I09e05M3E3G4VC6nlxZEl2GuiE9NfBADohlaaYy6BQ+S+XsS2DTwGeaQAAAABJRU5ErkJggg==" alt="procurement">`;

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

    var global_return_id = "";
    function CreateReturn() {
      openwin();
      wintitle.innerHTML = "Visszáru";
      winapp.innerHTML = '<div id="errorDIV"></div>';
      InitReturnEditor();
      global_return_id = "";

      if (<?php echo UserHasPerm('warehouse_add') ? 'true' : 'false'; ?>) {
        const container = document.getElementById('WarehouseAdd');
        container.innerHTML = ``;

        const iframe = document.createElement('iframe');
        iframe.src = './wh_add?iframe=1&reason=' + encodeURIComponent('Manual#<?php echo $userName; ?>').replace(/%20/g, '+') + '&functions=' + encodeURIComponent("box,foil").replace(/%20/g, '+');
        iframe.style.width = "100%";
        iframe.style.height = "500px";
        iframe.style.border = "0px";
        iframe.id = "WarehouseIframe";
        container.appendChild(iframe);
      }
    }

    function OpenRetun(return_id) {
      openwin();
      Loading();
      global_return_id = return_id;
      wintitle.innerHTML = "Visszáru";
      winapp.innerHTML = '<div id="errorDIV"></div>';

      const body = 'func=OpenRetun&return_id=' + return_id;
      get_POST_information("return_goods.php", body, function(text) {
        let response = JSON.parse(text);
        Loading(false);
        if (response.result == "ok") {

          var ElemStyle = `flex: 1 1 calc(33.333% - 10px); min-width: 250px; box-sizing: border-box;`;
          var date = new Date(response.data.return_date * 1000).toLocaleDateString('hu-HU', { year: 'numeric', month: '2-digit', day: '2-digit' }).replace(/(\d{4})-(\d{2})-(\d{2})/, '$1. $2. $3.');

          if (response.data.is_saved && response.data.is_saved == 1) {
            winapp.innerHTML += `<p style="color: #333333; margin-bottom: 0px; margin-left: 0px; font-size: 23px; font-weight: bold;">Vissszárú kezelés</p><br>
            <p style="font-weight: bold; font-size: 18px; margin-bottom: 0px;">Megtekintés:</p><p style="width: calc(100% - 35px); border-bottom: 1px solid #bdc3c7; margin-top: 5px;"></p>

            <div style="display: flex; flex-wrap: wrap; width: calc(100% - 35px); gap: 15px;">

              <div style="${ElemStyle}">
                <p class="label" style="margin-bottom: 5px;">Név:</p>
                <p style="color: var(--panelcolor);">${response.data.name}</p>
              </div>
              <div style="${ElemStyle}">
                <p class="label" style="margin-bottom: 5px;">Dátum:</p>
                <p style="color: var(--panelcolor);">${date}</p>
              </div>
              <div style="${ElemStyle}">
                <p class="label" style="margin-bottom: 5px;">Cikkszám:</p>
                <p style="color: var(--panelcolor);">${response.data.item_id}</p>
              </div>

              <div style="${ElemStyle}">
                <p class="label" style="margin-bottom: 5px;">Csomagszám:</p>
                <p style="color: var(--panelcolor);">${response.data.pack_id}</p>
              </div>
              <div style="${ElemStyle}">
                <p class="label" style="margin-bottom: 5px;">Rendelés szám:</p>
                <p style="color: var(--panelcolor);">${response.data.order_id}</p>
              </div>
              <div style="${ElemStyle}">
                <p class="label" style="margin-bottom: 5px;">Visszaküldés oka:</p>
                <p style="color: var(--panelcolor);">${response.data.return_reason}</p>
              </div>

              <div style="${ElemStyle}">
                <p class="label" style="margin-bottom: 5px;">Elállási nyilatkozat:</p>
                <p style="color: var(--panelcolor);">${response.data.is_withdraw}</p>
              </div>
              <div style="${ElemStyle}">
                <p class="label" style="margin-bottom: 5px;">Sztornó számla készült:</p>
                <p style="color: var(--panelcolor);">${response.data.cancellation_invoice}</p>
              </div>
              <div style="${ElemStyle}">
                <p class="label" style="margin-bottom: 5px;">Selejt:</p>
                <p style="color: var(--panelcolor);">${response.data.is_scrap}</p>
              </div>

              <div style="${ElemStyle}">
                <p class="label" style="margin-bottom: 5px;">Visszaraktam polcra:</p>
                <p style="color: var(--panelcolor);">${response.data.is_warehoused}</p>
              </div>
              <div style="${ElemStyle}">
                <p class="label" style="margin-bottom: 5px;">Elállás oka: </p>
                <p style="color: var(--panelcolor);">${response.data.reason}</p>
              </div>
              <div style="${ElemStyle}">
                <p class="label" style="margin-bottom: 5px;">Megjegyzés: </p>
                <p style="color: var(--panelcolor);">${response.data.note}</p>
              </div>

            </div>
            `;


          } else {
            InitReturnEditor();

            document.getElementById('winapp_name').value = response.data.name ?? '';
            if (response.data.return_date) document.getElementById('winapp_return_date').value = new Date(response.data.return_date * 1000).toLocaleDateString('sv').replace(/\//g,'-');
            document.getElementById('winapp_item_id').value = response.data.item_id ?? '';

            document.getElementById('winapp_pack_id').value = response.data.pack_id ?? '';
            document.getElementById('winapp_order_id').value = response.data.order_id ?? '';
            document.getElementById('winapp_return_reason').value = response.data.return_reason;

            document.getElementById('winapp_is_withdraw').value = response.data.is_withdraw;
            document.getElementById('winapp_cancellation_invoice').value = response.data.cancellation_invoice;
            document.getElementById('winapp_is_scrap').value = response.data.is_scrap;

            document.getElementById('winapp_is_warehoused').value = response.data.is_warehoused;
            document.getElementById('winapp_reason').innerHTML = response.data.reason ?? '';
            document.getElementById('winapp_note').innerHTML = response.data.note ?? '';

            if (<?php echo UserHasPerm('warehouse_add') ? 'true' : 'false'; ?>) {
              const container = document.getElementById('WarehouseAdd');
              container.innerHTML = ``;

              const iframe = document.createElement('iframe');
              iframe.src = './wh_add?iframe=1&reason=' + encodeURIComponent('Manual#<?php echo $userName; ?>').replace(/%20/g, '+') + '&functions=' + encodeURIComponent("box,foil").replace(/%20/g, '+');
              iframe.style.width = "100%";
              iframe.style.height = "500px";
              iframe.style.border = "0px";
              iframe.id = "WarehouseIframe";
              container.appendChild(iframe);
            }
          }

        } else {
          GenerateAlerts("error", response.result);
        }
      }, function() {
        Loading(false);
        GenerateAlerts("error", "Hálózati hiba!");
      });
    }
    function InitReturnEditor() {
      var ElemStyle = `flex: 1 1 calc(33.333% - 10px); min-width: 250px; box-sizing: border-box;`;
      winapp.innerHTML += `<p style="color: #333333; margin-bottom: 0px; margin-left: 0px; font-size: 23px; font-weight: bold;">Vissszárú kezelés</p><br>
            <p style="font-weight: bold; font-size: 18px; margin-bottom: 0px;">Töltse ki az alábbiakat:</p><p style="width: calc(100% - 35px); border-bottom: 1px solid #bdc3c7; margin-top: 5px;"></p>

            <div style="display: flex; flex-wrap: wrap; width: calc(100% - 35px); gap: 15px;">

              <div style="${ElemStyle}">
            		<p class="label" style="margin-bottom: 5px;">Név: <span style="color: red;">*</span></p>
            		<input id="winapp_name" type="text" autocomplete="off" spellcheck="false" placeholder="Név..." oninput="this.modified=true;" onblur="if(this.modified) {AutoSaveReturn(this.id, this.value); this.modified=false;}">
            	</div>
              <div style="${ElemStyle}">
                <p class="label" style="margin-bottom: 5px;">Dátum: <span style="color: red;">*</span></p>
                <input id="winapp_return_date" type="date" autocomplete="off" spellcheck="false" placeholder="Dátum..." oninput="this.modified=true;" onblur="if(this.modified) {AutoSaveReturn(this.id, this.value); this.modified=false;}">
              </div>
              <div style="${ElemStyle}">
                <p class="label" style="margin-bottom: 5px;">Cikkszám: <span style="color: red;">*</span></p>
                <input id="winapp_item_id" type="text" autocomplete="off" spellcheck="false" placeholder="Cikkszám..." oninput="this.modified=true;" onblur="if(this.modified) {AutoSaveReturn(this.id, this.value); this.modified=false;}">
              </div>

              <div style="${ElemStyle}">
                <p class="label" style="margin-bottom: 5px;">Csomagszám: <span style="color: red;">*</span></p>
                <input id="winapp_pack_id" type="text" autocomplete="off" spellcheck="false" placeholder="Csomagszám..." oninput="this.modified=true;" onblur="if(this.modified) {AutoSaveReturn(this.id, this.value); this.modified=false;}">
              </div>
              <div style="${ElemStyle}">
                <p class="label" style="margin-bottom: 5px;">Rendelés szám: <span style="color: red;">*</span></p>
                <input id="winapp_order_id" type="text" autocomplete="off" spellcheck="false" placeholder="Rendelés szám..." oninput="this.modified=true;" onblur="if(this.modified) {AutoSaveReturn(this.id, this.value); this.modified=false;}">
              </div>
              <div style="${ElemStyle}">
                <p class="label" style="margin-bottom: 5px;">Visszaküldés oka: <span style="color: red;">*</span></p>
                <select id="winapp_return_reason" style="max-width: unset; width: 218px;" oninput="this.modified=true;" onblur="if(this.modified) {AutoSaveReturn(this.id, this.value); this.modified=false;}">
                  <option value="Nem vette át">Nem vette át</option>
                  <option value="Téves rendelés csere">Téves rendelés csere</option>
                  <option value="Csomagolási hiba csere">Csomagolási hiba csere</option>
                  <option value="Hibás címzett">Hibás címzett</option>
                  <option value="Elállási visszaküldés">Elállási visszaküldés</option>
                  <option value="Kiszállítás előtt sérült">Kiszállítás előtt sérült</option>
                  <option value="Felszerelési törés">Felszerelési törés</option>
                </select>
              </div>

              <div style="${ElemStyle}">
                <p class="label" style="margin-bottom: 5px;">Elállási nyilatkozat:</p>
                <select id="winapp_is_withdraw" style="max-width: unset; width: 218px;" oninput="this.modified=true;" onblur="if(this.modified) {AutoSaveReturn(this.id, this.value); this.modified=false;}">
                  <option value="Volt">Volt</option>
                  <option value="Nem volt">Nem volt</option>
                  <option value="Nem kell">Nem kell</option>
                </select>
              </div>
              <div style="${ElemStyle}">
                <p class="label" style="margin-bottom: 5px;">Sztornó számla készült:</p>
                <select id="winapp_cancellation_invoice" style="max-width: unset; width: 218px;" oninput="this.modified=true;" onblur="if(this.modified) {AutoSaveReturn(this.id, this.value); this.modified=false;}">
                  <option value="Igen">Igen</option>
                  <option value="Nem">Nem</option>
                  <option value="Nem kell">Nem kell</option>
                </select>
              </div>
              <div style="${ElemStyle}">
                <p class="label" style="margin-bottom: 5px;">Selejt: <span style="color: red;">*</span></p>
                <select id="winapp_is_scrap" style="max-width: unset; width: 218px;" oninput="this.modified=true;" onblur="if(this.modified) {AutoSaveReturn(this.id, this.value); this.modified=false;}">
                  <option value="Igen">Igen</option>
                  <option value="Nem">Nem</option>
                  <option value="Részben">Részben</option>
                </select>
              </div>

              <div style="${ElemStyle}">
                <p class="label" style="margin-bottom: 5px;">Visszaraktam polcra: <span style="color: red;">*</span></p>
                <select id="winapp_is_warehoused" style="max-width: unset; width: 218px;" oninput="this.modified=true;" onblur="if(this.modified) {AutoSaveReturn(this.id, this.value); this.modified=false;}">
                  <option value="Igen">Igen</option>
                  <option value="Nem">Nem</option>
                  <option value="Selejt">Selejt</option>
                </select>
              </div>
              <div style="${ElemStyle}">
                <p class="label" style="margin-bottom: 5px;">Elállás oka: </p>
                <textarea style="resize: vertical; min-height: 80px; width: 200px;" id="winapp_reason" placeholder="Elállás oka..." autocomplete="off" oninput="this.modified=true;" onblur="if(this.modified) {AutoSaveReturn(this.id, this.value); this.modified=false;}"></textarea>
              </div>
              <div style="${ElemStyle}">
                <p class="label" style="margin-bottom: 5px;">Megjegyzés: </p>
                <textarea style="resize: vertical; min-height: 80px; width: 200px;" id="winapp_note" placeholder="Megjegyzés..." autocomplete="off" oninput="this.modified=true;" onblur="if(this.modified) {AutoSaveReturn(this.id, this.value); this.modified=false;}"></textarea>
              </div>

              <div style="flex: 1 1 calc(50% - 10px); margin: 20px 0px; min-width: 250px; box-sizing: border-box;">
            		<button onclick="SaveReturn();" style="width: 100%;">Mentés</button>
            	</div>
              <div style="flex: 1 1 calc(50% - 10px); margin: 20px 0px; min-width: 250px; box-sizing: border-box;">
                <button onclick="EndReturn();" style="width: 100%;">Lezárás</button>
              </div>

            </div>

            <br clear="all">
            <details>
            	<summary style="width: calc(100% - 15px); border-bottom: solid 1px rgb(211,220,228); display: inline-block; color: var(--panelcolor); cursor: pointer;"><span class="arrow"><svg role="graphics-symbol" viewBox="0 0 100 100" class=""><polygon points="5.9,88.2 50,11.8 94.1,88.2" fill="var(--panelcolor)"></polygon></svg></span> Raktározási program</summary>
            	<div id="WarehouseAdd"></div>
            </details>
            <br clear="all">
            `;

            document.getElementById('winapp_return_reason').value = '';
            document.getElementById('winapp_is_withdraw').value = '';
            document.getElementById('winapp_cancellation_invoice').value = '';
            document.getElementById('winapp_is_scrap').value = '';
            document.getElementById('winapp_is_warehoused').value = '';
    }
    window.addEventListener('message', function(event) {
      if (event.origin === 'https://szaturnusz.szatuna.hu') {
        if (event.data.iframeHeight) {
          setTimeout(() => {
            const iframe = document.getElementById("WarehouseIframe");
            iframe.style.height = event.data.iframeHeight + 'px';
            console.log(event.data.iframeHeight);
            //document.getElementById('WarehouseSection').style.maxHeight = document.getElementById('WarehouseSection').scrollHeight + 'px';
          }, 50);
        }
      }
    });

    function AutoSaveReturn(winapp_param, value) {
      if (document.getElementById("winapp_name").value != '') {

        var param = winapp_param.replace(/^winapp_/, '');
        const body = 'func=AutoSaveReturn&param=' + param + '&value=' + encodeURIComponent(value).replace(/%20/g, '+') + '&return_id=' + global_return_id;
        get_POST_information("return_goods.php", body, function(text) {
          let response = JSON.parse(text);
          if (response.result == "ok") {
            global_return_id = response.return_id;

            if (param == "name" || param == "return_date" || param == "item_id" || param == "pack_id" || param == "order_id") {
              LoadTable(true);
            }
            if (param == "is_saved") {
              OpenRetun(global_return_id);
            }
          } else {
            GenerateAlerts("error", response.result);
          }
        }, function() {
          Loading(false);
          GenerateAlerts("error", "Hálózati hiba!");
        });

      }
    }

    function SaveReturn() {
      var name = document.getElementById("winapp_name").value;
      var return_date = document.getElementById("winapp_return_date").value;
      var item_id = document.getElementById("winapp_item_id").value;
      var pack_id = document.getElementById("winapp_pack_id").value;
      var order_id = document.getElementById("winapp_order_id").value;
      var return_reason = document.getElementById("winapp_return_reason").value;
      var is_withdraw = document.getElementById("winapp_is_withdraw").value;
      var cancellation_invoice = document.getElementById("winapp_cancellation_invoice").value;
      var is_scrap = document.getElementById("winapp_is_scrap").value;
      var is_warehoused = document.getElementById("winapp_is_warehoused").value;
      var reason = document.getElementById("winapp_reason").value;
      var note = document.getElementById("winapp_note").value;

      const body = 'func=SaveReturn&return_id=' + global_return_id
      + '&name=' + encodeURIComponent(name).replace(/%20/g, '+')
      + '&return_date=' + encodeURIComponent(return_date).replace(/%20/g, '+')
      + '&item_id=' + encodeURIComponent(item_id).replace(/%20/g, '+')
      + '&pack_id=' + encodeURIComponent(pack_id).replace(/%20/g, '+')
      + '&order_id=' + encodeURIComponent(order_id).replace(/%20/g, '+')
      + '&return_reason=' + encodeURIComponent(return_reason).replace(/%20/g, '+')
      + '&is_withdraw=' + encodeURIComponent(is_withdraw).replace(/%20/g, '+')
      + '&cancellation_invoice=' + encodeURIComponent(cancellation_invoice).replace(/%20/g, '+')
      + '&is_scrap=' + encodeURIComponent(is_scrap).replace(/%20/g, '+')
      + '&is_warehoused=' + encodeURIComponent(is_warehoused).replace(/%20/g, '+')
      + '&reason=' + encodeURIComponent(reason).replace(/%20/g, '+')
      + '&note=' + encodeURIComponent(note).replace(/%20/g, '+');

      Loading();
      get_POST_information("return_goods.php", body, function(text) {
        let response = JSON.parse(text);
        Loading(false);
        if (response.result == "ok") {
          global_return_id = response.return_id;
          LoadTable(true);
        } else {
          GenerateAlerts("error", response.result);
        }
      }, function() {
        Loading(false);
        GenerateAlerts("error", "Hálózati hiba!");
      });
    }

    function EndReturn(isVerified = false) {
      const fields = {
          winapp_name: "Kérem, töltse ki ezt a mezőt!",
          winapp_return_date: "Kérem, töltse ki ezt a mezőt!",
          winapp_item_id: "Kérem, töltse ki ezt a mezőt!",
          winapp_return_reason: "Kérem, töltse ki ezt a mezőt!",
          winapp_is_scrap: "Kérem, töltse ki ezt a mezőt!",
          winapp_is_warehoused: "Kérem, töltse ki ezt a mezőt!"
      };

      const packOrOrder = document.getElementById("winapp_pack_id").value.trim() ||
                          document.getElementById("winapp_order_id").value.trim();

      let allFieldsValid = true;

      Object.entries(fields).forEach(([id, msg]) => {
          const elem = document.getElementById(id);
          if (!elem.value.trim()) {
              elem.setCustomValidity(msg);
              elem.reportValidity();
              allFieldsValid = false;
          } else {
              elem.setCustomValidity('');
          }
      });

      if (!packOrOrder) {
          document.getElementById("winapp_pack_id").setCustomValidity("Csomagszám vagy rendelés szám megadása kötelező!");
          document.getElementById("winapp_order_id").setCustomValidity("Csomagszám vagy rendelés szám megadása kötelező!");
          document.getElementById("winapp_pack_id").reportValidity();
          allFieldsValid = false;
      } else {
          document.getElementById("winapp_pack_id").setCustomValidity('');
          document.getElementById("winapp_order_id").setCustomValidity('');
      }

      if (isVerified) {
        AutoSaveReturn('is_saved', 1);
      } else if (allFieldsValid) {
        var html = `
            <p><strong>Biztos benne, hogy le szeretné zárni ezt a visszárú kezelést?</strong></p>
            <br clear="all"><br>
            <button id="AlertBtnNo" style="float: right; margin-left: 15px; width: 80px;">Mégsem</button>
            <button id="AlertBtnYes" style="float: right; width: 95px; background: var(--panelcolor); color: #f5f5f5; border: unset;">Lezárás</button>
        `;


        const overlay = CreateAlertBox('Lezárás', html);
        document.getElementById('AlertBtnYes').onclick = function () {
          EndReturn(true);
          CloseAlertBox(overlay);
        };
        document.getElementById('AlertBtnNo').onclick = function () {
          CloseAlertBox(overlay);
        };

        SaveReturn();
      }
    }

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