<?php

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

if (!(UserHasPerm('edit_item_introduction_basic_data') || UserHasPerm('edit_item_introduction_tools_send') || UserHasPerm('edit_item_introduction_testing') || UserHasPerm('edit_item_introduction_final') || UserHasPerm('read_item_introduction'))) {
  StopAndDie();
}

if (isset($_POST['func'])) {
  if (htmlspecialchars($_POST["func"]) == "LoadItemCreatorInProgressList") {
    $IntroductionItems = [];

    $query = "SELECT * FROM item_introduction WHERE status != 'complete'";
    if ($result = $conn->query($query)) {
      while ($introduction = $result->fetch_assoc()) {
        $user_can_edit = 2;
        $status_text = "";

        if (UserHasPerm('read_item_introduction')) {$user_can_edit = 3;}

        if ($introduction["status"] == "basic_data") {if (UserHasPerm('edit_item_introduction_basic_data')) {$user_can_edit = 1;}$status_text = "Alap adatok feltöltése";}
        if ($introduction["status"] == "tools_send") {if (UserHasPerm('edit_item_introduction_tools_send')) {$user_can_edit = 1;}$status_text = "Szerszámtervek vágásra továbbküldve";}
        if ($introduction["status"] == "testing") {if (UserHasPerm('edit_item_introduction_testing')) {$user_can_edit = 1;}$status_text = "Termékpróba szakasz";}
        if ($introduction["status"] == "deficit") {if (UserHasPerm('edit_item_introduction_basic_data')) {$user_can_edit = 1;}$status_text = "Adatpótlási szakasz";}
        if ($introduction["status"] == "last_statement") {if (UserHasPerm('edit_item_introduction_basic_data')) {$user_can_edit = 1;}$status_text = "Végső nyilatkozatok beküldése";}
        if ($introduction["status"] == "final") {if (UserHasPerm('edit_item_introduction_final')) {$user_can_edit = 1;}$status_text = "Végső ellenőrzés";}

        $IntroductionItems[] = [
          "item_id" => $introduction["item_id"],
          "status" => $status_text,
          "user_can_edit" => $user_can_edit
        ];

      }
    }

    usort($IntroductionItems, function ($a, $b) {return strcoll($a["user_can_edit"], $b["user_can_edit"]);});

    $responseStr = '';
    for ($i=0; $i < count($IntroductionItems); $i++) {
      if ($responseStr != "") {
        $responseStr = $responseStr."|%|";
      }

      $responseStr = $responseStr.$IntroductionItems[$i]['item_id'].'||'.$IntroductionItems[$i]['status'].'||'.$IntroductionItems[$i]['user_can_edit'];
    }

    echo '{"status": "ok", "data": "'.$responseStr.'"}';

  } else if (htmlspecialchars($_POST["func"]) == "SaveNewIntroduction") {
    $item_id = htmlspecialchars(str_replace(' ', '+', $_POST['item_id']));
    $json = "";

    $sql = mysqli_query($conn,"SELECT name_in_db FROM pr_parameters WHERE item_id = '$item_id'");
    $pr_parameters = mysqli_fetch_array($sql);

    $sql = mysqli_query($conn,"SELECT status FROM item_introduction WHERE item_id = '$item_id'");
    $item_introduction = mysqli_fetch_array($sql);

    if ($item_id == "") {
      $json = json_encode(["status" => "error", "message" => "Kötelező egy cikkszámot megadni!"]);
    } else if ($pr_parameters) {
      $json = json_encode(["status" => "error", "message" => "A megadott cikkszámmal, már létezik Termék!"]);
    } else if ($item_introduction) {
      $json = json_encode(["status" => "error", "message" => "A megadott cikkszámmal, már megkezdődött a bevezetési folyamat!"]);
    } else if(!UserHasPerm('edit_item_introduction_basic_data')) {
      $json = json_encode(["status" => "error", "message" => "Jogosultság megtagadva! Önnek nincsen joga termék bevezetést elkezdeni!"]);
    } else {
      $sql = mysqli_query($conn,"INSERT INTO item_introduction(item_id, status) VALUES ('$item_id', 'basic_data')");
      $json = json_encode(["status" => "ok"]);
    }

    echo $json;
  } else if (htmlspecialchars($_POST["func"]) == "OpenIntroduction") {
    $item_id = htmlspecialchars(str_replace(' ', '+', $_POST['item_id']));
    $json = "";

    $sql = mysqli_query($conn,"SELECT status FROM item_introduction WHERE item_id = '$item_id'");
    $item_introduction = mysqli_fetch_array($sql);

    if ($item_introduction) {
      $json = json_encode(["status" => "ok", "current_stage" => $item_introduction["status"]]);
    } else {
      $json = json_encode(["status" => "error", "message" => "A megadott cikkszámmal nem létezik bevezetési folyamat!"]);
    }

    echo $json;
  } else if (htmlspecialchars($_POST["func"]) == "StartToolsSend") {
    $item_id = htmlspecialchars(str_replace(' ', '+', $_POST['item_id']));
    $json = "";

    if (UserHasPerm('edit_item_introduction_basic_data')) {
      $json = json_encode(["status" => "ok"]);
      $sql = mysqli_query($conn,"UPDATE item_introduction SET status = 'tools_send' WHERE item_id = '$item_id'");
    } else {
      $json = json_encode(["status" => "error", "message" => "Jogosultság megtagadva! Önnek nincsen joga alap adatokat menteni!"]);
    }

    echo $json;
  } else if (htmlspecialchars($_POST["func"]) == "OpenBasicData") {
    $item_id = htmlspecialchars(str_replace(' ', '+', $_POST['item_id']));
    $json = "";
    $IsUserCanEdit = UserHasPerm('edit_item_introduction_basic_data');
    $all_product_information = array();

    $data = json_decode(file_get_contents($currentUrl."/managers/prdb.json"), true);
    if ($data) {
      foreach ($data["DBList"] as $table) {

        $sql = mysqli_query($conn,"SELECT item_id FROM ".$table["ID"]." WHERE item_id = '$item_id'");
        $test = mysqli_fetch_array($sql);

        if ($test) {
          //Ha létezik már adat erről a cikkszámról
          $query = "SELECT * FROM ".$table["ID"]." WHERE item_id = '$item_id'";
          if ($result = $conn->query($query)) {
            while ($dbdata = $result->fetch_assoc()) {
              foreach ($data["Parameters"] as $param) {
                if (strpos($param["ID"], $table['ID'] . "_") === 0) {
                  $newID = substr($param["ID"], strlen($table['ID']) + 1);
                  $all_product_information = array_merge($all_product_information, [$param["ID"] => $param["NAME"]."||".$dbdata[$newID]]);

                  if ($param["DATALIST"]) {
                    $query = "SELECT DISTINCT $newID FROM ".$table["ID"]." ORDER BY $newID ASC";
                    $GeneratedDatalist = "";
                    if ($result = $conn->query($query)) {
                      while ($datalist = $result->fetch_assoc()) {
                        $GeneratedDatalist .= '<option>'.$datalist[$newID].'</option>';
                      }
                    }

                    $all_product_information = array_merge($all_product_information, [$param["ID"]."_datalist" => $GeneratedDatalist]);
                  } else {
                    $all_product_information = array_merge($all_product_information, [$param["ID"]."_datalist" => ""]);
                  }
                }
              }

              $uploader_uid = $dbdata["uploader_uid"];
              $sql = mysqli_query($conn,"SELECT full_name FROM users WHERE uid = '$uploader_uid'");
              $userUploaderName = $coderclass->decode(mysqli_fetch_array($sql)[0], "TIT4");
              $all_product_information = array_merge($all_product_information, [$table['ID'] => $table["NAME"]]);
              $all_product_information = array_merge($all_product_information, [$table['ID'].'_can_see' => true]);
              $all_product_information = array_merge($all_product_information, [$table['ID'].'_can_edit' => $IsUserCanEdit]);

            }
          }
        } else {
          //Ha még nem létezik adat ebben a táblában a cikkszámról
          foreach ($data["Parameters"] as $param) {
            if (strpos($param["ID"], $table['ID'] . "_") === 0) {
              $newID = substr($param["ID"], strlen($table['ID']) + 1);
              $all_product_information = array_merge($all_product_information, [$param["ID"] => $param["NAME"]."||+"]);
              $all_product_information = array_merge($all_product_information, [$table['ID'] => $table["NAME"]]);
              $all_product_information = array_merge($all_product_information, [$table['ID'].'_can_see' => true]);
              $all_product_information = array_merge($all_product_information, [$table['ID'].'_can_edit' => $IsUserCanEdit]);

              if ($param["DATALIST"]) {
                $query = "SELECT DISTINCT $newID FROM ".$table["ID"]." ORDER BY $newID ASC";
                $GeneratedDatalist = "";
                if ($result = $conn->query($query)) {
                  while ($datalist = $result->fetch_assoc()) {
                    $GeneratedDatalist .= '<option>'.$datalist[$newID].'</option>';
                  }
                }

                $all_product_information = array_merge($all_product_information, [$param["ID"]."_datalist" => $GeneratedDatalist]);
              } else {
                $all_product_information = array_merge($all_product_information, [$param["ID"]."_datalist" => ""]);
              }

            }
          }
        }

      }

      $all_product_information = array_merge($all_product_information, ["status" => "ok", 'item_id' => $item_id]);
      $json = json_encode($all_product_information);
    }

    echo $json;
  } else if (htmlspecialchars($_POST["func"]) == "OpenToolsSend") {
    $item_id = htmlspecialchars(str_replace(' ', '+', $_POST['item_id']));
    $json = "";

    $sql = mysqli_query($conn,"SELECT is_tool_ok, is_tool_created, is_tool_can_be_tested FROM item_introduction WHERE item_id = '$item_id'");
    $item_introduction = mysqli_fetch_array($sql);

    if ($item_introduction) {

      $is_tool_ok = '';
      $is_tool_created = '';
      $is_tool_can_be_tested = '';

      if ($item_introduction["is_tool_ok"] != null && $item_introduction["is_tool_ok"] != "") {
        $is_tool_ok_uid = explode("|", $item_introduction["is_tool_ok"])[0];
        $sql = mysqli_query($conn,"SELECT full_name FROM users WHERE uid = '$is_tool_ok_uid'");
        $is_tool_ok_name = $coderclass->decode(mysqli_fetch_array($sql)[0], "TIT4");
        $is_tool_ok_time = explode("|", $item_introduction["is_tool_ok"])[1];

        $is_tool_ok = $is_tool_ok_name." - ".date("Y-m-d H:i:s", $is_tool_ok_time);
      }

      if ($item_introduction["is_tool_created"] != null && $item_introduction["is_tool_created"] != "") {
        $is_tool_created_uid = explode("|", $item_introduction["is_tool_created"])[0];
        $sql = mysqli_query($conn,"SELECT full_name FROM users WHERE uid = '$is_tool_created_uid'");
        $is_tool_created_name = $coderclass->decode(mysqli_fetch_array($sql)[0], "TIT4");
        $is_tool_created_time = explode("|", $item_introduction["is_tool_created"])[1];

        $is_tool_created = $is_tool_created_name." - ".date("Y-m-d H:i:s", $is_tool_created_time);
      }

      if ($item_introduction["is_tool_can_be_tested"] != null && $item_introduction["is_tool_can_be_tested"] != "") {
        $is_tool_can_be_tested_uid = explode("|", $item_introduction["is_tool_can_be_tested"])[0];
        $sql = mysqli_query($conn,"SELECT full_name FROM users WHERE uid = '$is_tool_can_be_tested_uid'");
        $is_tool_can_be_tested_name = $coderclass->decode(mysqli_fetch_array($sql)[0], "TIT4");
        $is_tool_can_be_tested_time = explode("|", $item_introduction["is_tool_can_be_tested"])[1];

        $is_tool_can_be_tested = $is_tool_can_be_tested_name." - ".date("Y-m-d H:i:s", $is_tool_can_be_tested_time);
      }

      $json = json_encode([
        "status" => "ok",
        "is_tool_ok" => $is_tool_ok,
        "is_tool_created" => $is_tool_created,
        "is_tool_can_be_tested" => $is_tool_can_be_tested,
        "user_can_edit" => UserHasPerm("edit_item_introduction_tools_send")
      ]);
    } else {
      $json = json_encode(["status" => "error", "message" => "A megadott cikkszámmal nem létezik bevezetési folyamat!"]);
    }

    echo $json;
  } else if (htmlspecialchars($_POST["func"]) == "OpenTesting") {
    $item_id = htmlspecialchars(str_replace(' ', '+', $_POST['item_id']));
    $json = "";

    $sql = mysqli_query($conn,"SELECT is_tested_in_car, is_production_ready FROM item_introduction WHERE item_id = '$item_id'");
    $item_introduction = mysqli_fetch_array($sql);

    if ($item_introduction) {

      $is_tested_in_car = '';
      $is_production_ready = '';


      if ($item_introduction["is_tested_in_car"] != null && $item_introduction["is_tested_in_car"] != "") {
        $is_tested_in_car_uid = explode("|", $item_introduction["is_tested_in_car"])[0];
        $sql = mysqli_query($conn,"SELECT full_name FROM users WHERE uid = '$is_tested_in_car_uid'");
        $is_tested_in_car_name = $coderclass->decode(mysqli_fetch_array($sql)[0], "TIT4");
        $is_tested_in_car_time = explode("|", $item_introduction["is_tested_in_car"])[1];

        $is_tested_in_car = $is_tested_in_car_name." - ".date("Y-m-d H:i:s", $is_tested_in_car_time);
      }

      if ($item_introduction["is_production_ready"] != null && $item_introduction["is_production_ready"] != "") {
        $is_production_ready_uid = explode("|", $item_introduction["is_production_ready"])[0];
        $sql = mysqli_query($conn,"SELECT full_name FROM users WHERE uid = '$is_production_ready_uid'");
        $is_production_ready_name = $coderclass->decode(mysqli_fetch_array($sql)[0], "TIT4");
        $is_production_ready_time = explode("|", $item_introduction["is_production_ready"])[1];

        if (count(explode("|", $item_introduction["is_production_ready"])) == 3) {
          $is_production_ready = "<span style='color: #c0392b'>".explode("|", $item_introduction["is_production_ready"])[2]."</span> - ".$is_production_ready_name." - ".date("Y-m-d H:i:s", $is_production_ready_time);
        } else {
          $is_production_ready = $is_production_ready_name." - ".date("Y-m-d H:i:s", $is_production_ready_time);
        }
      }


      $json = json_encode([
        "status" => "ok",
        "is_tested_in_car" => $is_tested_in_car,
        "is_production_ready" => $is_production_ready,
        "user_can_edit" => UserHasPerm("edit_item_introduction_testing")
      ]);
    } else {
      $json = json_encode(["status" => "error", "message" => "A megadott cikkszámmal nem létezik bevezetési folyamat!"]);
    }

    echo $json;
  } else if (htmlspecialchars($_POST["func"]) == "OpenLastStatement") {
    $item_id = htmlspecialchars(str_replace(' ', '+', $_POST['item_id']));
    $json = "";

    $sql = mysqli_query($conn,"SELECT is_kulcssoft_ready, is_on_web, is_data_valid, is_export_ready FROM item_introduction WHERE item_id = '$item_id'");
    $item_introduction = mysqli_fetch_array($sql);

    if ($item_introduction) {

      $is_kulcssoft_ready = '';
      $is_on_web = '';
      $is_data_valid = '';
      $is_export_ready = '';

      if ($item_introduction["is_kulcssoft_ready"] != null && $item_introduction["is_kulcssoft_ready"] != "") {
        $is_kulcssoft_ready_uid = explode("|", $item_introduction["is_kulcssoft_ready"])[0];
        $sql = mysqli_query($conn,"SELECT full_name FROM users WHERE uid = '$is_kulcssoft_ready_uid'");
        $is_kulcssoft_ready_name = $coderclass->decode(mysqli_fetch_array($sql)[0], "TIT4");
        $is_kulcssoft_ready_time = explode("|", $item_introduction["is_kulcssoft_ready"])[1];

        $is_kulcssoft_ready = $is_kulcssoft_ready_name." - ".date("Y-m-d H:i:s", $is_kulcssoft_ready_time);
      }

      if ($item_introduction["is_on_web"] != null && $item_introduction["is_on_web"] != "") {
        $is_on_web_uid = explode("|", $item_introduction["is_on_web"])[0];
        $sql = mysqli_query($conn,"SELECT full_name FROM users WHERE uid = '$is_on_web_uid'");
        $is_on_web_name = $coderclass->decode(mysqli_fetch_array($sql)[0], "TIT4");
        $is_on_web_time = explode("|", $item_introduction["is_on_web"])[1];

        $is_on_web = $is_on_web_name." - ".date("Y-m-d H:i:s", $is_on_web_time);
      }

      if ($item_introduction["is_data_valid"] != null && $item_introduction["is_data_valid"] != "") {
        $is_data_valid_uid = explode("|", $item_introduction["is_data_valid"])[0];
        $sql = mysqli_query($conn,"SELECT full_name FROM users WHERE uid = '$is_data_valid_uid'");
        $is_data_valid_name = $coderclass->decode(mysqli_fetch_array($sql)[0], "TIT4");
        $is_data_valid_time = explode("|", $item_introduction["is_data_valid"])[1];

        $is_data_valid = $is_data_valid_name." - ".date("Y-m-d H:i:s", $is_data_valid_time);
      }

      if ($item_introduction["is_export_ready"] != null && $item_introduction["is_export_ready"] != "") {
        $is_export_ready_uid = explode("|", $item_introduction["is_export_ready"])[0];
        $sql = mysqli_query($conn,"SELECT full_name FROM users WHERE uid = '$is_export_ready_uid'");
        $is_export_ready_name = $coderclass->decode(mysqli_fetch_array($sql)[0], "TIT4");
        $is_export_ready_time = explode("|", $item_introduction["is_export_ready"])[1];

        $is_export_ready = $is_export_ready_name." - ".date("Y-m-d H:i:s", $is_export_ready_time);
      }

      $json = json_encode([
        "status" => "ok",
        "is_kulcssoft_ready" => $is_kulcssoft_ready,
        "is_on_web" => $is_on_web,
        "is_data_valid" => $is_data_valid,
        "is_export_ready" => $is_export_ready,
        "user_can_edit" => UserHasPerm("edit_item_introduction_basic_data")
      ]);
    } else {
      $json = json_encode(["status" => "error", "message" => "A megadott cikkszámmal nem létezik bevezetési folyamat!"]);
    }

    echo $json;
  } else if (htmlspecialchars($_POST["func"]) == "OpenFinal") {
    $item_id = htmlspecialchars(str_replace(' ', '+', $_POST['item_id']));
    $all_information = array();

    $Parameters = ["is_tool_ok", "is_tool_created", "is_tool_can_be_tested", "is_tested_in_car", "is_production_ready", "is_kulcssoft_ready", "is_on_web", "is_data_valid", "is_export_ready"];

    for ($i=0; $i < count($Parameters); $i++) {

      $sql = mysqli_query($conn,"SELECT ".$Parameters[$i]." FROM item_introduction WHERE item_id = '$item_id'");
      $item_introduction = mysqli_fetch_array($sql);

      $this_uid = explode("|", $item_introduction[0])[0];
      $sql = mysqli_query($conn,"SELECT full_name FROM users WHERE uid = '$this_uid'");
      $this_name = $coderclass->decode(mysqli_fetch_array($sql)[0], "TIT4");
      $this_time = explode("|", $item_introduction[0])[1];

      $temp = $this_name." - ".date("Y-m-d H:i:s", $this_time);

      $all_information = array_merge($all_information, [$Parameters[$i] => $temp]);
    }

    $all_information = array_merge($all_information, ['status' => 'ok']);
    $all_information = array_merge($all_information, ['user_can_edit' => UserHasPerm("edit_item_introduction_final")]);
    echo json_encode($all_information);
  } else if (htmlspecialchars($_POST["func"]) == "OpenComplete") {
    $item_id = htmlspecialchars(str_replace(' ', '+', $_POST['item_id']));

    if (UserHasPerm('read_item_introduction') || UserHasPerm('edit_item_introduction_final')) {
      $sql = mysqli_query($conn,"SELECT finalized_by, finalized_in FROM item_introduction WHERE item_id = '$item_id'");
      $item_introduction = mysqli_fetch_array($sql);
      $this_uid = $item_introduction["finalized_by"];
      $sql = mysqli_query($conn,"SELECT full_name FROM users WHERE uid = '$this_uid'");
      $this_name = $coderclass->decode(mysqli_fetch_array($sql)[0], "TIT4");

      $json = json_encode([
        "status" => "ok",
        "finalized_by" => $this_name,
        "finalized_in" => date("Y-m-d H:i:s", $item_introduction["finalized_in"])
      ]);
    } else {
      $json = json_encode(["status" => "error", "message" => "Jogosultság megtagadva! Önnek nincsen joga megtekinteni a lezárt Termék bevezetéseket!"]);
    }

    echo $json;
  } else if (htmlspecialchars($_POST["func"]) == "StatementEditor") {
    $item_id = htmlspecialchars(str_replace(' ', '+', $_POST['item_id']));
    $statement_id = htmlspecialchars($_POST["statement_id"]);
    $edit_to = htmlspecialchars($_POST["edit_to"]);
    $input = htmlspecialchars($_POST["input"]);

    $json = "";

    $userMustHaveThisPerm = "god_profile";
    if ($statement_id == "is_tool_ok" || $statement_id == "is_tool_created" || $statement_id == "is_tool_can_be_tested") {
      $userMustHaveThisPerm = "edit_item_introduction_tools_send";
    } else if ($statement_id == "is_tested_in_car" || $statement_id == "is_production_ready") {
      $userMustHaveThisPerm = "edit_item_introduction_testing";
    } else if ($statement_id == "is_kulcssoft_ready" || $statement_id == "is_on_web" || $statement_id == "is_data_valid" || $statement_id == "is_export_ready") {
      $userMustHaveThisPerm = "edit_item_introduction_basic_data";
    }

    if (UserHasPerm($userMustHaveThisPerm)) {
      $text = "";
      if ($edit_to == "true") {
        $toupdate = $userID."|".(time());
        if ($input != "igen") {
          $toupdate .= "|".$input;
          $sql = mysqli_query($conn,"UPDATE item_introduction SET ".$statement_id." = '".$toupdate."' WHERE item_id = '$item_id'");
          $text = "<span style='color: #c0392b'>".$input."</span> - ".$userName." - ".date("Y-m-d H:i:s", (time()));
        } else {
          $sql = mysqli_query($conn,"UPDATE item_introduction SET ".$statement_id." = '".$toupdate."' WHERE item_id = '$item_id'");
          $text = $userName." - ".date("Y-m-d H:i:s", (time()));
        }

      } else {
        $sql = mysqli_query($conn,"UPDATE item_introduction SET ".$statement_id." = null WHERE item_id = '$item_id'");
      }

      $json = json_encode(["result" => "ok", "text" => $text]);
    } else {
      $json = json_encode(["result" => "Jogosultság megtagadva! Önnek nincsen joga ezt a nyilatkozat benyújtani!"]);
    }

    echo $json;
  } else if (htmlspecialchars($_POST["func"]) == "StartTesting") {
    $item_id = htmlspecialchars(str_replace(' ', '+', $_POST['item_id']));
    $json = "";

    $sql = mysqli_query($conn,"SELECT is_tool_ok, is_tool_created, is_tool_can_be_tested FROM item_introduction WHERE item_id = '$item_id'");
    $item_introduction = mysqli_fetch_array($sql);

    if ($item_introduction["is_tool_ok"] == null || $item_introduction["is_tool_ok"] == "" || $item_introduction["is_tool_created"] == null || $item_introduction["is_tool_created"] == "" ||$item_introduction["is_tool_can_be_tested"] == null || $item_introduction["is_tool_can_be_tested"] == "") {
      $json = json_encode(["status" => "error", "message" => "Minden nyilatkozatot be kell nyújtani!"]);
    } else if (UserHasPerm('edit_item_introduction_tools_send')) {
      $json = json_encode(["status" => "ok"]);
      $sql = mysqli_query($conn,"UPDATE item_introduction SET status = 'testing' WHERE item_id = '$item_id'");
    } else {
      $json = json_encode(["status" => "error", "message" => "Jogosultság megtagadva! Önnek nincsen joga alap adatokat menteni!"]);
    }

    echo $json;
  } else if (htmlspecialchars($_POST["func"]) == "StartDeficit") {
    $item_id = htmlspecialchars(str_replace(' ', '+', $_POST['item_id']));
    $json = "";

    $sql = mysqli_query($conn,"SELECT is_tested_in_car, is_production_ready FROM item_introduction WHERE item_id = '$item_id'");
    $item_introduction = mysqli_fetch_array($sql);

    if ($item_introduction["is_tested_in_car"] == null || $item_introduction["is_tested_in_car"] == "" || $item_introduction["is_production_ready"] == null || $item_introduction["is_production_ready"] == "") {
      $json = json_encode(["status" => "error", "message" => "Minden nyilatkozatot be kell nyújtani!"]);
    } else if (count(explode("|", $item_introduction["is_production_ready"])) != 2) {
      $json = json_encode(["status" => "error", "message" => "A Termék nem sorozatgyártható! Csak abban az esetben lehet folytatni, ha a termék sorozatgyártásba felvehető!"]);
    } else if (UserHasPerm('edit_item_introduction_testing')) {
      $json = json_encode(["status" => "ok"]);
      $sql = mysqli_query($conn,"UPDATE item_introduction SET status = 'deficit' WHERE item_id = '$item_id'");
    } else {
      $json = json_encode(["status" => "error", "message" => "Jogosultság megtagadva! Önnek nincsen joga alap adatokat menteni!"]);
    }

    echo $json;
  } else if (htmlspecialchars($_POST["func"]) == "StartLastStatement") {
    $item_id = htmlspecialchars(str_replace(' ', '+', $_POST['item_id']));
    $json = "";

    if (UserHasPerm('edit_item_introduction_basic_data')) {
      $json = json_encode(["status" => "ok"]);
      $sql = mysqli_query($conn,"UPDATE item_introduction SET status = 'last_statement' WHERE item_id = '$item_id'");
    } else {
      $json = json_encode(["status" => "error", "message" => "Jogosultság megtagadva! Önnek nincsen joga alap adatokat menteni!"]);
    }

    echo $json;
  } else if (htmlspecialchars($_POST["func"]) == "StartFinal") {
    $item_id = htmlspecialchars(str_replace(' ', '+', $_POST['item_id']));
    $json = "";

    $sql = mysqli_query($conn,"SELECT is_kulcssoft_ready, is_on_web, is_data_valid, is_export_ready FROM item_introduction WHERE item_id = '$item_id'");
    $item_introduction = mysqli_fetch_array($sql);

    if ($item_introduction["is_kulcssoft_ready"] == null || $item_introduction["is_kulcssoft_ready"] == "" || $item_introduction["is_on_web"] == null || $item_introduction["is_on_web"] == "" || $item_introduction["is_data_valid"] == null || $item_introduction["is_data_valid"] == "" || $item_introduction["is_export_ready"] == null || $item_introduction["is_export_ready"] == "") {
      $json = json_encode(["status" => "error", "message" => "Minden nyilatkozatot be kell nyújtani!"]);
    } else if (UserHasPerm('edit_item_introduction_basic_data')) {
      $json = json_encode(["status" => "ok"]);
      $sql = mysqli_query($conn,"UPDATE item_introduction SET status = 'final' WHERE item_id = '$item_id'");
    } else {
      $json = json_encode(["status" => "error", "message" => "Jogosultság megtagadva! Önnek nincsen joga alap adatokat menteni!"]);
    }

    echo $json;
  } else if (htmlspecialchars($_POST["func"]) == "StartComplete") {
    $item_id = htmlspecialchars(str_replace(' ', '+', $_POST['item_id']));
    $json = "";

    if (UserHasPerm('edit_item_introduction_final')) {
      $json = json_encode(["status" => "ok"]);
      $ctime = time();
      $sql = mysqli_query($conn,"UPDATE item_introduction SET status = 'complete', finalized_in = $ctime, finalized_by = $userID WHERE item_id = '$item_id'");

      $_GET['type'] = 'daily';
      $_GET['item_id'] = $item_id;
      $_GET['silent'] = true;
      include '../managers/statistics.php';

      $data = json_decode(file_get_contents($currentUrl."/managers/prdb.json"), true);
      if ($data) {
        foreach ($data["DBList"] as $table) {
          $sqlcommand = 'UPDATE '.$table["ID"].' SET data_status = 1 WHERE item_id = "'.$item_id.'"';
          $sql = mysqli_query($conn,$sqlcommand);
        }
      }
    } else {
      $json = json_encode(["status" => "error", "message" => "Jogosultság megtagadva! Önnek nincsen joga alap adatokat menteni!"]);
    }

    echo $json;
  } else if (htmlspecialchars($_POST["func"]) == "filter" && UserHasPerm("read_item_introduction")) {

    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);

    $finalized_by = '<option value="">-- Összes --</option>';
    $query = "SELECT DISTINCT finalized_by FROM item_introduction WHERE status = 'complete' ORDER BY finalized_by ASC";
    if ($result = $conn->query($query)) {
      while ($ccat = $result->fetch_assoc()) {
        if ($ccat['finalized_by'] != null && $ccat['finalized_by'] != "") {
          $this_uid = $ccat['finalized_by'];
          $sql = mysqli_query($conn,"SELECT full_name FROM users WHERE uid = '$this_uid'");
          $this_name = $coderclass->decode(mysqli_fetch_array($sql)[0], "TIT4");
          $finalized_by .= "<option value='".$ccat['finalized_by']."'>".$this_name."</option>";
        }
      }
    }

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

    echo $json;
  } else if (htmlspecialchars($_POST["func"]) == "table" && UserHasPerm("read_item_introduction")) {
    $maxperpage = intval(htmlspecialchars($_POST["perpage"]));
    $cpage = intval(htmlspecialchars($_POST["cpage"]));
    $orderby = htmlspecialchars($_POST["orderby"]);

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

    $addquery = "";
    $isfirst = true;

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

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

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

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

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

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

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

    if ($isfirst) {
      $addquery = $addquery." WHERE status = 'complete'";
      $isfirst = false;
    } else {
      $addquery = $addquery." and status = 'complete'";
    }

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

    if ($orderby != "") {
      $addquery = $addquery." ORDER BY ".$orderby;
      if ($orderby == "finalized_in") {
        $addquery .= " DESC";
      }
      $isfirst = false;
    }

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

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

    $responseStr = '';
    $query = "SELECT item_id, finalized_in, finalized_by FROM item_introduction".$addquery." LIMIT $limit, $maxperpage";
    if ($result = $conn->query($query)) {
      while ($c_item_introduction = $result->fetch_assoc()) {

        if ($responseStr != "") {
          $responseStr .= "|%|";
        }
        $this_uid = $c_item_introduction['finalized_by'];
        $sql = mysqli_query($conn,"SELECT full_name FROM users WHERE uid = '$this_uid'");
        $this_name = $coderclass->decode(mysqli_fetch_array($sql)[0], "TIT4");

        $responseStr .= $c_item_introduction['item_id'].'/!/'.date("Y. m. d.", $c_item_introduction['finalized_in']).'/!/'.$this_name;
      }
    }

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

  }

  exit();
} else if (isset($_GET['saving']) && $_GET['saving'] == 1) {
  header("Content-Type: application/json");
  $jsonData = file_get_contents("php://input");
  $SendedData = json_decode($jsonData, true);
  $LocalData = json_decode(file_get_contents($currentUrl."/managers/prdb.json"), true);

  $item_id = $SendedData['item_id'];

  $result_list = [];
  $parameters = [];
  if ($LocalData && UserHasPerm("edit_item_introduction_basic_data")) {
    foreach ($LocalData["DBList"] as $table) {
      foreach ($SendedData as $key => $value) {
        if (strpos($key, $table["ID"] . "_") === 0) {
          $param = substr($key, strlen($table["ID"]) + 1);
          $result_list[$table["ID"]][] = ['param' => $param, 'value' => $value];
        }
      }
    }

    if (!empty($result_list)) {
      foreach ($result_list as $table_id => $parameters) {
        $sql = mysqli_query($conn,"SELECT item_id FROM ".$table_id." WHERE item_id = '$item_id'");
        $test = mysqli_fetch_array($sql);
        $ctimestamp = time();

        if (!$test) {
          $sql = mysqli_query($conn,"INSERT INTO ".$table_id."(item_id, uploader_uid, registration_date) VALUES ('".$item_id."', ".$userID.", ".$ctimestamp.")");
        }
        foreach ($parameters as $param) {
          $param_name = $param['param'];
          $param_value = $param['value'];
          if ($table_id == "pr_warehouse_parameters" && $param_name == "size" && $param_value != "") {
            $boxsizeoptions = array_column($LocalData['BoxSizes'], 'Name');
            if (in_array($param_value, $boxsizeoptions, true)) {
              $sql = mysqli_query($conn,"UPDATE ".$table_id." SET ".$param_name." = '".$param_value."' WHERE item_id = '".$item_id."'");
            } else {
              die(json_encode(["status" => "Nem megfelelő doboz méretet adott meg!", "id" => "pr_warehouse_parameters_size"]));
            }
          } else {
            $sql = mysqli_query($conn,"UPDATE ".$table_id." SET ".$param_name." = '".$param_value."' WHERE item_id = '".$item_id."'");
          }
        }

      }
    }

  }

  echo json_encode(["status" => "done"]);
  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>
    .checklist {
      user-select: none;
      margin-bottom: 10px;
    }
    .parambox {
      overflow: hidden;
      display: none;
      visibility: hidden;
      height: auto;
      margin-left: 24px;
    }
    .parambox p {
      margin-bottom: 0px;
      display: inline;
    }
    .parambox p::after {
      content: ":";
    }
    .parambox input {
      display: inline;
      background: transparent;
      border: 0px;
    }
    .parambox input.saved {
      color: #0B6623;
      transition: 0.3s;
    }
    .parambox input.saved:focus {
      color: var(--panelcolor);
    }
    .parambox.active {
      display: block;
      visibility: visible;
    }
    .parambox > .parambox.active {
      animation: openAnimation 1s ease forwards;
      max-height: unset;
    }
    .box, .box3 {
      max-width: 250px;
    }
    @keyframes openAnimation {
      from {
        max-height: 0;
      }
      to {
        max-height: 1000px;
      }
    }
    .clTitle {
      font-weight: bold;
      text-transform: uppercase;
      cursor: pointer;
      margin: 0px;
      padding: 4px 0px;
      font-size: 16px;
    }
    .arrow svg {
      width: 0.6875em;
      height: 0.6875em;
      display: block;
      fill: inherit;
      flex-shrink: 0;
      transition: 0.3s ease-out 0s;
      transform: rotateZ(90deg);
      opacity: 0.6;
    }
    .arrow {
      float: left;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 24px;
      height: 24px;
      border-radius: 3px;
      transition: 0.3s;
    }
    .arrow svg.active {
      transform: rotateZ(180deg);
      opacity: 1;
    }
    button#SendBasicDataBtn:disabled {
      cursor: progress;
    }
    .clTitle:after {
      content: var(--after-content, '');
      color: var(--after-color, '#0B6623');
      margin-left: 5px;
    }
  </style>
  <body>
    <?php echo $menuhtml;?>
    <div class="window closed" id="win">
      <div class="topbar">
        <p id="wintitle">Title</p>
        <div class="btn fullscrn" onclick="fullscrn();" id="fullscrnbtn"></div>
        <div class="btn close" onclick="closewin();"></div>
      </div>
      <div class="wapp" id="winapp"><div id="errorDIV"></div></div>
      <div class="loading" id="winloading"></div>
    </div>
    <div class="loadingBG" id="loadingBG"><img src="../img/loading.gif"></div>
    <div class="content">
      <div id="errorDIV" style="z-index: 100; top: 50px; position: fixed; width: calc(100% - 260px);"></div>

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

      <h1>Termék (cikkszám) bevezetése</h1>

      <div id="ItemCreatorInProgressList"></div>

      <?php
      if (UserHasPerm('edit_item_introduction_basic_data')) {
        echo '
        <div class="box">
          <div class="statusimg"><img class="request" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAT0lEQVRoge3PQQ0AIBDAMMC/50MEj4ZkVbDtWX87OuBVA1oDWgNaA1oDWgNaA1oDWgNaA1oDWgNaA1oDWgNaA1oDWgNaA1oDWgNaA1oD2gX6dwFfInhRkAAAAABJRU5ErkJggg=="></div>
          <h2>Új termék hozzáadása</h2><p>Egy új termék bevezetésének elkezdése</p>
          <br><button onclick="StartNewIntroduction();">Elkezdés</button>
        </div>
        ';
      }
      ?>

      <div id="completed_item_introduction_div" style="visibility: hidden; display: none;">

        <br clear="all">
        <br clear="all">
        <div style="border-top: solid 1px rgb(211,220,228); width: calc(100% - 15px); height: 0px; margin-top: 15px;"></div>
        <p style="color: rgb(211,220,228);">Lezárt termék bevezetések</p>

        <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>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>Hitelesítő: </p>
            <select id="filter-finalized_by" onchange="SendFilter();"><option value="">-- Összes --</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>

        <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: 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 id="table_head_item_id" onclick="orderby_filter('item_id');" style="cursor: pointer;">Cikkszám</th>
                  <th id="table_head_finalized_in" onclick="orderby_filter('finalized_in');" style="cursor: pointer;">Hitelesítés dátuma</th>
                  <th id="table_head_finalized_by" onclick="orderby_filter('finalized_by');" style="cursor: pointer;">Hitelesítő</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>

      </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 SizeOptions = null;
      var FirstlyMandatoryTables = ["pr_parameters"];
      var MandatoryTables = ["pr_parameters", "pr_basic_info", "pr_cutting_parameters", "pr_packing_parameters", "pr_warehouse_parameters"];
      var MandatoryTablesForSet = ["pr_parameters", "pr_warehouse_parameters"];

      fetch('warehouse.php?boxsize=1')
        .then(response => response.json())
        .then(boxSizeArray => {
          SizeOptions = boxSizeArray.map(item => item.Name);
        })
        .catch(error => console.error('Hiba a BoxSize betöltésekor:', error));

      function LoadItemCreatorInProgressList(isInBG = true) {
        var TheDiv = document.getElementById("ItemCreatorInProgressList");
        if (!isInBG) {Loading();}
        const body = 'func=LoadItemCreatorInProgressList';
        get_POST_information("itemcreator.php", body, function(text) {
          let response = JSON.parse(text);
          if (!isInBG) {Loading(false);}
          if (response.status == "ok") {
            TheDiv.innerHTML = "";
            if (response.data != "") {
              if (response.data.includes("|%|")) {
                var data = response.data.split("|%|");
              } else {
                var data = [response.data];
              }
              for (var i = 0; i < data.length; i++) {
                var cdata = data[i].split("||");
                if (cdata[2] == "1") {
                  TheDiv.innerHTML += '<div class="box3"><div class="statusimg"><img class="work" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAT0lEQVRoge3PQQ0AIBDAMMC/50MEj4ZkVbDtWX87OuBVA1oDWgNaA1oDWgNaA1oDWgNaA1oDWgNaA1oDWgNaA1oDWgNaA1oDWgNaA1oD2gX6dwFfInhRkAAAAABJRU5ErkJggg=="></div><h2>Cikkszám: '+cdata[0]+'</h2><p>'+cdata[1]+'</p><br><br><button onclick="OpenIntroduction(\''+cdata[0]+'\')">Megtekintés</button></div>';
                } else if (cdata[2] == "2") {
                  TheDiv.innerHTML += '<div class="box2"><div class="statusimg"><img class="wait" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAT0lEQVRoge3PQQ0AIBDAMMC/50MEj4ZkVbDtWX87OuBVA1oDWgNaA1oDWgNaA1oDWgNaA1oDWgNaA1oDWgNaA1oDWgNaA1oDWgNaA1oD2gX6dwFfInhRkAAAAABJRU5ErkJggg=="></div><h2>Cikkszám: '+cdata[0]+'</h2><p>'+cdata[1]+'</p><br><br><button onclick="OpenIntroduction(\''+cdata[0]+'\')">Megtekintés</button></div>';
                } else {
                  TheDiv.innerHTML += '<div class="box"><div class="statusimg"><img class="request" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAT0lEQVRoge3PQQ0AIBDAMMC/50MEj4ZkVbDtWX87OuBVA1oDWgNaA1oDWgNaA1oDWgNaA1oDWgNaA1oDWgNaA1oDWgNaA1oDWgNaA1oD2gX6dwFfInhRkAAAAABJRU5ErkJggg=="></div><h2>Cikkszám: '+cdata[0]+'</h2><p>'+cdata[1]+'</p><br><br><button onclick="OpenIntroduction(\''+cdata[0]+'\')">Megtekintés</button></div>';
                }

              }
            }
          } else {
            GenerateAlerts('error', response.message);
          }
        }, function() {
          if (!isInBG) {Loading(false);}
          GenerateAlerts('error', 'Hálózati hiba! Kérjük, próbálja újra');
        });
      }
      LoadItemCreatorInProgressList(false);

      /* Termék bevezetés */

      function CheckAndActivate(input_id, button_id) {
        if (document.getElementById(input_id).value != '') {
          document.getElementById(button_id).disabled = false;
        } else {
          document.getElementById(button_id).disabled = true;
        }
      }
      function StartNewIntroduction() {
        Loading();
        openwin();
        wintitle.innerHTML = "Új termék bevezetése";
        winapp.innerHTML = '<div id="errorDIV"></div>';
        winapp.innerHTML += '<h1>Új termék bevezetési folyamat elkezdése</h1>';
        winapp.innerHTML += '<p><strong>Adjon meg egy cikkszámot:</strong></p>';
        winapp.innerHTML += '<input type="text" id="NewIntroductionID" onkeyup="CheckAndActivate(\'NewIntroductionID\', \'NewIntroductionButtonID\');" placeholder="Cikkszám" autocomplete="off" autocapitalize="off" spellcheck="false" autocorrect="off">';
        winapp.innerHTML += '<br><br><button onclick="SaveNewIntroduction();" id="NewIntroductionButtonID" disabled="true">Folyamat elkezdése</button>';
        Loading(false);
      }
      function SaveNewIntroduction() {
        var item_id = document.getElementById('NewIntroductionID').value;
        Loading();
        const body = 'func=SaveNewIntroduction&item_id='+item_id;
        get_POST_information("itemcreator.php", body, function(text) {
          let response = JSON.parse(text);
          Loading(false);
          if (response.status == "ok") {
            GenerateAlerts('success', 'A folyamat sikeresen elkezdve!');
            LoadItemCreatorInProgressList(true);
            OpenIntroduction(item_id);
          } else {
            GenerateAlerts('error', response.message);
          }
        }, function() {
          Loading(false);
          GenerateAlerts('error', 'Hálózati hiba! Kérjük, próbálja újra');
        });
      }

      function OpenIntroduction(item_id) {
        Loading();
        openwin();
        wintitle.innerHTML = "Termék bevezetése";
        const body = 'func=OpenIntroduction&item_id='+item_id;
        get_POST_information("itemcreator.php", body, function(text) {
          let response = JSON.parse(text);
          Loading(false);
          if (response.status == "ok") {
            winapp.innerHTML = '<div id="errorDIV"></div>';
            if (response.current_stage == "basic_data") {
              OpenBasicData(item_id);
            } else if (response.current_stage == "tools_send") {
              OpenToolsSend(item_id);
            } else if (response.current_stage == "testing") {
              OpenTesting(item_id);
            } else if (response.current_stage == "deficit") {
              OpenDeficit(item_id);
            } else if (response.current_stage == "last_statement") {
              OpenLastStatement(item_id);
            } else if (response.current_stage == "final") {
              OpenFinal(item_id);
            } else {
              OpenComplete(item_id);
            }

          } else {
            GenerateAlerts('error', response.message);
          }
        }, function() {
          Loading(false);
          GenerateAlerts('error', 'Hálózati hiba! Kérjük, próbálja újra');
        });
      }


      var UserCanSaveBasicData = false;
      function OpenBasicData(item_id, deficit = false) {
        Loading();
        openwin();
        wintitle.innerHTML = "Termék bevezetése - Alap adatok feltöltése";
        const body = 'func=OpenBasicData&item_id='+item_id;
        get_POST_information("itemcreator.php", body, function(text) {
          winapp.innerHTML = '<div id="errorDIV"></div>';
          let response = JSON.parse(text);
          Loading(false);
          if (response.status == "ok") {
            if (deficit) {
              winapp.innerHTML += '<h1 style="margin-bottom: 0px;">Alap adatok pótlása</h1><p style="margin-top: 5px;">Kérjük, töltse ki az alábbi mezőket</p>';
            } else {
              winapp.innerHTML += '<h1 style="margin-bottom: 0px;">Alap adatok feltöltése</h1><p style="margin-top: 5px;">Kérjük, töltse ki az alábbi mezőket</p>';
            }
            winapp.innerHTML += '<br clear="all"><div style="border-top: solid 1px rgb(211,220,228); width: calc(100% - 15px); height: 0px;"></div><br clear="all">';

            const tableNames = [];
            Object.keys(response).forEach(field => {
              if (field.endsWith("_can_see") && response[field] === true) {
                tableNames.push(field.replace("_can_see", ""));
              }
            });

            var LastHaveData = "pr_parameters";

            var Disabledtext = "disabled";
            if (response['pr_parameters_can_edit']) {
              UserCanSaveBasicData = true;
              Disabledtext = "";
            }

            tableNames.forEach(table => {
              var GenerateList = '';
              if (deficit) {
                if (item_id.includes("+")) {
                  GenerateList += '<div class="checklist" id="'+table+'"><div class="arrow"><svg role="graphics-symbol" viewBox="0 0 100 100"><polygon points="5.9,88.2 50,11.8 94.1,88.2 "></polygon></svg></div><p class="clTitle" mandatory="'+MandatoryTablesForSet.includes(table)+'" onclick="ShowBasicData(\''+table+'\')">'+response[table]+'</p>';
                } else {
                  GenerateList += '<div class="checklist" id="'+table+'"><div class="arrow"><svg role="graphics-symbol" viewBox="0 0 100 100"><polygon points="5.9,88.2 50,11.8 94.1,88.2 "></polygon></svg></div><p class="clTitle" mandatory="'+MandatoryTables.includes(table)+'" onclick="ShowBasicData(\''+table+'\')">'+response[table]+'</p>';
                }
              } else {
                GenerateList += '<div class="checklist" id="'+table+'"><div class="arrow"><svg role="graphics-symbol" viewBox="0 0 100 100"><polygon points="5.9,88.2 50,11.8 94.1,88.2 "></polygon></svg></div><p class="clTitle" mandatory="'+FirstlyMandatoryTables.includes(table)+'" onclick="ShowBasicData(\''+table+'\')">'+response[table]+'</p>';
              }

              Object.keys(response).forEach(field => {
                if (field.startsWith(table) && !field.endsWith("_can_edit") && !field.endsWith("_can_see") && !field.endsWith("_datalist") && field !== table) {
                  var cvalue = response[field];
                  var datalist = response[field+"_datalist"];

                  if (field == "pr_warehouse_parameters_size") {
                    var datalist = '';
                    for (var i = 0; i < SizeOptions.length; i++) {
                      datalist += '<option value="'+SizeOptions[i]+'">'+SizeOptions[i]+'</option>';
                    }
                  }

                  if (cvalue.includes("||+")) {
                    GenerateList += '<div class="parambox"><p>'+cvalue.split("||")[0]+'</p><input SavedValue="" class="saved" onkeydown="document.getElementById(\'SendBasicDataBtn\').disabled = true;" onblur="NeedToSave(this.id, \''+response["item_id"]+'\', '+deficit+');" type="text" id="BasicData_'+field+'" '+Disabledtext+' placeholder="'+cvalue.split("||")[0]+'" autocomplete="off" autocapitalize="off" spellcheck="false" autocorrect="off" list="Datalist_'+field+'"><datalist id="Datalist_'+field+'" role="listbox">'+datalist+'</datalist></div>';
                  } else {
                    if (cvalue.split("||")[1] != "") {LastHaveData = table;}
                    GenerateList += '<div class="parambox"><p>'+cvalue.split("||")[0]+'</p><input SavedValue="'+cvalue.split("||")[1]+'" onkeydown="document.getElementById(\'SendBasicDataBtn\').disabled = true;" class="saved" onblur="NeedToSave(this.id, \''+response["item_id"]+'\', '+deficit+');" type="text"id="BasicData_'+field+'" '+Disabledtext+' value="'+cvalue.split("||")[1]+'" placeholder="'+cvalue.split("||")[0]+'" autocomplete="off" autocapitalize="off" spellcheck="false" autocorrect="off" list="Datalist_'+field+'"><datalist id="Datalist_'+field+'" role="listbox">'+datalist+'</datalist></div>';
                  }
                }
              });

              GenerateList += '</div>';
              winapp.innerHTML += GenerateList;

            });

            checkAllInputsInBasicData();

            if (UserCanSaveBasicData && !deficit) {
              winapp.innerHTML += '<br clear="all"><br clear="all"><button onclick="SendBasicData(\''+response["item_id"]+'\');" id="SendBasicDataBtn">Szerszámtervek vágásra küldése</button>';
            } else if (UserCanSaveBasicData && deficit) {
              winapp.innerHTML += '<br clear="all"><br clear="all"><button onclick="StartLastStatement(\''+response["item_id"]+'\');" id="SendBasicDataBtn">Véglegesítés</button>';
            }
            ShowBasicData(LastHaveData);


          } else {
            GenerateAlerts('error', response.message);
          }
        }, function() {
          Loading(false);
          GenerateAlerts('error', 'Hálózati hiba! Kérjük, próbálja újra');
        });
      }
      function ShowBasicData(id) {
        const clDiv = document.getElementById(id);
        const checklistCategory = clDiv.querySelectorAll('.parambox');
        const Arrow = clDiv.querySelectorAll('.arrow svg');

        var OriginallyAtive = false;
        var IsFirst = true;
        checklistCategory.forEach(element => {
          if (element.classList.contains('active') && IsFirst) {
            OriginallyAtive = true;
          }
          if (OriginallyAtive) {
            element.classList.remove('active');
          } else {
            element.classList.add('active');
          }
          IsFirst = false;
        });

        Arrow.forEach(element => {
          if (OriginallyAtive) {
            element.classList.remove('active');
          } else {
            element.classList.add('active');
          }
        });

      }
      var ToSaveList = [];
      function NeedToSave(id, item_id) {
        if (document.getElementById(id).getAttribute("SavedValue") != document.getElementById(id).value && UserCanSaveBasicData) {
          document.getElementById(id).classList.remove("saved");
          document.getElementById(id).setAttribute("SavedValue", document.getElementById(id).value);
          if (!ToSaveList.includes(id)) {
            ToSaveList.push(id);
            document.getElementById("SendBasicDataBtn").disabled = true;
          }
        }

        setTimeout(function() {
          if (ToSaveList.length !== 0) {
            let ProductsData = {};
            for (var i = 0; i < ToSaveList.length; i++) {
              document.getElementById(ToSaveList[i]).classList.add("saved");
              ProductsData[ToSaveList[i].replace(/^BasicData_/, '')] = jsonSafeEncode(document.getElementById(ToSaveList[i]).value);
              ToSaveList = ToSaveList.filter(item => item !== ToSaveList[i]);
            }
            ProductsData["item_id"] = item_id;

            fetch("itemcreator.php?saving=1", {
              method: "POST",
              headers: {
                "Content-Type": "application/json"
              },
              body: JSON.stringify(ProductsData)
            })
            .then(response => response.json())
            .then(data => {
              if (data.status !== "done") {
                GenerateAlerts("error", data.status);
                document.getElementById("BasicData_" + data.id).classList.remove("saved");
                document.getElementById("BasicData_" + data.id).setAttribute("SavedValue", "");
              }
              checkAllInputsInBasicData();
            })
            .catch(error => GenerateAlerts("error", error));

          }
          document.getElementById("SendBasicDataBtn").disabled = false;
        }, 1000);
      }
      function checkAllInputsInBasicData() {
        const checklists = document.querySelectorAll('.checklist');
        AllMandatoryIsEdited = true;
        checklists.forEach(checklist => {
          const inputs = checklist.querySelectorAll('input');
          const title = checklist.querySelector('.clTitle');

          const allFilled = Array.from(inputs)
            .filter(input => !input.id.includes('_note'))
            .filter(input => !input.id.includes('_foil_product_place'))
            .every(input => input.getAttribute("SavedValue").trim() !== '');

          if (allFilled) {
            title.style.setProperty('--after-content', '"✔"');
            title.style.setProperty('--after-color', '#0B6623');
          } else if (title.getAttribute("mandatory") == "true") {
            title.style.setProperty('--after-content', '"*"');
            title.style.setProperty('--after-color', '#c0392b');
            AllMandatoryIsEdited = false;
          } else {
            title.style.setProperty('--after-content', '');
          }
        });
      }
      function SendBasicData(item_id, tosend = true) {
        if (tosend && !AllMandatoryIsEdited) {
          GenerateAlerts('error', 'Kérjük, minden kötelező adatbázist töltsön ki!');
        } else {
          Loading();
          openwin();
          wintitle.innerHTML = "Termék bevezetése - Alap adatok ellenőrzése";
          const body = 'func=openproduct&item_id=' + item_id;
          get_POST_information("products.php", body, function(text) {
            winapp.innerHTML = '<div id="errorDIV"></div>';
            let response = JSON.parse(text);
            Loading(false);
            if (response.result == "ok") {
              winapp.innerHTML += '<h1 style="margin-bottom: 0px;">Alap adatok ellenőrzése</h1><p style="margin-top: 5px;">Kérjük, ellenőrizze le a megadott adatokat, majd nyomjon az "Ellenőrizve" gombra.</p>';

              if (response.pr_parameters_data_status == "1") {winapp.innerHTML += '<p style="opacity: 0.8; margin-top: 0px;"><span id="wapp_item_id">'+response.item_id+'</span> - <span style="color: var(--panelcolor);">Értékesíthető</span></p>';
            } else if (response.pr_parameters_data_status == "-1") {winapp.innerHTML += '<p style="opacity: 0.8; margin-top: 0px;"><span id="wapp_item_id">'+response.item_id+'</span> - <span style="color: var(--panelcolor);">Kifutó</span></p>';
            } else if (response.pr_parameters_data_status == "-2") {winapp.innerHTML += '<p style="opacity: 0.8; margin-top: 0px;"><span id="wapp_item_id">'+response.item_id+'</span> - <span style="color: var(--panelcolor);">Megszűnt</span></p>';
            } else {winapp.innerHTML += '<p style="opacity: 0.8; margin-top: 0px;"><span id="wapp_item_id">'+response.item_id+'</span> - <span style="color: var(--panelcolor);">Bevezetés alatt</span></p>';}

              const tableNames = [];
              Object.keys(response).forEach(field => {
                if (field.endsWith("_can_see") && response[field] === true) {
                  tableNames.push(field.replace("_can_see", ""));
                }
              });


              tableNames.forEach(table => {
                winapp.innerHTML += '<br clear="all">';
                winapp.innerHTML += '<p style="width: calc(100% - 35px); border-bottom: 1px solid #bdc3c7; font-weigth: bold; display: inline-block; margin-right: 15px; ">'+response[table]+'</p>';

                winapp.innerHTML += '<div class="helpcursor"><span class="helptext">Létrehozó: '+response[table + "_uploader_name"]+'<br>Létrehozva: '+response[table + "_registration_date"]+'</span><span>&#9432;</span></div>';

                Object.keys(response).forEach(field => {
                  if (field.startsWith(table) && !field.endsWith("_can_edit") && !field.endsWith("_can_see") && !field.endsWith("_data_status") && !field.endsWith("_registration_date") && !field.endsWith("_uploader_name") && field !== table) {
                    var cvalue = response[field];
                    winapp.innerHTML += '<div class="productbox"><p>'+cvalue.split("||")[0]+'</p><p id="'+field+'" >'+cvalue.split("||")[1]+'</p></div>';
                  }
                });
              });

              winapp.innerHTML += '<br clear="all"><br clear="all">';
              if (tosend) {
                winapp.innerHTML += '<button onclick="OpenBasicData(\''+response.item_id+'\');" style="margin-right: 15px;">Visszalépés</button> <button onclick="StartToolsSend(\''+response.item_id+'\');">Ellenőrizve</button>';
              } else {
                winapp.innerHTML += '<button onclick="OpenIntroduction(\''+response.item_id+'\');">Visszalépés</button>';
              }

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


      function StatementEditor(item_id, Statement_id, Statement_name, edit_to, is_input = false, Confirmed = false, input = "igen") {
        FeedbackButtonStatus('loading', Statement_id + '_button');
        if (is_input && edit_to && !Confirmed) {
          var html = `
          <p><b>Kérjük, amennyiben sikertelen a(z) '${Statement_name}' indokolja meg, ha viszont sikeres, akkor írja be, hogy 'igen'!</b></p><br>
          <input type="text" id="AlertTextInput" placeholder="Indoklás..." autocomplete="off" autocapitalize="off" spellcheck="false" autocorrect="off" value="igen">
          <br clear="all"><br>
          <button id="AlertBtnNo" style="float: right; margin-left: 15px; width: 80;">Mégsem</button>
          <button id="AlertBtnYes" style="float: right; width: 60px; background: var(--panelcolor); color: #f5f5f5; border: unset;">Mentés</button>
          `;
          const overlay = CreateAlertBox('Nyilatkozat benyújtása!', html, false);
          document.getElementById('AlertBtnYes').onclick = function () { StatementEditor(item_id, Statement_id, Statement_name, edit_to, is_input, true, (document.getElementById("AlertTextInput").value).toLowerCase()); CloseAlertBox(overlay); };
          document.getElementById('AlertBtnNo').onclick = function () { CloseAlertBox(overlay); FeedbackButtonStatus('failed', Statement_id + '_button'); };
          return;
        } else if (edit_to && !Confirmed) {
          var html = `
          <p><b>Biztos benne, hogy a(z) '${Statement_name}' nevű nyilatkozatot benyújtja?</b></p>
          <button id="AlertBtnNo" style="float: right; margin-left: 15px; width: 60px;">Nem</button>
          <button id="AlertBtnYes" style="float: right; width: 60px; background: var(--panelcolor); color: #f5f5f5; border: unset;">Igen</button>
          `;
          const overlay = CreateAlertBox('Nyilatkozat benyújtása!', html, false);
          document.getElementById('AlertBtnYes').onclick = function () { StatementEditor(item_id, Statement_id, Statement_name, edit_to, is_input, true); CloseAlertBox(overlay); };
          document.getElementById('AlertBtnNo').onclick = function () { CloseAlertBox(overlay); FeedbackButtonStatus('failed', Statement_id + '_button'); };
          return;
        } else if (!Confirmed) {
          var html = `
          <p><b>Biztos benne, hogy a(z) '${Statement_name}' nevű nyilatkozatot visszavonja?</b></p>
          <button id="AlertBtnNo" style="float: right; margin-left: 15px; width: 60px;">Nem</button>
          <button id="AlertBtnYes" style="float: right; width: 60px; background: var(--panelcolor); color: #f5f5f5; border: unset;">Igen</button>
          `;
          const overlay = CreateAlertBox('Nyilatkozat visszavonása!', html, false);
          document.getElementById('AlertBtnYes').onclick = function () { StatementEditor(item_id, Statement_id, Statement_name, edit_to, is_input, true); CloseAlertBox(overlay); };
          document.getElementById('AlertBtnNo').onclick = function () { CloseAlertBox(overlay); FeedbackButtonStatus('failed', Statement_id + '_button'); };
          return;
        }
        if (Confirmed) {

          const body = 'func=StatementEditor&item_id='+item_id+'&statement_id='+Statement_id+'&edit_to='+edit_to+'&input='+encodeURIComponent(input).replace(/%20/g, '+');
          get_POST_information("itemcreator.php", body, function(text) {
            let response = JSON.parse(text);
            if (response.result == "ok") {
              if (is_input && input != 'igen') {
                FeedbackButtonStatus('failed', Statement_id + '_button');
              } else if (!edit_to){
                FeedbackButtonStatus('failed', Statement_id + '_button');
              } else {
                FeedbackButtonStatus('complete', Statement_id + '_button');
              }
              setTimeout(function() {
                document.getElementById(Statement_id + '_button').setAttribute('onclick', 'StatementEditor("'+item_id+'", "'+Statement_id+'", "'+Statement_name+'", '+!edit_to+', '+is_input+')');
                const span = document.querySelector('#'+Statement_id+'_button .button-text');
                if (!edit_to) {
                  span.textContent = "Nyilatkozok";
                  document.getElementById(Statement_id + "_text").innerHTML = "";
                } else {
                  span.textContent = "Visszavonás";
                  document.getElementById(Statement_id + "_text").innerHTML = response.text;
                }
              }, 300);
            } else {
              FeedbackButtonStatus('failed', Statement_id + '_button');
              GenerateAlerts('error', response.result);
            }
          }, function() {
            Loading(false);
            FeedbackButtonStatus('failed', Statement_id + '_button');
            GenerateAlerts("error", "Hálózati hiba!");
          });

        } else {
          FeedbackButtonStatus('failed', Statement_id + '_button');
        }
      }


      function StartToolsSend(item_id, Confirmed = false) {
        if (!AllMandatoryIsEdited) {
          GenerateAlerts('error', 'Kérjük, minden kötelező adatbázist töltsön ki!');
        } else if (Confirmed) {
          Loading();
          const body = 'func=StartToolsSend&item_id='+item_id;
          get_POST_information("itemcreator.php", body, function(text) {
            let response = JSON.parse(text);
            Loading(false);
            if (response.status == "ok") {
              GenerateAlerts('success', 'Szerszámtervek vágásra továbbküldve!');
              LoadItemCreatorInProgressList(true);
              OpenIntroduction(item_id);
            } else {
              GenerateAlerts('error', response.message);
            }
          }, function() {
            Loading(false);
            GenerateAlerts('error', 'Hálózati hiba! Kérjük, próbálja újra');
          });
        } else {
          var html = `
          <p><b>Biztos benne, hogy tovább akarja küldeni a folyamatot szerszámtervek vágására?</b></p>
          <button id="AlertBtnNo" style="float: right; margin-left: 15px; width: 60px;">Nem</button>
          <button id="AlertBtnYes" style="float: right; width: 60px; background: var(--panelcolor); color: #f5f5f5; border: unset;">Igen</button>
          `;
          const overlay = CreateAlertBox('Szerszámtervek', html);
          document.getElementById('AlertBtnYes').onclick = function () { StartToolsSend(item_id, true); CloseAlertBox(overlay); };
          document.getElementById('AlertBtnNo').onclick = function () { CloseAlertBox(overlay); };
          return;
        }
      }
      function OpenToolsSend(item_id) {
        Loading();
        openwin();
        wintitle.innerHTML = "Termék bevezetése - Szerszámtervek feldolgozása";
        const body = 'func=OpenToolsSend&item_id='+item_id;
        get_POST_information("itemcreator.php", body, function(text) {
          winapp.innerHTML = '<div id="errorDIV"></div>';
          let response = JSON.parse(text);
          Loading(false);
          if (response.status == "ok") {

            winapp.innerHTML += '<h1 style="margin-bottom: 0px;">Szerszámtervek feldolgozása</h1><p style="margin-top: 5px;"></p>';
            winapp.innerHTML += '<p style="width: calc(100% - 139px); border-bottom: 1px solid #bdc3c7; font-weigth: bold; display: inline-block; margin-right: 15px; ">Kérjük, nyilatkozzon az alábbiakról</p>';
            winapp.innerHTML += '<div class="helpcursor" onclick="SendBasicData(\''+item_id+'\', false);" style="color: var(--panelcolor); border: 1px solid #ddd; padding: 6.5px; cursor: pointer;">Termék adatlap</div>';

            winapp.innerHTML += '<p style="margin-right: 15px;"><strong>Szerszám rendben van:</strong><span id="is_tool_ok_text" style="margin-left: 15px;">'+response.is_tool_ok+'</span></p>';
            if ((response.is_tool_ok == "" || response.is_tool_ok == null) && response.user_can_edit == true) {
              winapp.innerHTML += '<button class="Feedback" id="is_tool_ok_button" style="width: 100px;" onclick="StatementEditor(\''+item_id+'\', \'is_tool_ok\', \'Szerszám rendben van\', true);"><span class="button-text">Nyilatkozok</span><div class="loader"></div><div class="checkmark">&#10004;</div><div class="crossmark">&#10006;</div></button>';
            } else if (response.user_can_edit == true) {
              winapp.innerHTML += '<button class="Feedback" id="is_tool_ok_button" style="width: 100px;" onclick="StatementEditor(\''+item_id+'\', \'is_tool_ok\', \'Szerszám rendben van\', false);"><span class="button-text">Visszavonás</span><div class="loader"></div><div class="checkmark">&#10004;</div><div class="crossmark">&#10006;</div></button>';
            }

            winapp.innerHTML += '<p style="margin-right: 15px;"><strong>Szerszám kész:</strong><span id="is_tool_created_text" style="margin-left: 15px;">'+response.is_tool_created+'</span></p>';
            if ((response.is_tool_created == "" || response.is_tool_created == null) && response.user_can_edit == true) {
              winapp.innerHTML += '<button class="Feedback" id="is_tool_created_button" style="width: 100px;" onclick="StatementEditor(\''+item_id+'\', \'is_tool_created\', \'Szerszám kész\', true);"><span class="button-text">Nyilatkozok</span><div class="loader"></div><div class="checkmark">&#10004;</div><div class="crossmark">&#10006;</div></button>';
            } else if (response.user_can_edit == true) {
              winapp.innerHTML += '<button class="Feedback" id="is_tool_created_button" style="width: 100px;" onclick="StatementEditor(\''+item_id+'\', \'is_tool_created\', \'Szerszám kész\', false);"><span class="button-text">Visszavonás</span><div class="loader"></div><div class="checkmark">&#10004;</div><div class="crossmark">&#10006;</div></button>';
            }

            winapp.innerHTML += '<p style="margin-right: 15px;"><strong>Próba darab kész:</strong><span id="is_tool_can_be_tested_text" style="margin-left: 15px;">'+response.is_tool_can_be_tested+'</span></p>';
            if ((response.is_tool_can_be_tested == "" || response.is_tool_can_be_tested == null) && response.user_can_edit == true) {
              winapp.innerHTML += '<button class="Feedback" id="is_tool_can_be_tested_button" style="width: 100px;" onclick="StatementEditor(\''+item_id+'\', \'is_tool_can_be_tested\', \'Próba darab kész\', true);"><span class="button-text">Nyilatkozok</span><div class="loader"></div><div class="checkmark">&#10004;</div><div class="crossmark">&#10006;</div></button>';
            } else if (response.user_can_edit == true) {
              winapp.innerHTML += '<button class="Feedback" id="is_tool_can_be_tested_button" style="width: 100px;" onclick="StatementEditor(\''+item_id+'\', \'is_tool_can_be_tested\', \'Próba darab kész\', false);"><span class="button-text">Visszavonás</span><div class="loader"></div><div class="checkmark">&#10004;</div><div class="crossmark">&#10006;</div></button>';
            }

            winapp.innerHTML += '<br clear="all"><div style="border-top: solid 1px rgb(211,220,228); width: calc(100% - 15px); height: 0px;"></div><br clear="all"><br clear="all">';
            if (response.user_can_edit == true) {
              winapp.innerHTML += '<button onclick="StartTesting(\''+item_id+'\');">Tesztelésre továbbküldés</button>';
            }

          } else {
            GenerateAlerts('error', response.message);
          }
        }, function() {
          Loading(false);
          GenerateAlerts('error', 'Hálózati hiba! Kérjük, próbálja újra');
        });
      }


      function StartTesting(item_id, Confirmed = false) {
        if (Confirmed) {
          Loading();
          const body = 'func=StartTesting&item_id='+item_id;
          get_POST_information("itemcreator.php", body, function(text) {
            let response = JSON.parse(text);
            Loading(false);
            if (response.status == "ok") {
              GenerateAlerts('success', 'Termék próbára továbbküldve!');
              LoadItemCreatorInProgressList(true);
              OpenIntroduction(item_id);
            } else {
              GenerateAlerts('error', response.message);
            }
          }, function() {
            Loading(false);
            GenerateAlerts('error', 'Hálózati hiba! Kérjük, próbálja újra');
          });
        } else {
          var html = `
          <p><b>Biztos benne, hogy tovább akarja küldeni a folyamatot tesztelésre?</b></p>
          <button id="AlertBtnNo" style="float: right; margin-left: 15px; width: 60px;">Nem</button>
          <button id="AlertBtnYes" style="float: right; width: 60px; background: var(--panelcolor); color: #f5f5f5; border: unset;">Igen</button>
          `;
          const overlay = CreateAlertBox('Tesztelés', html);
          document.getElementById('AlertBtnYes').onclick = function () { StartTesting(item_id, true); CloseAlertBox(overlay); };
          document.getElementById('AlertBtnNo').onclick = function () { CloseAlertBox(overlay); };
          return;
        }
      }
      function OpenTesting(item_id) {
        Loading();
        openwin();
        wintitle.innerHTML = "Termék bevezetése - Termékpróba szakasz";
        const body = 'func=OpenTesting&item_id='+item_id;
        get_POST_information("itemcreator.php", body, function(text) {
          winapp.innerHTML = '<div id="errorDIV"></div>';
          let response = JSON.parse(text);
          Loading(false);
          if (response.status == "ok") {

            winapp.innerHTML += '<h1 style="margin-bottom: 0px;">Termékpróba szakasz</h1><p style="margin-top: 5px;"></p>';
            winapp.innerHTML += '<p style="width: calc(100% - 139px); border-bottom: 1px solid #bdc3c7; font-weigth: bold; display: inline-block; margin-right: 15px; ">Kérjük, nyilatkozzon az alábbiakról</p>';
            winapp.innerHTML += '<div class="helpcursor" onclick="SendBasicData(\''+item_id+'\', false);" style="color: var(--panelcolor); border: 1px solid #ddd; padding: 6.5px; cursor: pointer;">Termék adatlap</div>';

            winapp.innerHTML += '<p style="margin-right: 15px;"><strong>Terméket tesztautóba bepróbálta:</strong><span id="is_tested_in_car_text" style="margin-left: 15px;">'+response.is_tested_in_car+'</span></p>';
            if ((response.is_tested_in_car == "" || response.is_tested_in_car == null) && response.user_can_edit == true) {
              winapp.innerHTML += '<button class="Feedback" id="is_tested_in_car_button" style="width: 100px;" onclick="StatementEditor(\''+item_id+'\', \'is_tested_in_car\', \'Terméket tesztautóba bepróbáltam\', true);"><span class="button-text">Nyilatkozok</span><div class="loader"></div><div class="checkmark">&#10004;</div><div class="crossmark">&#10006;</div></button>';
            } else if (response.user_can_edit == true) {
              winapp.innerHTML += '<button class="Feedback" id="is_tested_in_car_button" style="width: 100px;" onclick="StatementEditor(\''+item_id+'\', \'is_tested_in_car\', \'Terméket tesztautóba bepróbáltam\', false);"><span class="button-text">Visszavonás</span><div class="loader"></div><div class="checkmark">&#10004;</div><div class="crossmark">&#10006;</div></button>';
            }

            winapp.innerHTML += '<p style="margin-right: 15px;"><strong>Sorozatgyártható:</strong><span id="is_production_ready_text" style="margin-left: 15px;">'+response.is_production_ready+'</span></p>';
            if ((response.is_production_ready == "" || response.is_production_ready == null) && response.user_can_edit == true) {
              winapp.innerHTML += '<button class="Feedback" id="is_production_ready_button" style="width: 100px;" onclick="StatementEditor(\''+item_id+'\', \'is_production_ready\', \'Sorozatgyártható\', true, true);"><span class="button-text">Nyilatkozok</span><div class="loader"></div><div class="checkmark">&#10004;</div><div class="crossmark">&#10006;</div></button>';
            } else if (response.user_can_edit == true) {
              winapp.innerHTML += '<button class="Feedback" id="is_production_ready_button" style="width: 100px;" onclick="StatementEditor(\''+item_id+'\', \'is_production_ready\', \'Sorozatgyártható\', false, true);"><span class="button-text">Visszavonás</span><div class="loader"></div><div class="checkmark">&#10004;</div><div class="crossmark">&#10006;</div></button>';
            }

            winapp.innerHTML += '<br clear="all"><div style="border-top: solid 1px rgb(211,220,228); width: calc(100% - 15px); height: 0px;"></div><br clear="all"><br clear="all">';
            if (response.user_can_edit == true) {
              winapp.innerHTML += '<button onclick="StartDeficit(\''+item_id+'\');">Adatpótlásra továbbküldés</button>';
            }

          } else {
            GenerateAlerts('error', response.message);
          }
        }, function() {
          Loading(false);
          GenerateAlerts('error', 'Hálózati hiba! Kérjük, próbálja újra');
        });
      }


      function StartDeficit(item_id, Confirmed = false) {
        if (Confirmed) {
          Loading();
          const body = 'func=StartDeficit&item_id='+item_id;
          get_POST_information("itemcreator.php", body, function(text) {
            let response = JSON.parse(text);
            Loading(false);
            if (response.status == "ok") {
              GenerateAlerts('success', 'A folyamat adatpótlásra továbbküldve!');
              LoadItemCreatorInProgressList(true);
              OpenIntroduction(item_id);
            } else {
              GenerateAlerts('error', response.message);
            }
          }, function() {
            Loading(false);
            GenerateAlerts('error', 'Hálózati hiba! Kérjük, próbálja újra');
          });
        } else {
          var html = `
          <p><b>Biztos benne, hogy tovább akarja küldeni a folyamatot adatpótlásra?</b></p>
          <button id="AlertBtnNo" style="float: right; margin-left: 15px; width: 60px;">Nem</button>
          <button id="AlertBtnYes" style="float: right; width: 60px; background: var(--panelcolor); color: #f5f5f5; border: unset;">Igen</button>
          `;
          const overlay = CreateAlertBox('Adatpótlás', html);
          document.getElementById('AlertBtnYes').onclick = function () { StartDeficit(item_id, true); CloseAlertBox(overlay); };
          document.getElementById('AlertBtnNo').onclick = function () { CloseAlertBox(overlay); };
          return;
        }
      }
      function OpenDeficit(item_id) {
        OpenBasicData(item_id, true);
        wintitle.innerHTML = "Termék bevezetése - Adatpótlás";
      }

      var AllMandatoryIsEdited = false;
      function StartLastStatement(item_id, Confirmed = false) {
        if (!AllMandatoryIsEdited) {
          GenerateAlerts('error', 'Kérjük, minden kötelező adatbázist töltsön ki!');
        } else if (Confirmed) {
          Loading();
          const body = 'func=StartLastStatement&item_id='+item_id;
          get_POST_information("itemcreator.php", body, function(text) {
            let response = JSON.parse(text);
            Loading(false);
            if (response.status == "ok") {
              GenerateAlerts('success', 'A folyamat a végső nyilatkozatokra továbbküldve!');
              LoadItemCreatorInProgressList(true);
              OpenIntroduction(item_id);
            } else {
              GenerateAlerts('error', response.message);
            }
          }, function() {
            Loading(false);
            GenerateAlerts('error', 'Hálózati hiba! Kérjük, próbálja újra');
          });
        } else {
          var html = `
          <p><b>Biztos benne, hogy tovább akar lépni a végső nyilatkozatokhoz?</b><br><br>A késöbbiekben a termékkatalógusban lesz lehetősége az adatok módosítására és létrehozására!</p>
          <button id="AlertBtnNo" style="float: right; margin-left: 15px; width: 60px;">Nem</button>
          <button id="AlertBtnYes" style="float: right; width: 60px; background: var(--panelcolor); color: #f5f5f5; border: unset;">Igen</button>
          `;
          const overlay = CreateAlertBox('Végső nyilatkozatok', html);
          document.getElementById('AlertBtnYes').onclick = function () { StartLastStatement(item_id, true); CloseAlertBox(overlay); };
          document.getElementById('AlertBtnNo').onclick = function () { CloseAlertBox(overlay); };
          return;
        }
      }
      function OpenLastStatement(item_id) {
        Loading();
        openwin();
        wintitle.innerHTML = "Termék bevezetése - Végső nyilatkozatok";
        const body = 'func=OpenLastStatement&item_id='+item_id;
        get_POST_information("itemcreator.php", body, function(text) {
          winapp.innerHTML = '<div id="errorDIV"></div>';
          let response = JSON.parse(text);
          Loading(false);
          if (response.status == "ok") {

            winapp.innerHTML += '<h1 style="margin-bottom: 0px;">Végső nyilatkozatok</h1><p style="margin-top: 5px;"></p>';
            winapp.innerHTML += '<p style="width: calc(100% - 139px); border-bottom: 1px solid #bdc3c7; font-weigth: bold; display: inline-block; margin-right: 15px; ">Kérjük, nyilatkozzon az alábbiakról</p>';
            winapp.innerHTML += '<div class="helpcursor" onclick="SendBasicData(\''+item_id+'\', false);" style="color: var(--panelcolor); border: 1px solid #ddd; padding: 6.5px; cursor: pointer;">Termék adatlap</div>';


            winapp.innerHTML += '<p style="margin-right: 15px;"><strong>Terméket Kulcsszoftba felvitted és -1 re állítottad a raktárkészletét:</strong><span id="is_kulcssoft_ready_text" style="margin-left: 15px;">'+response.is_kulcssoft_ready+'</span></p>';
            if ((response.is_kulcssoft_ready == "" || response.is_kulcssoft_ready == null) && response.user_can_edit == true) {
              winapp.innerHTML += '<button class="Feedback" id="is_kulcssoft_ready_button" style="width: 100px;" onclick="StatementEditor(\''+item_id+'\', \'is_kulcssoft_ready\', \'Terméket Kulcsszoftba felvitted és -1 re állítottad a raktárkészletét\', true);"><span class="button-text">Nyilatkozok</span><div class="loader"></div><div class="checkmark">&#10004;</div><div class="crossmark">&#10006;</div></button>';
            } else if (response.user_can_edit == true) {
              winapp.innerHTML += '<button class="Feedback" id="is_kulcssoft_ready_button" style="width: 100px;" onclick="StatementEditor(\''+item_id+'\', \'is_kulcssoft_ready\', \'Terméket Kulcsszoftba felvitted és -1 re állítottad a raktárkészletét\', false);"><span class="button-text">Visszavonás</span><div class="loader"></div><div class="checkmark">&#10004;</div><div class="crossmark">&#10006;</div></button>';
            }

            winapp.innerHTML += '<p style="margin-right: 15px;"><strong>A terméket webre felvitted:</strong><span id="is_on_web_text" style="margin-left: 15px;">'+response.is_on_web+'</span></p>';
            if ((response.is_on_web == "" || response.is_on_web == null) && response.user_can_edit == true) {
              winapp.innerHTML += '<button class="Feedback" id="is_on_web_button" style="width: 100px;" onclick="StatementEditor(\''+item_id+'\', \'is_on_web\', \'A terméket webre felvitted\', true);"><span class="button-text">Nyilatkozok</span><div class="loader"></div><div class="checkmark">&#10004;</div><div class="crossmark">&#10006;</div></button>';
            } else if (response.user_can_edit == true) {
              winapp.innerHTML += '<button class="Feedback" id="is_on_web_button" style="width: 100px;" onclick="StatementEditor(\''+item_id+'\', \'is_on_web\', \'A terméket webre felvitted\', false);"><span class="button-text">Visszavonás</span><div class="loader"></div><div class="checkmark">&#10004;</div><div class="crossmark">&#10006;</div></button>';
            }

            winapp.innerHTML += '<p style="margin-right: 15px;"><strong>Az adatok Saturnusban és Kulcsszoftban megegyeznek:</strong><span id="is_data_valid_text" style="margin-left: 15px;">'+response.is_data_valid+'</span></p>';
            if ((response.is_data_valid == "" || response.is_data_valid == null) && response.user_can_edit == true) {
              winapp.innerHTML += '<button class="Feedback" id="is_data_valid_button" style="width: 100px;" onclick="StatementEditor(\''+item_id+'\', \'is_data_valid\', \'Az adatok Saturnusban és Kulcsszoftban megegyeznek\', true);"><span class="button-text">Nyilatkozok</span><div class="loader"></div><div class="checkmark">&#10004;</div><div class="crossmark">&#10006;</div></button>';
            } else if (response.user_can_edit == true) {
              winapp.innerHTML += '<button class="Feedback" id="is_data_valid_button" style="width: 100px;" onclick="StatementEditor(\''+item_id+'\', \'is_data_valid\', \'Az adatok Saturnusban és Kulcsszoftban megegyeznek\', false);"><span class="button-text">Visszavonás</span><div class="loader"></div><div class="checkmark">&#10004;</div><div class="crossmark">&#10006;</div></button>';
            }

            winapp.innerHTML += '<p style="margin-right: 15px;"><strong>Nagykereket / viszonteladókat / export partnereket értesítetted:</strong><span id="is_export_ready_text" style="margin-left: 15px;">'+response.is_export_ready+'</span></p>';
            if ((response.is_export_ready == "" || response.is_export_ready == null) && response.user_can_edit == true) {
              winapp.innerHTML += '<button class="Feedback" id="is_export_ready_button" style="width: 100px;" onclick="StatementEditor(\''+item_id+'\', \'is_export_ready\', \'Nagykereket / viszonteladókat / export partnereket értesítetted\', true);"><span class="button-text">Nyilatkozok</span><div class="loader"></div><div class="checkmark">&#10004;</div><div class="crossmark">&#10006;</div></button>';
            } else if (response.user_can_edit == true) {
              winapp.innerHTML += '<button class="Feedback" id="is_export_ready_button" style="width: 100px;" onclick="StatementEditor(\''+item_id+'\', \'is_export_ready\', \'Nagykereket / viszonteladókat / export partnereket értesítetted\', false);"><span class="button-text">Visszavonás</span><div class="loader"></div><div class="checkmark">&#10004;</div><div class="crossmark">&#10006;</div></button>';
            }

            winapp.innerHTML += '<br clear="all"><div style="border-top: solid 1px rgb(211,220,228); width: calc(100% - 15px); height: 0px;"></div><br clear="all"><br clear="all">';
            if (response.user_can_edit == true) {
              winapp.innerHTML += '<button onclick="StartFinal(\''+item_id+'\');">Végső ellenőrzésre küldés</button>';
            }

          } else {
            GenerateAlerts('error', response.message);
          }
        }, function() {
          Loading(false);
          GenerateAlerts('error', 'Hálózati hiba! Kérjük, próbálja újra');
        });
      }


      function StartFinal(item_id, Confirmed = false) {
        if (Confirmed) {
          Loading();
          const body = 'func=StartFinal&item_id='+item_id;
          get_POST_information("itemcreator.php", body, function(text) {
            let response = JSON.parse(text);
            Loading(false);
            if (response.status == "ok") {
              GenerateAlerts('success', 'Termék végső ellenőrzésre továbbküldve!');
              LoadItemCreatorInProgressList(true);
              OpenIntroduction(item_id);
            } else {
              GenerateAlerts('error', response.message);
            }
          }, function() {
            Loading(false);
            GenerateAlerts('error', 'Hálózati hiba! Kérjük, próbálja újra');
          });
        } else {
          var html = `
          <p><b>Biztos benne, hogy tovább akarja küldeni a folyamatot a végső ellenőrzésre?</b></p>
          <button id="AlertBtnNo" style="float: right; margin-left: 15px; width: 60px;">Nem</button>
          <button id="AlertBtnYes" style="float: right; width: 60px; background: var(--panelcolor); color: #f5f5f5; border: unset;">Igen</button>
          `;
          const overlay = CreateAlertBox('Végső ellenőrzésre', html);
          document.getElementById('AlertBtnYes').onclick = function () { StartFinal(item_id, true); CloseAlertBox(overlay); };
          document.getElementById('AlertBtnNo').onclick = function () { CloseAlertBox(overlay); };
          return;
        }
      }
      function OpenFinal(item_id, noeditmode = false) {
        Loading();
        openwin();
        wintitle.innerHTML = "Termék bevezetése - Végső ellenőrzés";
        const body = 'func=OpenFinal&item_id='+item_id;
        get_POST_information("itemcreator.php", body, function(text) {
          winapp.innerHTML = '<div id="errorDIV"></div>';
          let response = JSON.parse(text);
          if (!noeditmode) {Loading(false);}
          if (response.status == "ok") {

            if (!noeditmode) {
              winapp.innerHTML += '<h1 style="margin-bottom: 0px;">Végső ellenőrzés</h1><p style="margin-top: 5px;"></p>';
              winapp.innerHTML += '<p style="width: calc(100% - 139px); border-bottom: 1px solid #bdc3c7; font-weigth: bold; display: inline-block; margin-right: 15px; ">Kérjük, tekintse át az adatokat!</p>';
              winapp.innerHTML += '<div class="helpcursor" onclick="SendBasicData(\''+item_id+'\', false);" style="color: var(--panelcolor); border: 1px solid #ddd; padding: 6.5px; cursor: pointer;">Termék adatlap</div>';
            } else {
              winapp.innerHTML += '<h1 style="margin-bottom: 0px;">Lezárt termék bevezető</h1><p style="margin-top: 5px;"></p>';
            }

            winapp.innerHTML += '<br clear="all"><p style="width: calc(100% - 35px); border-bottom: 1px solid #bdc3c7; font-weigth: bold; display: inline-block; margin-right: 15px; ">Szerszám elkészítése</p>';
            winapp.innerHTML += '<p style="margin-right: 15px;"><strong>Szerszám rendben van:</strong><span style="margin-left: 15px;">'+response.is_tool_ok+'</span></p>';
            winapp.innerHTML += '<p style="margin-right: 15px;"><strong>Szerszám kész:</strong><span style="margin-left: 15px;">'+response.is_tool_created+'</span></p>';
            winapp.innerHTML += '<p style="margin-right: 15px;"><strong>Próbadarab kész:</strong><span style="margin-left: 15px;">'+response.is_tool_can_be_tested+'</span></p>';

            winapp.innerHTML += '<br clear="all"><p style="width: calc(100% - 35px); border-bottom: 1px solid #bdc3c7; font-weigth: bold; display: inline-block; margin-right: 15px; ">Termékpróba szakasz</p>';
            winapp.innerHTML += '<p style="margin-right: 15px;"><strong>Terméket tesztautóba bepróbálta:</strong><span style="margin-left: 15px;">'+response.is_tested_in_car+'</span></p>';
            winapp.innerHTML += '<p style="margin-right: 15px;"><strong>Sorozatgyártható:</strong><span style="margin-left: 15px;">'+response.is_production_ready+'</span></p>';

            winapp.innerHTML += '<br clear="all"><p style="width: calc(100% - 35px); border-bottom: 1px solid #bdc3c7; font-weigth: bold; display: inline-block; margin-right: 15px; ">Végső nyilatkozatok beküldése</p>';
            winapp.innerHTML += '<p style="margin-right: 15px;"><strong>Terméket Kulcsszoftba felvitte és -1 re állította a raktárkészletét:</strong><span style="margin-left: 15px;">'+response.is_kulcssoft_ready+'</span></p>';
            winapp.innerHTML += '<p style="margin-right: 15px;"><strong>A terméket webre felvitte:</strong><span style="margin-left: 15px;">'+response.is_on_web+'</span></p>';
            winapp.innerHTML += '<p style="margin-right: 15px;"><strong>Az adatok Saturnusban és Kulcsszoftban megegyeznek:</strong><span style="margin-left: 15px;">'+response.is_data_valid+'</span></p>';
            winapp.innerHTML += '<p style="margin-right: 15px;"><strong>Nagykereket / viszonteladókat / export partnereket értesítetted:</strong><span style="margin-left: 15px;">'+response.is_export_ready+'</span></p>';

            if (response.user_can_edit == true && !noeditmode) {
              winapp.innerHTML += '<br clear="all"><div style="border-top: solid 1px rgb(211,220,228); width: calc(100% - 15px); height: 0px;"></div><br clear="all"><br clear="all">';
              winapp.innerHTML += '<button onclick="StartComplete(\''+item_id+'\');">Gyártható</button>';
            }

          } else {
            GenerateAlerts('error', response.message);
          }
        }, function() {
          Loading(false);
          GenerateAlerts('error', 'Hálózati hiba! Kérjük, próbálja újra');
        });
      }


      function StartComplete(item_id, Confirmed = false) {
        if (Confirmed) {
          Loading();
          const body = 'func=StartComplete&item_id='+item_id;
          get_POST_information("itemcreator.php", body, function(text) {
            Loading(false);
            let response = JSON.parse(text);
            if (response.status == "ok") {
              GenerateAlerts('success', 'Termék sikeresen létrehozva!');
              LoadItemCreatorInProgressList(true);
              LoadTable();
              OpenIntroduction(item_id);
              StartProduction(item_id);
            } else {
              GenerateAlerts('error', response.message);
            }
          }, function() {
            Loading(false);
            GenerateAlerts('error', 'Hálózati hiba! Kérjük, próbálja újra');
          });
        } else {
          var html = `
          <p><b>Biztos benne, hogy a termék gyártásba kerülhet?</b></p>
          <button id="AlertBtnNo" style="float: right; margin-left: 15px; width: 60px;">Nem</button>
          <button id="AlertBtnYes" style="float: right; width: 60px; background: var(--panelcolor); color: #f5f5f5; border: unset;">Igen</button>
          `;
          const overlay = CreateAlertBox('Gyártásba kerülés', html);
          document.getElementById('AlertBtnYes').onclick = function () { StartComplete(item_id, true); CloseAlertBox(overlay); };
          document.getElementById('AlertBtnNo').onclick = function () { CloseAlertBox(overlay); };
          return;
        }
      }
      function StartProduction(item_id) {
        var classic_selected = '';
        var sporty_selected = '';
        var injmold_selected = '';

        if (/^\d/.test(item_id)) {
          classic_selected = 'selected';
        } else if (item_id.startsWith('FR')) {
          injmold_selected = 'selected';
        } else if (item_id.startsWith('F')) {
          sporty_selected = 'selected';
        }

        var html = `
        <p><b>Válassza ki a gyártás típusát</b></p>
        <select id="StartProductionType">
          <option value="">-- Válasszon --</option>
          <option value="classic" ${classic_selected}>Classic gyártás</option>
          <option value="sporty" ${sporty_selected}>Sporty gyártás</option>
          <option value="injmold" ${injmold_selected}>Fröccsöntött gyártás</option>
        </select>
        <br clear="all">
        <button id="AlertBtnNo" style="float: right; margin-left: 15px; width: 60px;">Mégsem</button>
        <button id="startProductionAlertBtn" style="float: right; background: var(--panelcolor); color: #f5f5f5;">Indítás</button>
        `;

        const overlay = CreateAlertBox('Gyártás létrehozása', html);

        document.getElementById('startProductionAlertBtn').onclick = function () {
          CloseAlertBox(overlay);
          CreateProduction(item_id, overlay);
        };
        document.getElementById('AlertBtnNo').onclick = function () { CloseAlertBox(overlay); };
      }
      function CreateProduction(item_id, overlay) {
        var type = document.getElementById('StartProductionType').value;
        if (type == null || type == "") {
          GenerateAlerts('warning', 'Nem válasszon ki egy típust! A gyártást innentől a <a href="./productionstat" style="text-decoration: underline; color: white;">Gyártástervezőből</a> indíthatja.');
          return;
        }

        Loading();
        const body = 'func=CreateProduction&item_id=' + encodeURIComponent(item_id).replace(/%20/g, '+') + '&type=' + type;
        get_POST_information("productionstat.php", body, function(text) {
          Loading(false);
          let response = JSON.parse(text);
          if (response.result == "ok") {
            GenerateAlerts("info", response.db_start + " pár cikkszám az ajánlott gyártási mennyiség.");
            GenerateAlerts("success", "Sikeresen felvette gyártásba! Továbbiakat a <a href='./production' style='text-decoration: underline; color: white;'>termékgyártás</a> menuponton érheti el.");
          } else {
            GenerateAlerts("error", response.result);
          }
        }, function() {
          Loading(false);
          GenerateAlerts("error", "Hálózati hiba!");
        });
      }
      function OpenComplete(item_id) {
        OpenFinal(item_id, true);
        wintitle.innerHTML = "Lezárt termék bevezetések";
        Loading();
        const body = 'func=OpenComplete&item_id='+item_id;
        setTimeout(function() {
          get_POST_information("itemcreator.php", body, function(text) {
            let response = JSON.parse(text);
            Loading(false);
            if (response.status == "ok") {
              winapp.innerHTML += '<br clear="all"><p style="width: calc(100% - 35px); border-bottom: 1px solid #bdc3c7; font-weigth: bold; display: inline-block; margin-right: 15px; ">A folyamatot lezárta</p>';
              winapp.innerHTML += '<p style="margin-right: 15px;"><strong>Felhasználó:</strong><span style="margin-left: 15px;">'+response.finalized_by+'</span></p>';
              winapp.innerHTML += '<p style="margin-right: 15px;"><strong>Dátum:</strong><span style="margin-left: 15px;">'+response.finalized_in+'</span></p>';

              winapp.innerHTML += '<br clear="all"><div style="border-top: solid 1px rgb(211,220,228); width: calc(100% - 15px); height: 0px;"></div><br clear="all"><br clear="all">';
              winapp.innerHTML += '<button onclick="GoToProduct(\''+item_id+'\');">Termékkatalógus</button>';
            } else {
              GenerateAlerts('error', response.message);
            }
          }, function() {
            Loading(false);
            GenerateAlerts('error', 'Hálózati hiba! Kérjük, próbálja újra');
          });
        }, 500);
      }
      function GoToProduct(item_id, Confirmed = false) {
        if (Confirmed) {
          window.location='./products?item='+item_id;
        } else {
          var html = `
          <p><b>Biztos át akar lépni a Termékkatalógusba?</b><br>Ha önnek nincsen joga megtekinteni, nem lesz elérhető számára!</p>
          <button id="AlertBtnNo" style="float: right; margin-left: 15px; width: 60px;">Nem</button>
          <button id="AlertBtnYes" style="float: right; width: 60px; background: var(--panelcolor); color: #f5f5f5; border: unset;">Igen</button>
          `;
          const overlay = CreateAlertBox('Termékkatalógus', html);
          document.getElementById('AlertBtnYes').onclick = function () { GoToProduct(item_id, true); CloseAlertBox(overlay); };
          document.getElementById('AlertBtnNo').onclick = function () { CloseAlertBox(overlay); };
          return;
        }
      }


      /* Bevezetett termékek */
      var orderby = 'item_id';
      var UserCanSeeOldInroduction = <?php if(UserHasPerm("read_item_introduction")) {echo 'true';} else {echo 'false';};?>;

      function LoadFilter() {
        const body = 'func=filter';
        get_POST_information("itemcreator.php", body, function(text) {
          let response = JSON.parse(text);
          if (response.result == "ok") {
            document.getElementById('filter-finalized_by').innerHTML = response.finalized_by;
            document.getElementById('filter-perpage').innerHTML = response.perpage;

            orderby_filter();
          } else {
            GenerateAlerts("error", response.result);
          }
        }, function() {
          GenerateAlerts("error", "Hálózati hiba!");
        });
      }
      function orderby_filter(by = 'item_id') {
        orderby = by;
        document.getElementById('cpage').innerHTML = '1';

        document.getElementById('table_head_item_id').innerHTML = "Cikkszám";
        document.getElementById('table_head_finalized_in').innerHTML = "Hitelesítés dátuma";
        document.getElementById('table_head_finalized_by').innerHTML = "Hitelesítő";

        if (by == "finalized_in") {
          document.getElementById('table_head_finalized_in').innerHTML = "Hitelesítés dátuma <small><small style='opacity: 0.6;'>(Rendezés eszerint)</small></small>";
        } else if (by == "finalized_by") {
          document.getElementById('table_head_finalized_by').innerHTML = "Hitelesítő <small><small style='opacity: 0.6;'>(Rendezés eszerint)</small></small>";
        } else {
          document.getElementById('table_head_item_id').innerHTML = "Cikkszám <small><small style='opacity: 0.6;'>(Rendezés eszerint)</small></small>";
        }

        LoadTable();
      }
      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() {
        if (UserCanSeeOldInroduction) {
          Loading();
          var item_id = document.getElementById("filter-item_id").value;
          var start_datetime = document.getElementById("filter-start_datetime").value;
          var end_datetime = document.getElementById("filter-end_datetime").value;
          var finalized_by = document.getElementById("filter-finalized_by").value;

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

          const body = 'func=table&perpage=' + perpage + '&cpage=' + cpage + '&orderby=' + orderby + '&item_id=' + encodeURIComponent(item_id).replace(/%20/g, '+') + '&start_datetime=' + encodeURIComponent(start_datetime).replace(/%20/g, '+') +'&end_datetime=' + encodeURIComponent(end_datetime).replace(/%20/g, '+') + '&finalized_by=' + encodeURIComponent(finalized_by).replace(/%20/g, '+');
          get_POST_information("itemcreator.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);

                  newCell_1.innerHTML = datas[0];
                  newCell_2.innerHTML = datas[1];
                  newCell_3.innerHTML = datas[2];
                  newCell_4.innerHTML = '<a style="cursor: pointer;" onclick="OpenIntroduction(\'' + datas[0] + '\')">Megnyitás</button>';
                }
              }
            } else {
              GenerateAlerts("error", response.result);
            }
          }, function() {
            Loading(false);
            GenerateAlerts("error", "Hálózati hiba!");
          });
        }
      }
      if (UserCanSeeOldInroduction) {
        LoadFilter();
        document.getElementById('completed_item_introduction_div').style.visibility = "visible";
        document.getElementById('completed_item_introduction_div').style.display = "unset";
      }

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