<?php

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

if (!UserHasPerm('removal_from_warehouse')) {
  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 / oszlop</option>
    <option value='50'>50 db / oszlop</option>
    <option value='100'>100 db / oszlop</option>
    <option value='250'>250 db / oszlop</option>
    <option value='500'>500 db / oszlop</option>
    <option value='1000'>1000 db / oszlop</option>";
    $perpageselect = str_replace("value='".$maxperpage."'", "value='".$maxperpage."' selected", $perpageselect);

    $UserItems = [];
    $query = "SELECT full_name, uid FROM users";
    if ($result = $conn->query($query)) {
      while ($cuser = $result->fetch_assoc()) {

        $Current_full_name = $coderclass->decode($cuser['full_name'], 'TIT4');
        $UserItems[] = [ 'full_name' => $Current_full_name, 'uid' => $cuser['uid'] ];
      }
    }

    usort($UserItems, function ($a, $b) {
      return strcoll($a['full_name'], $b['full_name']);
    });

    $userselect = '';
    for ($i=0; $i < count($UserItems); $i++) {
      $cval = $UserItems[$i]['full_name'] . " - " . $coderclass->encode($UserItems[$i]['uid'], 'RM');
      $userselect .= '<option value="'.$cval.'"></option>';
    }

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

    echo $json;
  } else if (htmlspecialchars($_POST["func"]) == 'CreateRemoval') {
    $category = $_POST['category'] ?? '';
    $rawData = $_POST['data'] ?? '';
    $allowedCategories = ['warranty', 'scrap', 'employee'];

    if (!in_array($category, $allowedCategories, true)) {
      echo 'Érvénytelen kategória';
      exit;
    }

    $jsonData = json_decode($rawData, true);
    if (!is_array($jsonData)) {
      echo 'Hibás adatstruktúra';
      exit;
    }

    $itemIdValue = null;
    foreach ($jsonData as $param) {
      if ($param['name'] === 'item_id') {
        $itemIdValue = $param['value'];
        break;
      }
    }

    if ($itemIdValue == null) {
      echo 'Hibás adatstruktúra';
      exit;
    } else {
      $sql = mysqli_query($conn,"SELECT name_in_db FROM pr_parameters WHERE item_id = '$itemIdValue'");
      $pr_parameters = mysqli_fetch_array($sql);
      if ($pr_parameters == null) {
        echo 'Nem létező cikkszámot adott meg!';
        exit;
      }
    }

    $table = $conn->real_escape_string("{$category}_removal");

    $time = time();
    mysqli_query($conn, "INSERT INTO $table (date_create) VALUES ($time)");
    $rid = mysqli_insert_id($conn);


    foreach ($jsonData as $item) {
      if (!isset($item['name'], $item['value'])) {
        continue;
      }
      $paramName = $item['name'];
      $paramValue = $item['value'];

      if (!preg_match('/^[a-z_]+$/', $paramName)) {
        continue;
      }

      if ($paramValue === '$[TIMESTAMP]') {
        $paramValue = time();
        $type = 'i';
      } else {
        $paramValue = htmlspecialchars($paramValue, ENT_QUOTES, 'UTF-8');
        $type = 's';
      }

      if ($paramName === 'uid') {
        $paramValue = $coderclass->decode($paramValue, "RM");
      }

      $column = $conn->real_escape_string($paramName);
      $sql = "UPDATE `{$table}` SET `{$column}` = ? WHERE `{$category}_rid` = ?";
      $stmt = $conn->prepare($sql);

      if (!$stmt) {
        continue;
      }

      $stmt->bind_param($type . 'i', $paramValue, $rid);
      $stmt->execute();
      $stmt->close();
    }
    echo 'ok';
  } else if (htmlspecialchars($_POST["func"]) == "table") {
    $category = $_POST['category'] ?? '';
    $rawData = $_POST['data'] ?? '';
    $allowedCategories = ['warranty', 'scrap', 'employee'];

    if (!in_array($category, $allowedCategories, true)) {
      echo '{"result": "Érvénytelen kategória"}';
      exit;
    }

    $maxperpage = intval(htmlspecialchars($_POST["perpage"]));
    $cpage = intval(htmlspecialchars($_POST["cpage"]));

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

    $addquery = "";
    $isfirst = true;

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

    if ($name != "" && $category != "scrap") {
      $addquery = $addquery." WHERE name LIKE '%".$name."%'";
      $isfirst = false;
    } else if ($name != "") {
      $addquery = $addquery." WHERE wh_id LIKE '%".$name."%'";
      $isfirst = false;
    }

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

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

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

      if ($isfirst) {
        $addquery = $addquery." WHERE date_create < '".$timestamp."'";
        $isfirst = false;
      } else {
        $addquery = $addquery." and date_create < '".$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."%'";
      }
    }

    $table = $conn->real_escape_string("{$category}_removal");

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

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

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

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

    $responseStr = '';
    $isnamequery = ($category === "scrap") ? 'wh_id' : 'name';
    $ridquery = $category."_rid";

    $query = "SELECT $ridquery, $isnamequery, item_id, date_create, right_db, left_db FROM $table".$addquery." LIMIT $limit, $maxperpage";
    if ($result = $conn->query($query)) {
      while ($c_removal = $result->fetch_assoc()) {

        if ($responseStr != "") {
          $responseStr .= "|%|";
        }
        $responseStr .= $c_removal[$isnamequery].'/!/'.$c_removal['item_id'].'/!/'.date("Y. m. d.", $c_removal['date_create']).'/!/'.$c_removal['right_db'].'/!/'.$c_removal['left_db'].'/!/'.$c_removal[$ridquery];
      }
    }

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

  } else if (htmlspecialchars($_POST["func"]) == "OpenInfo") {
    $category = $_POST['category'] ?? '';
    $allowedCategories = ['warranty', 'scrap', 'employee'];
    $rid = intval(htmlspecialchars($_POST["rid"]));

    if (!in_array($category, $allowedCategories, true)) {
      echo '{"result": "Érvénytelen kategória"}';
      exit;
    }

    $table = $conn->real_escape_string("{$category}_removal");

    $NameTranslate = [
      "warranty" => "Garanciális ügyintézés",
      "scrap" => "Selejt kivét",
      "employee" => "Dolgozói kivét",
      "name" => "Ügyfél / Raktár / Dolgozó neve",
      "mail" => "Email",
      "order_id" => "Rendelés azonosító",
      "item_id" => "Cikkszám",
      "right_db" => "Jobb oldal db",
      "left_db" => "Bal oldal db",
      "reason" => "Kivét / Selejt oka",
      "note" => "Megjegyzés",
      "date_create" => "Dátum",
      "wh_id" => "Raktárhely"
    ];

    $sql = mysqli_query($conn,"SELECT * FROM $table WHERE ".$category."_rid = $rid");
    $result = mysqli_fetch_array($sql);

    $html = '<p><span style="font-size: 18px; font-weight: bold;">'.$NameTranslate[$category].'</span><br><br>';

    if ($result != null) {
      foreach ($result as $paramName => $value) {
        if (array_key_exists($paramName, $NameTranslate)) {
          $cvalue = $value;
          if ($paramName == "date_create") {
            $cvalue = date("Y. m. d. h:i:s", $value);
            $html .= '<br><b>'.$NameTranslate[$paramName].':</b> '.$cvalue.'<br>';
            continue;
          }
          $html .= '<b>'.$NameTranslate[$paramName].':</b> '.$cvalue.'<br>';
        }
      }
      $html .= '</p>';
    } else {
      echo '{"result": "Érvénytelen azonosító"}';
      exit;
    }

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

  } else if (htmlspecialchars($_POST["func"]) == "ScrapRemoval") {
    $item_id = htmlspecialchars($_POST["item_id"]);
    $left = intval(htmlspecialchars($_POST["left"]));
    $right = intval(htmlspecialchars($_POST["right"]));
    $warehouse_code = htmlspecialchars($_POST["warehouse_code"]);

    $sql = mysqli_query($conn,"SELECT wid FROM warehouse_foil WHERE item_id = '$item_id' and place LIKE '%$warehouse_code%' AND is_active = 1");
    $foil_warehouse = mysqli_fetch_array($sql);

    if ($foil_warehouse != null) {
      $left_db = -$left;
      $right_db = -$right;

      $wid = $foil_warehouse['wid'];

      $sql = mysqli_query($conn,"UPDATE warehouse_foil SET left_db = CASE WHEN left_db + $left_db < 0 THEN 0 ELSE left_db + $left_db END, right_db = CASE WHEN right_db + $right_db < 0 THEN 0 ELSE right_db + $right_db END WHERE wid = '$wid'");

      $loggerclass->writeLogWarehouse(['reason' => 'Kivét selejt miatt', 'reason_code' => 1,
          'item_id' => $item_id,
          'from_place' => $warehouse_code,
          'to_place' => '',
          'amount_left' => $left,
          'amount_right' => $right
        ]);
    } else {
      $position = substr($warehouse_code, -3);
      $wcode = substr($warehouse_code, 0, strlen($warehouse_code) - 3);

      $letter = $position[0];
      $numberFromLetter = ord(strtoupper($letter)) - ord('A') + 1;
      $number = ltrim(substr($position, 1, 2), '0');
      $position = $numberFromLetter . ':' . $number;

      $sql = mysqli_query($conn,"SELECT warehouse_id FROM warehouse_structure WHERE code = '$wcode'");
      $warehouse_structure = mysqli_fetch_array($sql);

      if ($warehouse_structure != null) {
        $warehouse_id = $warehouse_structure['warehouse_id'];

        $sql = mysqli_query($conn,"SELECT wid FROM warehouse WHERE warehouse_id = '$warehouse_id' and item_id = '$item_id' and position = '$position'");
        $warehouse_box = mysqli_fetch_array($sql);

        if ($warehouse_box != null) {
          $box_db = -max($left, $right);
          $wid = $warehouse_box['wid'];
          $sql = mysqli_query($conn,"UPDATE warehouse SET amount = CASE WHEN amount + $box_db < 0 THEN 0 ELSE amount + $box_db END WHERE wid = '$wid'");

          $loggerclass->writeLogWarehouse(['reason' => 'Kivét selejt miatt', 'reason_code' => 1,
              'item_id' => $item_id,
              'from_place' => $warehouse_code,
              'to_place' => '',
              'amount_left' => $box_db,
              'amount_right' => $box_db
            ]);
        } else {
          echo json_encode(array(
            'result' => 'A cikkszám nem található meg ezen a raktárazonosítón!'
          ));
          exit();
        }
      } else {
        echo json_encode(array(
          'result' => 'Nem létező raktár azonosítót adott meg!'
        ));
        exit();
      }
    }

    echo json_encode(array(
      'result' => 'ok'
    ));
  }

  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>
  <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" style="margin-right: 30px;">
      <div id="errorDIV" style="z-index: 100; top: 50px; position: fixed; width: calc(100% - 260px);"></div>

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

      <!-- KATEGÓRIA GOMBOK -->
      <div class="category-tabs">
        <div class="category-tab active" onclick="switchCategory(this, 'warranty')">
          <div class="category-tab-icon">
            <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAACXBIWXMAAAsTAAALEwEAmpwYAAAEMUlEQVR4nO2ZXWgUVxTHT2PbF7ElraDZLBGhIKybbFAfBUNNK60PIiWYzEptSuiLoogfbGaloRQTlD4JhZZQmkVEjEZBnbmb3ZhAE41JNzGZySZ+RFAQ8iAmiD4EduYeubOTMLOzrZnNzCSBHPjDsjP37v83994z594FWI3VWA3HAwlsU0W4phCYYWKf2XewHANF8GcIVGUIVGdE+FolEFMIqCoBNEr/Lsbu0e4lUMXaLp3xm7BeJXBDEYHmml2olGzb65iEz7013w5rFAJ9hRrPM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76taMKirbwszI/AGTlkvFwWFgN+TqBZADEBNe3e/Su50CiPSMVBXh4ORqXL+a6X1omXSjkxxaaU9+5gecY7hGF4QgN8A1AAAAAASUVORK5CYII=" alt="warranty--v1">
          </div>
          <div class="category-tab-title">Garanciális ügyintézés</div>
          <div class="category-tab-desc">Garancia szerinti csere</div>
        </div>

        <div class="category-tab" onclick="switchCategory(this, 'scrap')">
          <div class="category-tab-icon">
            <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAACXBIWXMAAAsTAAALEwEAmpwYAAAJT0lEQVR4nO2Y20/jaRnHm032xjWaqIl6YaI3XnizN7rxYo0mJntn9NJEk/VGY6KJf8EuzAwzDJ0ZoJzLmUIptFB6oLSlLaUtPVBaej5COfX8+7XMMO5odtbla963Z6DQmezszibzJJ8QQkk/z/d93vd34HDe1Jt6/SqVOvsuwzA2hmGzLMv+jvN1qnQ6/Q2GYbcYhgUhn2fOGYa5D+AtzuteAN5mGFZdkb+AOJvNvsN5XQvAW/k8u9BEvoIvm83+hPM6Vj7P8m6QL8MUcjn2t5zXKXmGYTpbk6/ui+csy/7tKxE+O3uqfvbsP/jkk2cUtnCKo2QauTzTcgPJVBqyNd3zr0D+zNAgXyxi7/AEe4fHlGQqc1Py2Nn1Y1SwiP7xWXyp8qp14z+7R6ZA6BufpQKToiXI1XqYrE64vEEEY/uI7R/i+CSNVCqDQDgGu9ONNb0JYpkKo4IF+n8VOF9mzUpkp+RL7/eP4R5vBA+HJtA3JmgQaoXhKRG2HG4cJzNbkb2DrVgi8atXLq/Q6NsqAkT6Xi8fHT3D6OgdRtfAGHr50zeKCxZl8IdidM8Uio+RzuQykb0DlNFFIvs/Tybz72YymT+n0xluJpPVnpyk2HA8AUI0tnfo9Yb+7nK53n4heZ3L9e3xOcnzeple/gw6uocod8o8GJy4Uly5bsTRcZJKF08f05+F4ikSR8cI7x0gHCeUJPcSR0imUkinM0ilM0gcniAU26eQv3v9oc9cu37W5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XRCjXBgStluf2j9MFIqzdTVNrN89mFFT7nVdXiyqqWyI5UmBChny/A/d6Ra0Uv00eZWZBCozNRpErts3GR9APOq65lhfofM/PLp/yphXMy762ItnMvc+dRP1a1G1DrTFiQqhKPxOKbb9C+yGp7wPtZO7evrZ3bv3uL28e2c3netq4+WRuX19ve1f+vW1ze72939r3b0d39w7YHPb/5uIsn/LiL92lbFw+EoYk58jh6PiNa7uJ8XaqNO/CDjzp72j/q7ElOz0uP+JMLv/iqnd7Um+KU6v/c9rF3BDVaCQAAAABJRU5ErkJggg==" alt="paper-waste">
          </div>
          <div class="category-tab-title">Selejt kivét</div>
          <div class="category-tab-desc">Selejtből raktári kivét</div>
        </div>

        <div class="category-tab" onclick="switchCategory(this, 'employee')">
          <div class="category-tab-icon">
            <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAACXBIWXMAAAsTAAALEwEAmpwYAAAFgklEQVR4nO2YbUyTVxTHr73RT5tsn3RkmVRRBKYuOnEbUhBkvDid2UuWOfcFVPrw0ha/bFEznJosmcuyL3PTbTGbS8yIGTjKm7yUUvrABIxTJ8pMmPptUVpAWmxL/8u5TyG0FoVQWkw4yT+5uefc2//vPKdPkzI2H/MxH7MSntIoq2d/FIRKF1vY0xBuib3pltgPbondGDfvk1tiPW4tO+UuYJlsrgW0LM4jsVaPxDCuAAC/nJaZUcRWsbkQLomlurXM5mfwSQASoyfS7ypkmoh3Pqj5KQCMQaCArYwYgEdipqDmpwjg8Y1TRMzTl3FSU9MBkBjchSwj/ABa9mPIACR2MvwA9KoMHUBP+AG0bChkAFo2FHaAx5qfJoBHYgireZeWpYQawFXINofFPI4m3sfRRMyKjiTem32AI4n3nmoAin/LYxM6Di7pl0uWwmFKwkjrZjxsS4O7PROeP3Mx2rkD3u6dwKV3hWhNe5SjGqqlMw5TEsz5L6KleEl/39ll8Sxc0Veu3t/9xVJc+XyZMOH0AbgEQA5GO7cL095L7ygSANtFjmqols44TEm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MNiw6Pd9n06D1SI7i2AVxbD15QB9W+2kMzB9DJ1wLHgj5Mo9EgJSUFycnJ0zI9sctpgfcU1IHvqwXfVwO+txqqPcarMwbgeutI4Czjb/aork2iq0F0Jbj4XiP4nirw/D/A88+D51U4QwHgP8s6y9SNTmb2r+DieWS60k8zB9BZ7gaOxXS6GtTs5eDiAeZ5XuWdmQMUt+TwIvPdibM8na5OZnYKAHd4/vnw/dUyH/PBns74H103Ro9XlAz1AAAAAElFTkSuQmCC" alt="worker-male">
          </div>
          <div class="category-tab-title">Dolgozói kivét</div>
          <div class="category-tab-desc">Dolgozó által kivett</div>
        </div>
      </div>

      <!-- GARANCIÁLIS -->
      <div id="warranty" class="cat-tab form-section active">
        <div class="form-title">Garanciális ügyintézés</div>
        <div class="form-desc">Ügyfél garanciális igénye alapján töltse ki az adatokat</div>

        <form onsubmit="handleSubmit(event, 'warranty')">
          <div class="form-row">
            <div class="form-group">
              <label class="required">Ügyfél neve</label>
              <input id="warranty" name="name" type="text" placeholder="Ügyfél neve" autocomplete="off" required>
            </div>
            <div class="form-group">
              <label class="required">E-mail cím</label>
              <input id="warranty" name="mail" type="email" placeholder="E-mail cím" autocomplete="off" required>
            </div>
            <div class="form-group">
              <label>Rendelés azonosító</label>
              <input id="warranty" name="order_id" type="text" placeholder="Rendelés azonosító" autocomplete="off">
              <div class="form-hint">Nem kötelező</div>
            </div>
          </div>

          <div class="form-row">
            <div class="form-group">
              <label class="required">Cikkszám</label>
              <input id="warranty" name="item_id" onkeyup="CopyData(this.name, this.value)" type="text" placeholder="Cikkszám" autocomplete="off" required>
            </div>
            <div class="form-group">
              <label class="required">Bal oldal darabszám</label>
              <input id="warranty" name="left_db" value="0" onkeyup="CopyData(this.name, this.value)" type="number" min="0" placeholder="Bal oldal darabszám" autocomplete="off"required>
            </div>
            <div class="form-group">
              <label class="required">Jobb oldal darabszám</label>
              <input id="warranty" name="right_db" value="0" onkeyup="CopyData(this.name, this.value)" type="number" min="0" placeholder="Jobb oldal darabszám" autocomplete="off" required>
            </div>
          </div>

          <div class="form-row">
            <div class="form-group">
              <label class="required">Garancia típusa</label>
              <select id="warranty" name="reason" required>
                <option value="">-- Válassz --</option>
                <option value="Felszerelési törés garancia">Felszerelési törés garancia</option>
                <option value="Szállítási törés garancia">Szállítási törés garancia</option>
                <option value="Téves rendelés garancia">Téves rendelés garancia</option>
                <option value="Csomagolási hiba garancia">Csomagolási hiba garancia</option>
                <option value="Export partner garancia">Export partner garancia</option>
                <option value="Nagyker partner garancia">Nagyker partner garancia</option>
                <option value="1 éves vásárolt garancia">1 éves vásárolt garancia</option>
                <option value="2 éves vásárolt garancia">2 éves vásárolt garancia</option>
              </select>
            </div>
          </div>

          <div class="form-row full">
            <div class="form-group">
              <label>Megjegyzés</label>
              <textarea id="warranty" name="note" placeholder="Megjegyzés a kiszedéshez..." autocomplete="off"></textarea>
              <div class="form-hint">Nem kötelező</div>
            </div>
          </div>

          <div class="form-actions">
            <button type="submit" class="btn-primary">Rögzítés</button>
          </div>
        </form>
      </div>

      <!-- SELEJT -->
      <div id="scrap" class="cat-tab form-section">
        <div class="form-title">Selejt kivét</div>
        <div class="form-desc">Raktári selejt adatait rögzítse az alábbi űrlapon</div>

        <form onsubmit="handleSubmit(event, 'scrap')">
          <div class="form-row">
            <div class="form-group">
              <label class="required">Raktárhely</label>
              <input id="scrap" name="wh_id" type="text" placeholder="Raktárhely" autocomplete="off" required>
            </div>
          </div>

          <div class="form-row">
            <div class="form-group">
              <label class="required">Cikkszám</label>
              <input id="scrap" name="item_id" onkeyup="CopyData(this.name, this.value)" type="text" placeholder="Cikkszám" autocomplete="off" required>
            </div>
            <div class="form-group">
              <label class="required">Bal oldal darabszám</label>
              <input id="scrap" name="left_db" value="0" onkeyup="CopyData(this.name, this.value)" type="number" min="0" placeholder="Bal oldal darabszám" autocomplete="off" required>
            </div>
            <div class="form-group">
              <label class="required">Jobb oldal darabszám</label>
              <input id="scrap" name="right_db" value="0" onkeyup="CopyData(this.name, this.value)" type="number" min="0" placeholder="Jobb oldal darabszám" autocomplete="off" required>
            </div>
          </div>

          <div class="form-row full">
            <div class="form-group">
              <label class="required">Selejt oka</label>
              <textarea id="scrap" name="reason" placeholder="Részletes leírás a selejt okáról..." autocomplete="off" required></textarea>
            </div>
          </div>

          <div class="form-actions">
            <button type="submit" class="btn-primary">Rögzítés</button>
          </div>
        </form>
      </div>

      <!-- DOLGOZÓI -->
      <div id="employee" class="cat-tab form-section">
        <div class="form-title">Dolgozói kivét</div>
        <div class="form-desc">Dolgozó által kivett terméket rögzítse itt</div>

        <div class="info-banner">
          <strong>Infó:</strong> A dolgozó ID nem kötelező mező! A szaturnusz rendszerben létező fiókokhoz való társításra szolgál.
        </div>

        <form onsubmit="handleSubmit(event, 'employee')">
          <div class="form-row">
            <div class="form-group">
              <label class="required">Dolgozó neve</label>
              <input id="employee" name="name"type="text" placeholder="Dolgozó neve" list="employee_list" oninput="EmployeeName(this.value);" autocomplete="off" required>
              <datalist id="employee_list" role="listbox"></datalist>
            </div>
            <div class="form-group">
              <label>Dolgozó ID</label>
              <input id="employee" title="Válasszon a névlistából" name="uid" type="text" placeholder="Dolgozó ID" autocomplete="off" disabled>
              <div class="form-hint">Válasszon a névlistából</div>
            </div>
          </div>

          <div class="form-row">
            <div class="form-group">
              <label class="required">Cikkszám</label>
              <input id="employee" name="item_id" onkeyup="CopyData(this.name, this.value)" type="text" placeholder="Cikkszám" autocomplete="off" required>
            </div>
            <div class="form-group">
              <label class="required">Bal oldal darabszám</label>
              <input id="employee" name="left_db" value="0" onkeyup="CopyData(this.name, this.value)" type="number" min="0" placeholder="Bal oldal darabszám" autocomplete="off" required>
            </div>
            <div class="form-group">
              <label class="required">Jobb oldal darabszám</label>
              <input id="employee" name="right_db" value="0" onkeyup="CopyData(this.name, this.value)" type="number" min="0" placeholder="Jobb oldal darabszám" autocomplete="off" required>
            </div>
          </div>

          <div class="form-actions">
            <button type="submit" class="btn-primary">Rögzítés</button>
          </div>
        </form>

      </div>

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

      <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>Ügyfél / Raktár / Dolgozó neve: </p>
          <input type="text" id="filter-name" placeholder="Ügyfél / Raktár / Dolgozó 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>Időtartam kezdet: </p>
          <input type="datetime-local" id="filter-start_datetime" onchange="SendFilter();" >
        </div><div style="display: inline; float: left; padding-left: 15px;">
        <p>Időtartam vége: </p>
          <input type="datetime-local" id="filter-end_datetime" onchange="SendFilter();">
        </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>

      <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="table">
            <thead>
              <tr style="top: 0px; position: sticky; z-index: 1;">
                <th >Ügyfél / Raktár / Dolgozó neve</th>
                <th >Cikkszám</th>
                <th >Dátum</th>
                <th style="width: 100px;">Jobb db</th>
                <th style="width: 100px;">Bal db</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="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">
      var ActiveCategory = "warranty";
    	function switchCategory(element, categoryId) {
    		document.querySelectorAll('.category-tab').forEach(tab => tab.classList.remove('active'));
    		element.classList.add('active');

    		document.querySelectorAll('.form-section').forEach(section => section.classList.remove('active'));
    		document.getElementById(categoryId).classList.add('active');

        ActiveCategory = categoryId;
        LoadTable();
    	}

      /* Kereső */
      function LoadFilter() {
        const body = 'func=filter';
        get_POST_information("wh_remove.php", body, function(text) {
          let response = JSON.parse(text);
          if (response.result == "ok") {
            document.getElementById('filter-perpage').innerHTML = response.perpage;
            document.getElementById('employee_list').innerHTML = response.userselect;
            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 name = document.getElementById("filter-name").value;
        var start_datetime = document.getElementById("filter-start_datetime").value;
        var end_datetime = document.getElementById("filter-end_datetime").value;

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

        const body = 'func=table&perpage=' + perpage + '&cpage=' + cpage + '&category=' + ActiveCategory + '&item_id=' + encodeURIComponent(item_id).replace(/%20/g, '+') + '&start_datetime=' + encodeURIComponent(start_datetime).replace(/%20/g, '+') +'&end_datetime=' + encodeURIComponent(end_datetime).replace(/%20/g, '+') + '&name=' + encodeURIComponent(name).replace(/%20/g, '+');
        get_POST_information("wh_remove.php", body, function(text) {
          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);
                var newCell_6 = newRow.insertCell(5);

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

      function OpenInfo(category, rid) {
        Loading();
        const body = 'func=OpenInfo&category=' + category + "&rid=" + rid;
        get_POST_information("wh_remove.php", body, function(text) {
          Loading(false);
          let response = JSON.parse(text);
          if (response.result == "ok") {
            CreateAlertBox("Adatlap", response.html);
          } else {
            GenerateAlerts("error", response.result);
          }
        }, function() {
          Loading(false);
          GenerateAlerts("error", "Hálózati hiba!");
        });
      }

      /* Kiszedés létrehozás */
      async function SendCreateRemoval(json, category) {
        try {
          const formData = new FormData();
          formData.append('func', 'CreateRemoval');
          formData.append('category', category);
          formData.append('data', JSON.stringify(json));

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

          const result = await response.text();
          return result;
        } catch (error) {
          console.error('Hiba:', error);
          return null;
        }
      }
      function handleSubmit(event, type) {
    		event.preventDefault();
        Loading();
        document.querySelector('input#employee[name="uid"]').disabled = false;

    		const formData = new FormData(event.target);
    		const data = Object.fromEntries(formData);

        document.querySelector('input#employee[name="uid"]').disabled = true;

        const dataArray = [];

        Object.entries(data).forEach(([paramName, paramValue]) => { dataArray.push({ name: paramName, value: paramValue }); });

        if (type == "scrap") {
          ScrapRemoval(
            document.querySelector('input#scrap[name="item_id"]').value,
            parseInt(document.querySelector('input#scrap[name="right_db"]').value),
            parseInt(document.querySelector('input#scrap[name="left_db"]').value),
            document.querySelector('input#scrap[name="wh_id"]').value,
            dataArray
          );
          return;
        }

        SendCreateRemoval(dataArray, type).then(result => {
          Loading(false);
          if (!(result == "ok" || result == "reload - ok")) {
            GenerateAlerts("error", result);
          } else {
            GenerateAlerts("success", "Sikeresen regisztrálta a kivétet!");
            if (type == "warranty") {
              var amount = Math.min(
                parseInt(document.querySelector('input#warranty[name="right_db"]').value),
                parseInt(document.querySelector('input#warranty[name="left_db"]').value)
              );
              ReservItem(
                document.querySelector('input#warranty[name="item_id"]').value,
                amount,
                "Garanciális - " + document.querySelector('input#warranty[name="name"]').value,
                document.querySelector('input#warranty[name="order_id"]').value,
                document.querySelector('input#warranty[name="name"]').value,
                document.querySelector('input#warranty[name="mail"]').value,
                document.querySelector('textarea#warranty[name="note"]').value, 0
              );

              var difference = Math.abs(
                parseInt(document.querySelector('input#warranty[name="right_db"]').value) -
                parseInt(document.querySelector('input#warranty[name="left_db"]').value)
              );

              if (parseInt(document.querySelector('input#warranty[name="right_db"]').value) > parseInt(document.querySelector('input#warranty[name="left_db"]').value)) {
                ReservItem(
                  document.querySelector('input#warranty[name="item_id"]').value,
                  difference,
                  "Garanciális - " + document.querySelector('input#warranty[name="name"]').value,
                  document.querySelector('input#warranty[name="order_id"]').value,
                  document.querySelector('input#warranty[name="name"]').value,
                  document.querySelector('input#warranty[name="mail"]').value,
                  document.querySelector('textarea#warranty[name="note"]').value, 1
                );
              } else if (parseInt(document.querySelector('input#warranty[name="right_db"]').value) < parseInt(document.querySelector('input#warranty[name="left_db"]').value)) {
                ReservItem(
                  document.querySelector('input#warranty[name="item_id"]').value,
                  difference,
                  "Garanciális - " + document.querySelector('input#warranty[name="name"]').value,
                  document.querySelector('input#warranty[name="order_id"]').value,
                  document.querySelector('input#warranty[name="name"]').value,
                  document.querySelector('input#warranty[name="mail"]').value,
                  document.querySelector('textarea#warranty[name="note"]').value, 2
                );
              }

            } else if (type == "employee") {
              var amount = Math.min(
                parseInt(document.querySelector('input#employee[name="right_db"]').value),
                parseInt(document.querySelector('input#employee[name="left_db"]').value)
              );
              ReservItem(
                document.querySelector('input#employee[name="item_id"]').value,
                amount,
                "Dolgozói - " + document.querySelector('input#employee[name="name"]').value,
                document.querySelector('input#employee[name="uid"]').value,
                document.querySelector('input#employee[name="name"]').value,
                "", "", 0
              );

              var difference = Math.abs(
                parseInt(document.querySelector('input#employee[name="right_db"]').value) -
                parseInt(document.querySelector('input#employee[name="left_db"]').value)
              );

              if (parseInt(document.querySelector('input#employee[name="right_db"]').value) > parseInt(document.querySelector('input#employee[name="left_db"]').value)) {
                ReservItem(
                  document.querySelector('input#employee[name="item_id"]').value,
                  difference,
                  "Dolgozói - " + document.querySelector('input#employee[name="name"]').value,
                  document.querySelector('input#employee[name="uid"]').value,
                  document.querySelector('input#employee[name="name"]').value,
                  "", "", 1
                );
              } else if (parseInt(document.querySelector('input#employee[name="right_db"]').value) < parseInt(document.querySelector('input#employee[name="left_db"]').value)) {
                ReservItem(
                  document.querySelector('input#employee[name="item_id"]').value,
                  difference,
                  "Dolgozói - " + document.querySelector('input#employee[name="name"]').value,
                  document.querySelector('input#employee[name="uid"]').value,
                  document.querySelector('input#employee[name="name"]').value,
                  "", "", 2
                );
              }
            }
            LoadTable();
          }

          const inputs = document.querySelectorAll('input[name="right_db"], input[name="left_db"]');
          inputs.forEach(input => {
            input.value = '0';
          });

          const inputs2 = document.querySelectorAll('input[name="item_id"]');
          inputs2.forEach(input => {
            input.value = '';
          });
        });


    	}

      function ReservItem(item_id, amount, reason, order_id, order_name, order_mail, note, amount_type, order_primary_source_input = null) {
        if (Number(amount) <= 0 || isNaN(Number(amount))) return;

        if (order_primary_source_input != null || Number(amount_type) != 0) {
          if (Number(amount_type) != 0) {
            order_primary_source = 0;
          } else {
            order_primary_source = order_primary_source_input;
          }
          Loading();
          const body = 'func=reservitem&item_id=' + encodeURIComponent(item_id).replace(/%20/g, '+') + '&primary_source=' + order_primary_source + '&amount_type=' + amount_type + '&reason=' + encodeURIComponent(reason).replace(/%20/g, '+') + '&amount=' + amount + '&order_id=' + encodeURIComponent(order_id).replace(/%20/g, '+') + '&order_name=' + encodeURIComponent(order_name).replace(/%20/g, '+') + '&order_mail=' + encodeURIComponent(order_mail).replace(/%20/g, '+') + '&note=' + encodeURIComponent(note).replace(/%20/g, '+');
          get_POST_information("wh_orders.php", body, function(text) {
            let response = JSON.parse(text);
            Loading(false);
            if (response.result == "ok") {
              LoadTable();
            } else {
              GenerateAlerts("error", response.result);
            }
          }, function() {
            Loading(false);
            GenerateAlerts("error", "Hálózati hiba!");
          });
          return;
        } else {
          var html = `
          <p><b>Válassza ki, hogy elsődlegesen honnan legyen kiszedve az alábbi rendelés:</b><br>
          ${reason}</p>
          <button id="AlertBtnFoil" style="float: right; margin-left: 15px;">Fóliás</button>
          <button id="AlertBtnBox" style="float: right;">Dobozos</button>
          `;
          const overlay = CreateAlertBox('Elsődleges forrás', html, false);
          document.getElementById('AlertBtnFoil').onclick = function () { ReservItem(item_id, amount, reason, order_id, order_name, order_mail, note, amount_type, 1),  CloseAlertBox(overlay); };
          document.getElementById('AlertBtnBox').onclick = function () { ReservItem(item_id, amount, reason, order_id, order_name, order_mail, note, amount_type, 0), CloseAlertBox(overlay); };
          return;
        }
      }
      function ScrapRemoval(item_id, right, left, warehouse_code, dataArray) {
        Loading();
        const body = 'func=ScrapRemoval&item_id=' + encodeURIComponent(item_id).replace(/%20/g, '+') + '&left=' + left + '&right=' + right + '&warehouse_code=' + encodeURIComponent(warehouse_code).replace(/%20/g, '+');
        get_POST_information("wh_remove.php", body, function(text) {
          let response = JSON.parse(text);
          Loading(false);
          if (response.result == "ok") {
            GenerateAlerts("success", "Sikeresen törölte a raktárból");

            var type = "scrap"
            SendCreateRemoval(dataArray, type).then(result => {
              Loading(false);
              if (!(result == "ok" || result == "reload - ok")) {
                GenerateAlerts("error", result);
              } else {
                GenerateAlerts("success", "Sikeresen regisztrálta a kivétet!");
                LoadTable();
              }

              const inputs = document.querySelectorAll('input[name="right_db"], input[name="left_db"]');
              inputs.forEach(input => {
                input.value = '0';
              });

              const inputs2 = document.querySelectorAll('input[name="item_id"]');
              inputs2.forEach(input => {
                input.value = '';
              });
            });

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

      /* Egyéb */
      function CopyData(name, value) {
        const inputs = document.querySelectorAll(`input[name="${name}"]`);
        inputs.forEach(input => {
          input.value = value;
        });
      }
      function EmployeeName(name) {
        document.querySelector('input#employee[name="uid"]').value = name.includes(" - ") ? name.split(" - ")[1] : "";
        document.querySelector('input#employee[name="name"]').value = name.includes(" - ") ? name.split(" - ")[0] : name;
      }

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