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

if (!(UserHasPerm('production_classic') || UserHasPerm('production_injmold') || UserHasPerm("production_sporty") || 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'>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"]));

    $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 ($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(scrap_date)) = '".$date."'";
        $isfirst = false;
      } else {
        $addquery = $addquery." and DATE(FROM_UNIXTIME(scrap_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 scrap_production".$addquery);
    $count = mysqli_fetch_array($sql)[0];

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

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

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

    $responseStr = '';

    $query = "SELECT scrap_id, place, reason, item_id, scrap_date, is_saved FROM scrap_production".$addquery." LIMIT $limit, $maxperpage";
    if ($result = $conn->query($query)) {
      while ($c_prod = $result->fetch_assoc()) {

        if ($responseStr != "") {
          $responseStr .= "|%|";
        }
        $responseStr .= $c_prod['scrap_id'].'/!/'.$c_prod['item_id'].'/!/'.$c_prod['place'].'/!/'.$c_prod['reason'].'/!/'.date("Y. m. d.", $c_prod['scrap_date']).'/!/'.$c_prod['is_saved'];
      }
    }

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

  } else if (htmlspecialchars($_POST["func"]) == "CreateScrap") {
    $item_id = htmlspecialchars(str_replace(' ', '+', $_POST['item_id']));
    $sql = mysqli_query($conn,"INSERT INTO scrap_production(item_id) VALUES ('$item_id')");
    $sid = mysqli_insert_id($conn);

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

    echo $json;
  } else if (htmlspecialchars($_POST["func"]) == "OpenScrap") {
    $sid = htmlspecialchars($_POST["scrap_id"]);

    $sql = mysqli_query($conn,"SELECT * FROM scrap_production WHERE scrap_id = '$sid'");
    $data = mysqli_fetch_array($sql);

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

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

    $params = ['item_id', 'right_db', 'left_db', 'place', 'reason', 'source', 'note', 'scrap_date', 'is_saved'];
    if (!(!empty($param) && in_array($param,$params))) {
      echo json_encode(array('result' => 'Hibás paraméter lett megadva!'));
      exit();
    }

    if ($param == "scrap_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 ($scrap_id != "") {
      $sql = mysqli_query($conn,"UPDATE scrap_production SET $param='$value' WHERE scrap_id = '$scrap_id'");
    } else {
      $sql = mysqli_query($conn, "INSERT INTO scrap_production($param) VALUES ('$value')");
      $scrap_id = mysqli_insert_id($conn);
    }

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

  } else if (htmlspecialchars($_POST["func"]) == "SaveScrap") {
    $scrap_id = htmlspecialchars($_POST["scrap_id"]);

    $item_id = htmlspecialchars($_POST["item_id"]);
    $right_db = htmlspecialchars($_POST["right_db"]);
    $left_db = htmlspecialchars($_POST["left_db"]);
    $place = htmlspecialchars($_POST["place"]);
    $reason = htmlspecialchars($_POST["reason"]);
    $source = htmlspecialchars($_POST["source"]);
    $note = htmlspecialchars($_POST["note"]);
    $scrap_date = htmlspecialchars($_POST["scrap_date"]);

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

    if ($item_id != "") {
      $sql = mysqli_query($conn,"SELECT item_id FROM scrap_production 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 ($scrap_id == "") {
      $sql = mysqli_query($conn, "INSERT INTO scrap_production(item_id) VALUES ('$item_id')");
      $scrap_id = mysqli_insert_id($conn);
    }

    $sql = mysqli_query($conn,"UPDATE scrap_production SET
      item_id = '$item_id',
      place = '$place',
      reason = '$reason',
      source = '$source',
      note = '$note'
    WHERE scrap_id = '$scrap_id'");

    if ($scrap_date != "") {
      $sql = mysqli_query($conn,"UPDATE scrap_production SET scrap_date = $scrap_date WHERE scrap_id = '$scrap_id'");
    } else {
      $sql = mysqli_query($conn,"UPDATE scrap_production SET scrap_date = NULL WHERE scrap_id = '$scrap_id'");
    }

    if ($right_db != "") {
      $sql = mysqli_query($conn,"UPDATE scrap_production SET right_db = $right_db WHERE scrap_id = '$scrap_id'");
    } else {
      $sql = mysqli_query($conn,"UPDATE scrap_production SET right_db = 0 WHERE scrap_id = '$scrap_id'");
    }

    if ($left_db != "") {
      $sql = mysqli_query($conn,"UPDATE scrap_production SET left_db = $left_db WHERE scrap_id = '$scrap_id'");
    } else {
      $sql = mysqli_query($conn,"UPDATE scrap_production SET left_db = 0 WHERE scrap_id = '$scrap_id'");
    }

    echo json_encode(array('result' => 'ok', 'scrap_id' => $scrap_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>
  </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">

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

            <h1>Gyártási selejt</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..." 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="CreateScrap();">Új selejt</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>Cikkszám</th>
                      <th>Keletkezésének helye</th>
                      <th>Selejt oka</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("production_scrap.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 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 +'&item_id=' + encodeURIComponent(item_id).replace(/%20/g, '+') + '&date=' + date + '&is_saved=' + is_saved;
        get_POST_information("production_scrap.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="OpenScrap(\''+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,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAYAAAAeP4ixAAAACXBIWXMAAAsTAAALEwEAmpwYAAAFeUlEQVR4nO1Ze2gcZRDfUFtfRVR8UBWikNzOt22jNCoarbVSRUTwWZ8ovkAUFKsYRCjz7SWlRalS/aNGVHwglGupUsPtzKZ4vmjVBB+IVgUFjWilkSqtRCUmMrt7ufRubx93ueSEDHwct/vtt99vfjPzzcwaxpzMyf9ZJlpU1m1X6NygNK9XSJTBfIfRzLICC4eprLMYkG5XyBuU5rcU0ojSPDE5kIdk7plYOBaQe41mE5DNaxo9ZNMhw0S6ReYr5G6FNK7QWWU0kygkigOhkH7q7BuaLwOQfyxes5CON5pFQNMP8UC4W+Zamm4tu77NaAaxsLDQM5MIEKDpwNL1/cfJfKVpsPy+pfneGdwwXw/IWwAp5w9+xkT3FBPds+PYkLkeCNtZHjGv77SNu45sHIJcbh4gPRGuaf5NaX49xKm7wpYCzW/EgP48gwTTjqEN88co5P5Y+y83FRy4sHwthXyR0vxvLHuaDijt3FbThi2ky5Xmp0HTa6DZkXgvDgya/0wLYroGIL/UiTuOSgXE18LsbDh60O5UQGZ/w1x1pAOC9E4KLX1nIZ8lftB0QAxjosXSdGdFblRpt+9lsHCCPGEhndtwIMhjqWC0bcofLr+ySaX5lbADDjS/aGFugc+ge4XS/EckaM1/y7khCaKcNaDdm0HzWkB+VWxfadoXD4S2pwKiNH1j2rSy+N9CvkSuFbVianqkeA+QH5ZrCbS5Ie69seZpO8tTAvHQjyukl4um04qFIxSyBqQr/ZfmFgDSC0lMQpLCjif5aJ892g5IHwahfa0ws9jOnyNMBWdLNV8cTAViEkiJzhET+Q7xm+J9AQea3k1q25btrvbA2+7qWv3DDFL+2oGURsHMDiwV7UmkinhhF/Q6izwfQHpOWPUZLCwEzcO1gADNw1NS/jeFvXqAJBoZmy8IXdOvEmuNVt2yhrDiA6NPTXRObyiQ4MVfCxseK73OIgHnRa2a2KDwlB9pBGy6tLFApnGApk2yJ7DdFSEKG5MANNV/mxcIDmTiUn6ph8QHEwMBTfvFmb0DDfnjmQBilHws+qxC+qACCCD9UzmZRiXOT233ANJjCvmvGQGiY+YifV/JCPKDh6QlyGOAzrVyT8pZ0LxGgHhzvd5VNDs+i9QVV8vXAwQCXwphhW8qaZvumzwLkD7xH+SPLMxbidjp6W8NFLSrUUBMdC4OBeJp36aVCt3HvT+53DyvW1hpbt1yL9hoaIoh+VjgsGvSArEk/4puUohSfynuIVaU5merL0a7i401pXlPGeX7LU0PyL1MD5/RCD8C5PsTgQCkh+IXpBsDrW/2F6evxCSnhkVpiTYCSGff0Px4JmznqmTdDt7sg3bPA+TLSofURIsHAGlH2DoSBCSTbluXP9FCaoMsd8p806brpLgTJYImVEhPSQ0EmraC5gE55QHpW9D0awImnGWAdDChZvZMfVbS/qCZ/UV1k6CDRqNF9fS3KuSf01AsOZVoVWnaKL6RgMVhT2GSLSPt9Ys3GhSNe5qXesdjgtAzb6S7hClhzGMu67bHNr2l+GmEPZc56Wf+u3hJHWtsiWbEq6OrPGw75wdmt7cuMMhve++KrAw5csQ2vJes23kyaP4yXAvOMpkjB2JdYIJPCArp6lrXMLOOGesn1cDI5ounel1gkJ/32ee7awRSiAUxI2CCzorS/Gj0PPodNL0vnxr8PNBZJQHCSCsdyCeFhVGJ4eKoMkcoThvlBEBcGQyaBxLX6EmZka78dDID6N4TMNJXzfQ6k5zajZA0zIDN13hAkLeVmdK4X8LOsiQGExRqEoZL12lUSgijWSQJmKJ/ySe2AMS+au2kWRUvCYyoHtt7d54q86SlKoVaol7VnMyJMSvyH92GN07IoDZ/AAAAAElFTkSuQmCC" alt="paper-waste">`;

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

      var global_scrap_id = "";
      function CreateScrap() {
        openwin();
        wintitle.innerHTML = "Selejt";
        winapp.innerHTML = '<div id="errorDIV"></div>';
        InitScrapEditor();
        global_scrap_id = "";
      }

      function OpenScrap(scrap_id) {
        openwin();
        Loading();
        global_scrap_id = scrap_id;
        wintitle.innerHTML = "Selejt";
        winapp.innerHTML = '<div id="errorDIV"></div>';

        const body = 'func=OpenScrap&scrap_id=' + scrap_id;
        get_POST_information("production_scrap.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.scrap_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;">Gyártási selejt rögzíté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;">Dátum: <span style="color: red;">*</span></p>
                        <p style="color: var(--panelcolor);">${response.data.scrap_date}</p>
                      </div>
                      <div style="${ElemStyle}">
                        <p class="label" style="margin-bottom: 5px;">Cikkszám: <span style="color: red;">*</span></p>
                        <p style="color: var(--panelcolor);">${response.data.item_id}</p>
                      </div>
                      <div style="${ElemStyle}">
                        <p class="label" style="margin-bottom: 5px;">Selejt keletkezésének helye: <span style="color: red;">*</span></p>
                        <p style="color: var(--panelcolor);">${response.data.place}</p>
                      </div>

                      <div style="${ElemStyle}">
                        <p class="label" style="margin-bottom: 5px;">Selejt oka: <span style="color: red;">*</span></p>
                        <p style="color: var(--panelcolor);">${response.data.reason}</p>
                      </div>
                      <div style="${ElemStyle}">
                        <p class="label" style="margin-bottom: 5px;">Jobb:</p>
                        <p style="color: var(--panelcolor);">${response.data.right_db}</p>
                      </div>
                      <div style="${ElemStyle}">
                        <p class="label" style="margin-bottom: 5px;">Bal:</p>
                        <p style="color: var(--panelcolor);">${response.data.left_db}</p>
                      </div>

                      <div style="${ElemStyle}">
                        <p class="label" style="margin-bottom: 5px;">Hiba forrása: <span style="color: red;">*</span></p>
                        <p style="color: var(--panelcolor);">${response.data.source}</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 style="${ElemStyle}">
                      </div>

                    </div>
                    `;


            } else {
              InitScrapEditor();

              if (response.data.scrap_date) document.getElementById('winapp_scrap_date').value = new Date(response.data.scrap_date * 1000).toLocaleDateString('sv').replace(/\//g,'-');
              document.getElementById('winapp_item_id').value = response.data.item_id ?? '';
              document.getElementById('winapp_place').value = response.data.place ?? '';

              LoadReasonVariant();

              document.getElementById('winapp_reason').value = response.data.reason ?? '';
              document.getElementById('winapp_right_db').value = response.data.right_db ?? '';
              document.getElementById('winapp_left_db').value = response.data.left_db;

              document.getElementById('winapp_source').value = response.data.source;
              document.getElementById('winapp_note').innerHTML = response.data.note ?? '';
            }

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

      function InitScrapEditor() {
        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;">Gyártási selejt rögzíté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;">Dátum: <span style="color: red;">*</span></p>
                  <input id="winapp_scrap_date" type="date" autocomplete="off" spellcheck="false" placeholder="Dátum..." oninput="this.modified=true;" onblur="if(this.modified) {AutoSaveScrap(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) {AutoSaveScrap(this.id, this.value); this.modified=false;}">
                </div>
                <div style="${ElemStyle}">
                  <p class="label" style="margin-bottom: 5px;">Selejt keletkezésének helye: <span style="color: red;">*</span></p>
                  <select id="winapp_place" style="max-width: unset; width: 218px;" oninput="this.modified=true;" onblur="if(this.modified) {AutoSaveScrap(this.id, this.value); this.modified=false; LoadReasonVariant();}">
                    <option value="Terítékfelvágás">Terítékfelvágás</option>
                    <option value="Préselés">Préselés</option>
                    <option value="Feldolgozás">Feldolgozás</option>
                    <option value="Utómunka">Utómunka</option>
                  </select>
                </div>

                <div style="${ElemStyle}">
                  <p class="label" style="margin-bottom: 5px;">Selejt oka: <span style="color: red;">*</span></p>
                  <select id="winapp_reason" style="max-width: unset; width: 218px;" oninput="this.modified=true;" onblur="if(this.modified) {AutoSaveScrap(this.id, this.value); this.modified=false;}">
                  </select>
                </div>
                <div style="${ElemStyle}">
                  <p class="label" style="margin-bottom: 5px;">Jobb selejtszám:</p>
                  <input id="winapp_right_db" type="number" min="0" autocomplete="off" spellcheck="false" placeholder="Jobb selejtszám..." oninput="this.modified=true;" onblur="if(this.modified) {AutoSaveScrap(this.id, this.value); this.modified=false;}">
                </div>
                <div style="${ElemStyle}">
                  <p class="label" style="margin-bottom: 5px;">Bal selejtszám:</p>
                  <input id="winapp_left_db" type="number" min="0" autocomplete="off" spellcheck="false" placeholder="Bal selejtszám..." oninput="this.modified=true;" onblur="if(this.modified) {AutoSaveScrap(this.id, this.value); this.modified=false;}">
                </div>

                <div style="${ElemStyle}">
                  <p class="label" style="margin-bottom: 5px;">Hiba forrása: <span style="color: red;">*</span></p>
                  <select id="winapp_source" style="max-width: unset; width: 218px;" oninput="this.modified=true;" onblur="if(this.modified) {AutoSaveScrap(this.id, this.value); this.modified=false;}">
                    <option value="Gépi">Gépi</option>
                    <option value="Emberi">Emberi</option>
                  </select>
                </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) {AutoSaveScrap(this.id, this.value); this.modified=false;}"></textarea>
                </div>
                <div style="${ElemStyle}">
                </div>


                <div style="flex: 1 1 calc(50% - 10px); margin: 20px 0px; min-width: 250px; box-sizing: border-box;">
                  <button onclick="SaveScrap();" 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="EndScrap();" style="width: 100%;">Lezárás</button>
                </div>

              </div>

              <br clear="all">
              `;

              LoadReasonVariant();
              document.getElementById('winapp_place').value = '';
              document.getElementById('winapp_reason').value = '';
              document.getElementById('winapp_source').value = '';
      }

      function LoadReasonVariant() {
        var currentPlace = document.getElementById('winapp_place').value;
        if (currentPlace != '') {
          if (currentPlace == 'Terítékfelvágás') {
            document.getElementById('winapp_reason').innerHTML = `
            <option value="Mérethibás teríték">Mérethibás teríték</option>
            <option value="Rossz oldalra forgatott teríték">Rossz oldalra forgatott teríték</option>
            `;
          } else if (currentPlace == 'Préselés') {
            document.getElementById('winapp_reason').innerHTML = `
            <option value="Hideg, Lapos légterelő">Hideg, Lapos légterelő</option>
            <option value="Meleg túlfújt légterelő">Meleg túlfújt légterelő</option>
            <option value="Szerszám hiba látható rajta">Szerszám hiba látható rajta</option>
            <option value="Szellemképes">Szellemképes</option>
            <option value="Anyag lemezek közé becsúszott (kicsi teríték)">Anyag lemezek közé becsúszott (kicsi teríték)</option>
            <option value="Anyag lemezek közé becsúszott (rossz pozícionálás)">Anyag lemezek közé becsúszott (rossz pozícionálás)</option>
            <option value="Lég befúvás meglátszik">Lég befúvás meglátszik</option>
            <option value="Karcos légterelő">Karcos légterelő</option>
            <option value="Törés rossz tárolás miatt">Törés rossz tárolás miatt</option>
            `;
          } else if (currentPlace == 'Feldolgozás') {
            document.getElementById('winapp_reason').innerHTML = `
            <option value="Belső vágó eltörte">Belső vágó eltörte</option>
            <option value="Külső vágó eltörte">Külső vágó eltörte</option>
            <option value="Maró eltörte, karcolta">Maró eltörte, karcolta</option>
            <option value="Gyalu eltörte">Gyalu eltörte</option>
            <option value="Fűrész eltörte">Fűrész eltörte</option>
            <option value="Paraméterek nem megfelelőek">Paraméterek nem megfelelőek</option>
            <option value="Törés rossz tárolás miatt">Törés rossz tárolás miatt</option>
            `;
          } else if (currentPlace == 'Utómunka') {
            document.getElementById('winapp_reason').innerHTML = `
            <option value="Letört sarok">Letört sarok</option>
            `;
          } else {
            document.getElementById('winapp_reason').innerHTML = ``;
          }
        }
      }

      function AutoSaveScrap(winapp_param, value) {
        if (document.getElementById("winapp_item_id").value != '') {

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

              if (param == "place" || param == "reason" || param == "item_id" || param == "scrap_date") {
                LoadTable(true);
              }
              if (param == "is_saved") {
                OpenScrap(global_scrap_id);
              }
            } else {
              GenerateAlerts("error", response.result);
            }
          }, function() {
            Loading(false);
            GenerateAlerts("error", "Hálózati hiba!");
          });

        }
      }

      function SaveScrap() {
        var scrap_date = document.getElementById("winapp_scrap_date").value;
        var item_id = document.getElementById("winapp_item_id").value;
        var right_db = document.getElementById("winapp_right_db").value;
        var left_db = document.getElementById("winapp_left_db").value;
        var place = document.getElementById("winapp_place").value;
        var reason = document.getElementById("winapp_reason").value;
        var source = document.getElementById("winapp_source").value;
        var note = document.getElementById("winapp_note").value;

        const body = 'func=SaveScrap&scrap_id=' + global_scrap_id
        + '&scrap_date=' + encodeURIComponent(scrap_date).replace(/%20/g, '+')
        + '&item_id=' + encodeURIComponent(item_id).replace(/%20/g, '+')
        + '&right_db=' + encodeURIComponent(right_db).replace(/%20/g, '+')
        + '&left_db=' + encodeURIComponent(left_db).replace(/%20/g, '+')
        + '&place=' + encodeURIComponent(place).replace(/%20/g, '+')
        + '&reason=' + encodeURIComponent(reason).replace(/%20/g, '+')
        + '&source=' + encodeURIComponent(source).replace(/%20/g, '+')
        + '&note=' + encodeURIComponent(note).replace(/%20/g, '+')

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

      function EndScrap(isVerified = false) {
        const fields = {
          winapp_item_id: "Kérem, töltse ki ezt a mezőt!",
          winapp_place: "Kérem, töltse ki ezt a mezőt!",
          winapp_reason: "Kérem, töltse ki ezt a mezőt!",
          winapp_source: "Kérem, töltse ki ezt a mezőt!",
          winapp_scrap_date: "Kérem, töltse ki ezt a mezőt!",
        };

        const leftOrRight = document.getElementById("winapp_right_db").value.trim() ||
                            document.getElementById("winapp_left_db").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 (!leftOrRight) {
            document.getElementById("winapp_right_db").setCustomValidity("Jobb vagy Bal oldali selejtszám megadása kötelező!");
            document.getElementById("winapp_left_db").setCustomValidity("Jobb vagy Bal oldali selejtszám megadása kötelező!");
            document.getElementById("winapp_right_db").reportValidity();
            allFieldsValid = false;
        } else {
            document.getElementById("winapp_right_db").setCustomValidity('');
            document.getElementById("winapp_left_db").setCustomValidity('');
        }

        if (isVerified) {
          AutoSaveScrap('is_saved', 1);
        } else if (allFieldsValid) {
          var html = `
              <p><strong>Biztos benne, hogy le szeretné zárni ezt a selejt rögzíté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 () {
            EndScrap(true);
            CloseAlertBox(overlay);
          };
          document.getElementById('AlertBtnNo').onclick = function () {
            CloseAlertBox(overlay);
          };

          SaveScrap();
        }
      }

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