<?php

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

if (!(UserHasPerm('pr_parameters_read') || UserHasPerm('pr_parameters_edit') || UserHasPerm("edit_item_introduction_basic_data"))) {
  StopAndDie();
}

if (isset($_POST["func"])) {
  if (htmlspecialchars($_POST["func"]) == "table") {
    $maxperpage = intval(htmlspecialchars($_POST["perpage"]));
    $cpage = intval(htmlspecialchars($_POST["cpage"]));
    $data_status = htmlspecialchars($_POST["data_status"]);
    $orderby = htmlspecialchars($_POST["orderby"]);

    $category = htmlspecialchars($_POST["category"]);
    $car_brand = htmlspecialchars($_POST["car_brand"]);
    $car_type = htmlspecialchars($_POST["car_type"]);
    $car_year = htmlspecialchars($_POST["car_year"]);
    $car_doors = htmlspecialchars($_POST["car_doors"]);
    $item_id = htmlspecialchars(str_replace(' ', '+', $_POST['item_id']));
    $name_in_db = htmlspecialchars($_POST["name_in_db"]);

    if (!(UserHasPerm('pr_parameters_read') || UserHasPerm('pr_parameters_edit')) && UserHasPerm("edit_item_introduction_basic_data")) {
      $data_status = "0";
    }

    $addquery = "";
    $isfirst = true;

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

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

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

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

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

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

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

    if ($data_status != "" && $data_status != "ALL") {
      if ($isfirst) {
        $addquery = $addquery." WHERE data_status = '".$data_status."'";
        $isfirst = false;
      } else {
        $addquery = $addquery." and data_status = '".$data_status."'";
      }
    }

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

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

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

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

    $responseStr = '';
    $query = "SELECT * FROM pr_parameters".$addquery." LIMIT $limit, $maxperpage";
    if ($result = $conn->query($query)) {
      while ($c_pr_parameters = $result->fetch_assoc()) {

        if ($responseStr != "") {
          $responseStr .= "|%|";
        }

        $responseStr .= escapeForJson($c_pr_parameters['item_id']).'/!/'.escapeForJson($c_pr_parameters['name_in_db']).'/!/'.escapeForJson($c_pr_parameters['category']).'/!/'.escapeForJson($c_pr_parameters['car_brand']).'/!/'.escapeForJson($c_pr_parameters['car_type']).'/!/'.escapeForJson($c_pr_parameters['car_year']).'/!/'.escapeForJson($c_pr_parameters['car_doors']);
      }
    }

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

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

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

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

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

    $category = '<option value="">-- Összes --</option>';
    $query = "SELECT DISTINCT category FROM pr_parameters ORDER BY category ASC";
    if ($result = $conn->query($query)) {
      while ($ccat = $result->fetch_assoc()) {
        if ($ccat['category'] != null && $ccat['category'] != "") {
          $category .= "<option value='".$ccat['category']."'>".$ccat['category']."</option>";
        }
      }
    }

    $car_brand = '<option value="">-- Összes --</option>';
    $query = "SELECT DISTINCT car_brand FROM pr_parameters ORDER BY car_brand ASC";
    if ($result = $conn->query($query)) {
      while ($ccar_brand = $result->fetch_assoc()) {
        if ($ccar_brand['car_brand'] != null && $ccar_brand['car_brand'] != "") {
          $car_brand .= "<option value='".$ccar_brand['car_brand']."'>".$ccar_brand['car_brand']."</option>";
        }
      }
    }

    $car_type = '<option value="">-- Összes --</option>';
    $query = "SELECT DISTINCT car_type FROM pr_parameters ORDER BY car_type ASC";
    if ($result = $conn->query($query)) {
      while ($ccar_type = $result->fetch_assoc()) {
        if ($ccar_type['car_type'] != null && $ccar_type['car_type'] != "") {
          $car_type .= "<option value='".$ccar_type['car_type']."'>".$ccar_type['car_type']."</option>";
        }
      }
    }

    $car_doors = '<option value="">-- Összes --</option>';
    $query = "SELECT DISTINCT car_doors FROM pr_parameters ORDER BY car_doors ASC";
    if ($result = $conn->query($query)) {
      while ($ccar_doors = $result->fetch_assoc()) {
        if ($ccar_doors['car_doors'] != null && $ccar_doors['car_doors'] != "") {
          $car_doors .= "<option>".$ccar_doors['car_doors']."</option>";
        }
      }
    }


    $json = json_encode(array(
        'category' => $category,
        'car_brand' => $car_brand,
        'car_type' => $car_type,
        'car_doors' => $car_doors,
        'perpage' => $perpageselect,
        'result' => 'ok'
    ));

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

    $data = json_decode(file_get_contents($currentUrl."/managers/prdb.json"), true);
    if ($data) {
      $Tables = [];
      foreach ($data["DBList"] as $table) {
        if (UserHasPerm($table["ID"]."_read") || UserHasPerm($table["ID"]."_edit") || UserHasPerm("edit_item_introduction_basic_data")) {

          $sql = mysqli_query($conn,"SELECT item_id FROM ".$table["ID"]." WHERE item_id = '$item_id'");
          if (mysqli_fetch_array($sql)) {
            $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);
                    if (!($dbdata["data_status"] != "0" && !UserHasPerm($table["ID"]."_read"))) {
                      $all_product_information = array_merge($all_product_information, [$param["ID"] => $param["NAME"]."||".$dbdata[$newID]]);
                    }
                  }
                }

                $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'].'_uploader_name' => $userUploaderName]);
                $all_product_information = array_merge($all_product_information, [$table['ID'] => $table["NAME"]]);
                $all_product_information = array_merge($all_product_information, [$table['ID'].'_registration_date' => date("Y-m-d H:i:s", $dbdata["registration_date"])]);
                $all_product_information = array_merge($all_product_information, [$table['ID'].'_data_status' => $dbdata["data_status"]]);

                $EditingPerm = false;
                if ($dbdata["data_status"] == "0" && UserHasPerm("edit_item_introduction_basic_data")) {
                  $EditingPerm = true;
                } else if (UserHasPerm($table["ID"]."_edit")) {
                  $EditingPerm = true;
                }

                $CanSee = true;
                if ($dbdata["data_status"] != "0" && !UserHasPerm($table["ID"]."_read")) {
                  $CanSee = false;
                }

                $all_product_information = array_merge($all_product_information, [$table['ID'].'_can_see' => $CanSee]);
                $all_product_information = array_merge($all_product_information, [$table['ID'].'_can_edit' => $EditingPerm]);

              }
            }
          } else if (UserHasPerm($table["ID"]."_edit") || UserHasPerm("edit_item_introduction_basic_data")) {
            $all_product_information = array_merge($all_product_information, [$table['ID'] => $table["NAME"]]);
            $all_product_information = array_merge($all_product_information, [$table['ID'].'_can_edit' => true]);
          }

        } else {
          $all_product_information = array_merge($all_product_information, [$table['ID'].'_can_see' => false]);
        }

      }

      $item_query = "SELECT average_production, average_scrap, produced_quantity, total_consumption, went_into_production, year FROM statistics_annual WHERE item_id = '" . $item_id . "' ORDER BY year DESC";
      $result = mysqli_query($conn, $item_query);

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

      $all_product_information = array_merge( $all_product_information, ["result" => "ok", "item_id" => $item_id, "statistics_annual" => $statistics_annual] );

      $json = json_encode($all_product_information);
    } else {
      $json = json_encode(["result" => "DB Table loading error!"]);
    }

    echo $json;
  } else if (htmlspecialchars($_POST["func"]) == "addtable") {
    $item_id = htmlspecialchars(str_replace(' ', '+', $_POST['item_id']));
    $table_id = htmlspecialchars($_POST["table_id"]);
    $LocalData = json_decode(file_get_contents($currentUrl."/managers/prdb.json"), true);
    $json = "";

    if ($LocalData && (UserHasPerm("edit_item_introduction_basic_data") || UserHasPerm($table_id."_edit"))) {

      $isDB = false;
      foreach ($LocalData["DBList"] as $item) {
        if ($item["ID"] === $table_id) {
          $isDB = true;
          break;
        }
      }

      if ($isDB) {
        $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,"SELECT data_status FROM pr_parameters WHERE item_id = '$item_id'");
          $DataStatus = mysqli_fetch_array($sql)[0];

          $sql = mysqli_query($conn,"INSERT INTO ".$table_id." (item_id, uploader_uid, registration_date, data_status) VALUES ('".$item_id."', ".$userID.", ".$ctimestamp.", ".$DataStatus.")");
          $json = json_encode(["result" => "ok"]);
        } else {
          $json = json_encode(["result" => "Ez a tábla már létezik!"]);
        }
      } else {
        $json = json_encode(["result" => "Nem létezik ilyen nevű táblázat!"]);
      }
    } else {
      $json = json_encode(["result" => "Jogosultság megtagadva!"]);
    }

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

    if (UserHasPerm("god_profile")) {
      $sql = mysqli_query($conn,"SELECT item_id FROM pr_parameters WHERE item_id = '$old_item_id'");
      $check_item_id = mysqli_fetch_array($sql)[0];

      $sql = mysqli_query($conn,"SELECT item_id FROM pr_parameters WHERE item_id = '$new_item_id'");
      $check_new_item_id = mysqli_fetch_array($sql)[0];

      if ($check_item_id != null && $check_new_item_id == null) {
        $sql = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME = 'item_id';";
        $result = $conn->query($sql);
        if ($result) {
        	while ($row = $result->fetch_assoc()) {
        		$table = $row['TABLE_NAME'];

        		$update_sql = mysqli_query($conn,"UPDATE $table SET item_id = '$new_item_id' WHERE item_id = '$old_item_id'");
        	}
          $json = json_encode(["result" => "ok", "item_id" => $new_item_id]);
        } else {
          $json = json_encode(["result" => "Hiba a táblák lekérdezésekor: " . $conn->error]);
        }
      } else if ($check_item_id == null) {
        $json = json_encode(["result" => "Nem létező cikkszámot szeretne módosítani!"]);
      } else {
        $json = json_encode(["result" => "Ilyen azonosítóval létezik már cikkszám!"]);
      }
    } else {
      $json = json_encode(["result" => "Jogosultság megtagadva!"]);
    }
    echo $json;
  } else if (htmlspecialchars($_POST["func"]) == "GenerateExport") {
    $json = "";
    $all_product_information = array();

    $data = json_decode(file_get_contents($currentUrl."/managers/prdb.json"), true);
    if ($data) {

      $query = "SELECT item_id, data_status, price_category FROM pr_parameters";
      if ($result = $conn->query($query)) {
        while ($c_export = $result->fetch_assoc()) {
          $c_item_id = $c_export['item_id'];

          $all_product_information[$c_item_id][] = [
            "name" => 'Cikkszám',
            "value" => $c_item_id
          ];

          foreach ($data["DBList"] as $table) {
            $c_table_id = $table["ID"];
            if (UserHasPerm($c_table_id."_read") || UserHasPerm($c_table_id."_edit")) {

              $sql = mysqli_query($conn,"SELECT * FROM $c_table_id WHERE item_id = '$c_item_id'");
              $c_result = mysqli_fetch_array($sql);

              foreach ($data["Parameters"] as $param) {
                if (strpos($param["ID"], $table['ID'] . "_") === 0) {
                  $newID = substr($param["ID"], strlen($table['ID']) + 1);

                  if ($c_result != null) {
                    $all_product_information[$c_item_id][] = [
                      "name" => $param["NAME"],
                      "value" => $c_result[$newID]
                    ];
                  } else {
                    $all_product_information[$c_item_id][] = [
                      "name" => $param["NAME"],
                      "value" => ''
                    ];
                  }

                }
              }

            }
          }

          $statusText = match (intval($c_export["data_status"])) {
          	1  => 'Értékesíthető',
          	0  => 'Bevezetés alatt',
          	-1 => 'Kifutó',
          	-2 => 'Megszűnt',
          	default => 'Ismeretlen',
          };

          $all_product_information[$c_item_id][] = [
            "name" => 'Termék státusza',
            "value" => $statusText
          ];

          $category_name = $c_export["price_category"];
          $query_price = "SELECT type_name, currency, price FROM customer_types WHERE is_active = 1 and category_name = '$category_name'";
          if ($result_price = $conn->query($query_price)) {
            while ($c_price = $result_price->fetch_assoc()) {
              $all_product_information[$c_item_id][] = [
                "name" => $c_price['type_name'] . ' ár',
                "value" => $c_price['price'] . ' ' . $c_price['currency']
              ];
            }
          }

        }
      }


      $json = json_encode(["result" => "ok", "data" => $all_product_information]);
    } else {
      $json = json_encode(["result" => "DB Table loading error!"]);
    }

    echo $json;
  }

  exit();
} else if (isset($_GET['saving']) && $_GET['saving'] == 1) {

  header("Content-Type: application/json");

  $jsonData = file_get_contents("php://input");
  $data = json_decode($jsonData, true);

  $LocalData = json_decode(file_get_contents($currentUrl."/managers/prdb.json"), true);

  if ($data) {
    $tables = [];

    foreach ($data as $key => $value) {
      if (strpos($key, "_can_edit") !== false && $value === "true") {
        $tableName = str_replace("_can_edit", "", $key);

        $sql = mysqli_query($conn,"SELECT data_status FROM ".$tableName." WHERE item_id = '".$data['item_id']."'");
        $tableDataStatus = mysqli_fetch_array($sql)[0];

        $EditingPerm = false;
        if ($tableDataStatus == "0" && UserHasPerm("edit_item_introduction_basic_data")) {
          $EditingPerm = true;
        } else if (UserHasPerm($tableName.'_edit')) {
          $EditingPerm = true;
        }

        if ($EditingPerm) {
          $tables[] = $tableName;
        }

      }
    }

    $response = [];

    foreach ($tables as $table) {
      $updateFields = [];
      $updateValues = [];

      foreach ($data as $key => $value) {
        if (strpos($key, $table . "_") === 0 && $key !== $table . "_can_edit") {
          $columnName = str_replace($table . "_", "", $key);

          if ($table == "pr_warehouse_parameters" && $columnName == "size" && $data[$table."_".$columnName] != "") {
            $boxsizeoptions = array_column($LocalData['BoxSizes'], 'Name');
            if (!in_array($data[$table."_".$columnName], $boxsizeoptions, true)) {
              echo json_encode(["status" => "error", "message" => "Nem megfelelő doboz méretet adott meg a Raktározási paramétereknél!"]);
              die();
            }
          }

          $updateFields[] = "$columnName = '".htmlspecialchars($data[$table."_".$columnName])."'";
          $updateValues[] = $value;
        }
      }

      if (!empty($updateFields)) {
        $updateQuery = "UPDATE $table SET " . implode(", ", $updateFields) . " WHERE item_id = '".$data['item_id']."'";
        $sql = mysqli_query($conn, $updateQuery);
      }
    }

    echo json_encode(["status" => "done", "updates" => $response]);

  } else {
    echo json_encode(["status" => "error", "message" => "Hibás adat"]);
  }

  exit();
}

?>

<!DOCTYPE html>
<html lang="hu" dir="ltr">
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="../css/panel.css">
    <title>Kezelőfelület</title>
  </head>
  <body>
    <?php echo $menuhtml;?>
    <div class="window closed" id="win">
      <div class="topbar">
        <p id="wintitle">Title</p>
        <div class="btn fullscrn" onclick="fullscrn();" id="fullscrnbtn"></div>
        <div class="btn close" onclick="closewin();"></div>
      </div>
      <div class="wapp" id="winapp"><div id="errorDIV"></div></div>
      <div class="loading" id="winloading"></div>
    </div>
    <div class="loadingBG" id="loadingBG"><img src="../img/loading.gif"></div>
    <div class="content">
      <div id="errorDIV" style="z-index: 100; top: 50px; position: fixed; width: calc(100% - 260px);"></div>

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

      <h1>Termékkatalógus</h1>

      <a title="Excel letöltés" style="position: absolute; float: right; top: 65px; right: 15px;" onclick="GenerateExport()">
        <img style="width: 48px; height: 48px;" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAACXBIWXMAAAsTAAALEwEAmpwYAAAD/0lEQVR4nO2bbU8TQRDH++F8IfGtofU5GKxvNBCMDxHbirXylAAREBFQgQRBAWO4a6ul9FpLgaO29Hq3HwD8HmNmyy1XD4s17d0iO8k/5XaXm5nf3c5OmtTjESZMWD1GiHbBMPSfhOjghDq6B7Mensww9AOnkkedu3iHLwjEweRNAKiuwNCW5ywDOMcLBOIiAC4gEJcBuA6BcADAVQiEEwCuQSAcAXAFAuEMgOMQCIcAHIVAOAXgGATiMIB6JQA02wgHSQoARAAAAYAIACAAEAEAuADg7wrX1bE1Qv6uCE8AIo4DuH2PIwCEIwkAzTbCQZICAOEMgF+cAhFxChBOJAA02wgHSQoARAAARwEEJN+FoOT9GZS8cBoUWGs9CMjelsYBWGs9cDup+tW63zAAQdeT+TcJAI2y4DE3D8k+mFZ64E0qaJvDMZzDNT3yFZhMhWB0/UHNYPvi7TCjPIOF7DC8VZ7DwNfbzA+O4z1q+XEcwGx6gFZdwyjDSKKTjQ8nOukYzs1lBmgyZoXujbXb7vNU9sGX7fegE62qmuM9ZtN9MJ8ZpNe6UYahbx3s/0YsfjAWxwEMJe6CcRh0phCFkFR5CumCXEmAaHTNu3QvS8p8qseBRG2XFEjkV0DVvtPrhe8jMPytgyaP18oPufJWSD7q0+rHlRqwmptmwU+neqjM69XcFF1zEoCvu5/oXF7bZK8yfuITDkmX6PXnrRl2jyn0o1j8bFX8uALgWfQaDRwD2dWyVGYyOPc3AOSdBfbKL2++hnD0hm1NOHod8lrO5mcX/chX3QMQlLwwkey2dWOTG0eF8SQAY8kHbCuhSvoPWMm9sSWGBc/mJxVw7xQIWrRTSrOgdkqZqrmTAKBmlDDs6fmq5LZLKdvboJYyVfXipLgcAfBWCdueDFb+egCgIrE2ugU0vcDWr+3MWyAdnSas7ig97gKIxNqgUFZpMLniBhX+XSyr8CLWVhcAU/1xP93blbcpzfwUrX72Dv3oKp1zDUBUXWTJ4V5+uX4fDFI5smLq4l8BWM69hvX8Kk3cPOLwuMP1W3sbdCxWw09U/eAOgAlL8YurH9m4NdiJjSdVADChbDHBNJ58SIsezmn6HmQKcdi21BM8/v7kJ767ZPHz2HkAS5tjlcCNIvTFb1W1tOY+XsqOHbt3TWGjg93i712g2VxhEfyzHz+UjSKdW9wcdR5ASLpEe/RXyUe2ufHkI9oUYZv7VL5M+/i5TH+V3qd72f59EbsJs5l+WM5NwmL2JX2iZmdZyw+OTR36ce0UCHKshgEInPUvRAKyt+V0QWjdD0m+855mGOHgi89aakrSViNnHYDh8M/m6tS+AwCMFk4h7Ou63px9L0yY57+1Xyf2nhfCI+qBAAAAAElFTkSuQmCC" alt="external-xlsx-file-file-extension-fauzidea-flat-fauzidea">
      </a>

      <div style="width: 100%; min-height: 85px;">
        <div style="display: inline; float: left;">
          <p>Cikkszám: </p>
          <input type="text" id="filter-item_id" placeholder="Cikkszám..." value="<?php echo htmlspecialchars($_GET['item'] ?? '', ENT_QUOTES, 'UTF-8');?>" onkeydown="if (event.keyCode == 13) {SendFilter();}" autocomplete="off" style="width: 147px; height: 17px;">
        </div><div style="display: inline; float: left; padding-left: 15px;">
          <p>Terméknév: </p>
          <input type="text" id="filter-name_in_db" placeholder="Terméknév..." onkeydown="if (event.keyCode == 13) {SendFilter();}" autocomplete="off" style="width: 147px; height: 17px;">
        </div><div style="display: inline; float: left; padding-left: 15px;">
          <p>Termékkategória: </p>
          <select id="filter-category" onchange="SendFilter();"><option value="">-- Összes --</option></select>
        </div><div style="display: inline; float: left; padding-left: 15px;">
          <p>Autó: </p>
          <select id="filter-car_brand" onchange="SendFilter();"><option value="">-- Összes --</option></select>
        </div><div style="display: inline; float: left; padding-left: 15px;">
          <p>Típus: </p>
          <select id="filter-car_type" onchange="SendFilter();"><option value="">-- Összes --</option></select>
        </div><div style="display: inline; float: left; padding-left: 15px;">
          <p>Évjárat: </p>
          <input type="text" id="filter-car_year" placeholder="Évjárat..." onkeydown="if (event.keyCode == 13) {SendFilter();}" autocomplete="off" style="width: 147px; height: 17px;">
        </div><div style="display: inline; float: left; padding-left: 15px;">
          <p>Ajtók: </p>
          <select id="filter-car_doors" onchange="SendFilter();"><option value="">-- Összes --</option></select>
        </div><div style="display: inline; float: left; padding-left: 15px;">
          <p>Adat státusza: </p>
          <?php
          if (!(UserHasPerm('pr_parameters_read') || UserHasPerm('pr_parameters_edit')) && UserHasPerm("edit_item_introduction_basic_data")) {
            echo '<select id="filter-data_status" onchange="SendFilter();"><option value="0">Bevezetés alatt</option></select>';
          } else {
            echo '<select id="filter-data_status" onchange="SendFilter();"><option value="ALL">-- Összes --</option><option value="1">Értékesíthető</option><option value="0">Bevezetés alatt</option><option value="-1">Kifutó</option><option value="-2">Megszűnt</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_name_in_db" onclick="orderby_filter('name_in_db');" style="cursor: pointer;">Terméknév</th>
                <th id="table_head_category" onclick="orderby_filter('category');" style="cursor: pointer;">Termékkategória</th>
                <th id="table_head_car_brand" onclick="orderby_filter('car_brand');" style="cursor: pointer;">Autó</th>
                <th id="table_head_car_type" onclick="orderby_filter('car_type');" style="cursor: pointer;">Típus</th>
                <th id="table_head_car_year" onclick="orderby_filter('car_year');" style="cursor: pointer;">Évjárat</th>
                <th id="table_head_car_doors" onclick="orderby_filter('car_doors');" style="cursor: pointer;">Ajtók</th>
                <th style="width: 100px;">Adatlap</th>
              </tr>
            </thead>

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

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

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

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

    </div>
    <script src="../js/default.js" type="text/javascript"></script>
    <script src="../js/xlsx.full.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    Loading();

    var orderby = 'item_id';

    function LoadFilter() {
      const body = 'func=filter';
      get_POST_information("products.php", body, function(text) {
        let response = JSON.parse(text);
        if (response.result == "ok") {
          document.getElementById('filter-category').innerHTML = response.category;
          document.getElementById('filter-car_brand').innerHTML = response.car_brand;
          document.getElementById('filter-car_type').innerHTML = response.car_type;
          document.getElementById('filter-car_doors').innerHTML = response.car_doors;

          document.getElementById('filter-perpage').innerHTML = response.perpage;

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

    function SendFilter() {
      document.getElementById('cpage').innerHTML = '1';
      LoadTable();
    }
    function left() {
      var cpage = document.getElementById("cpage").innerHTML;
      if ((parseInt(cpage) - 1) >= 1) {
        document.getElementById("cpage").innerHTML = parseInt(cpage) - 1;
        LoadTable();
      }
    }
    function right() {
      var cpage = document.getElementById("cpage").innerHTML;
      var maxpage = document.getElementById("maxpage").innerHTML;
      if ((parseInt(cpage) + 1) <= parseInt(maxpage)) {
        document.getElementById("cpage").innerHTML = parseInt(cpage) + 1;
        LoadTable();
      }
    }
    function 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_name_in_db').innerHTML = "Terméknév";
      document.getElementById('table_head_category').innerHTML = "Termékkategória";
      document.getElementById('table_head_car_brand').innerHTML = "Autó";
      document.getElementById('table_head_car_type').innerHTML = "Típus";
      document.getElementById('table_head_car_year').innerHTML = "Évjárat";
      document.getElementById('table_head_car_doors').innerHTML = "Ajtók";

      if (by == "name_in_db") {
        document.getElementById('table_head_name_in_db').innerHTML = "Terméknév <small><small style='opacity: 0.6;'>(Rendezés eszerint)</small></small>";
      } else if (by == "category") {
        document.getElementById('table_head_category').innerHTML = "Termékkategória <small><small style='opacity: 0.6;'>(Rendezés eszerint)</small></small>";
      } else if (by == "car_brand") {
        document.getElementById('table_head_car_brand').innerHTML = "Autó <small><small style='opacity: 0.6;'>(Rendezés eszerint)</small></small>";
      } else if (by == "car_type") {
        document.getElementById('table_head_car_type').innerHTML = "Típus <small><small style='opacity: 0.6;'>(Rendezés eszerint)</small></small>";
      } else if (by == "car_year") {
        document.getElementById('table_head_car_year').innerHTML = "Évjárat <small><small style='opacity: 0.6;'>(Rendezés eszerint)</small></small>";
      } else if (by == "car_doors") {
        document.getElementById('table_head_car_doors').innerHTML = "Ajtók <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 LoadTable() {
      Loading();
      var category = document.getElementById('filter-category').value;
      var car_brand = document.getElementById('filter-car_brand').value;
      var car_type = document.getElementById('filter-car_type').value;
      var car_doors = document.getElementById('filter-car_doors').value;

      var item_id = document.getElementById('filter-item_id').value;
      var name_in_db = document.getElementById('filter-name_in_db').value;
      var car_year = document.getElementById('filter-car_year').value;

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

      const body = 'func=table&perpage=' + perpage + '&data_status=' + data_status + '&cpage=' + cpage + '&orderby=' + orderby + '&category=' + encodeURIComponent(category).replace(/%20/g, '+') + '&car_brand=' + encodeURIComponent(car_brand).replace(/%20/g, '+') + '&car_type=' + encodeURIComponent(car_type).replace(/%20/g, '+') + '&car_year=' + encodeURIComponent(car_year).replace(/%20/g, '+') + '&car_doors=' + encodeURIComponent(car_doors).replace(/%20/g, '+') + '&item_id=' + encodeURIComponent(item_id).replace(/%20/g, '+') + '&name_in_db=' + encodeURIComponent(name_in_db).replace(/%20/g, '+');

      get_POST_information("products.php", body, function(text) {
        Loading(false);
        let response = JSON.parse(text);
        if (response.result == "ok") {
          var table = document.getElementById('table').getElementsByTagName('tbody')[0];
          table.innerHTML = "";
          document.getElementById("cpage").innerHTML = response.cpage;
          document.getElementById("maxpage").innerHTML = response.maxpage;

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

              var newRow = table.insertRow();
              var newCell_1 = newRow.insertCell(0);
              var newCell_2 = newRow.insertCell(1);
              var newCell_3 = newRow.insertCell(2);
              var newCell_4 = newRow.insertCell(3);
              var newCell_5 = newRow.insertCell(4);
              var newCell_6 = newRow.insertCell(5);
              var newCell_7 = newRow.insertCell(6);
              var newCell_8 = newRow.insertCell(7);

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

    LoadFilter();

    function OpenProduct(item_id) {
      Loading();
      openwin();
      wintitle.innerHTML = "Adatlap";
      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") {

          var UserHaveSomeEditingPerm = false;

          winapp.innerHTML += '<div class="productbox" style="padding-left: 0px;"><p style="display: none; visibility: invisible;"></p><p id="pr_parameters_name_in_db" style="color: #333333; margin-bottom: 0px; margin-left: 0px; font-size: 23px; font-weight: bold;" contenteditable="'+response.pr_parameters_can_edit+'" spellcheck="false" autocorrect="off">'+response.pr_parameters_name_in_db.split("||")[1]+'</p></div>';
          winapp.innerHTML += '<input type="hidden" id="winapp_item_id" value="'+response.item_id+'">'  ;

          wintitle.innerHTML = "Adatlap - "+response.item_id;

          var EditItemIDText = ``;
          if (<?= UserHasPerm("god_profile") ? 'true' : 'false' ?>) {
            EditItemIDText = `<span style="margin-left: 5px; margin-right: 5px; opacity: 0.5; cursor: pointer;" onclick="RenameItemID('${response.item_id}');">&#9998;</span>`;
          }

          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> '+EditItemIDText+' - <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> '+EditItemIDText+' - <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> '+EditItemIDText+' - <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> '+EditItemIDText+' - <span style="color: var(--panelcolor);">Bevezetés alatt</span></p>';}

          winapp.innerHTML += '<br clear="all">';

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

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


          tableNames.forEach(table => {
            winapp.innerHTML += '<br clear="all">';
            if (response[table + "_can_edit"]) {
              UserHaveSomeEditingPerm = true;
              winapp.innerHTML += '<p style="width: calc(100% - 35px); border-bottom: 1px solid #bdc3c7; display: inline-block; margin-right: 15px; ">'+response[table]+' - <span style="color: var(--panelcolor);">Szerkeszthető</span></p>';
              winapp.innerHTML += '<div class="productbox" style="display: none; visibility: invisible;"><p></p><p id="'+table+'_can_edit" contenteditable="true" spellcheck="false" autocorrect="off">true</p></div>';
            } else {
              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 && field !== "pr_parameters_name_in_db") {
                var cvalue = response[field];
                winapp.innerHTML += '<div class="productbox"><p>'+cvalue.split("||")[0]+'</p><p id="'+field+'" contenteditable="'+response[table + "_can_edit"]+'"  spellcheck="false" autocorrect="off">'+cvalue.split("||")[1]+'</p></div>';
              }
            });
          });

          CanBeAddedTables.forEach(table => {
            winapp.innerHTML += '<br clear="all">';
            winapp.innerHTML += '<p style="width: calc(100% - 35px); border-bottom: 1px solid #bdc3c7; display: inline-block; margin-right: 15px; font-style: italic; opacity: 0.5;">'+response[table]+' - <span style="color: var(--panelcolor); cursor: pointer;" onclick="AddTable(\''+table+'\', \''+response.item_id+'\', \''+response[table]+'\')">Katt a hozzáadáshoz</span></p>';
          });


          if (UserHaveSomeEditingPerm) {
            winapp.innerHTML += '<br clear="all">';
            winapp.innerHTML += '<br clear="all">';
            winapp.innerHTML += '<button onclick="SaveProduct(\''+response.item_id+'\')">Adatbázisok mentése</button>';
          }

          let statistics = response.statistics_annual;
          if (Array.isArray(statistics) && statistics.length > 0) {
            winapp.innerHTML += '<br clear="all">';
            winapp.innerHTML += '<p style="width: 100%; border-bottom: 1px solid var(--panelcolor); font-weight: bold; display: inline-block; margin-top: 30px;">Éves statisztikák</p>';
            winapp.innerHTML += '<br clear="all">';

            statistics.forEach(item => {
              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; ">${item.year} -s év</p>`;
              winapp.innerHTML += `<p style="margin: 3px 20px;"><b>Éves fogyás: </b><span style="color: var(--panelcolor); margin-left: 6px;">${item.total_consumption ? item.total_consumption : " N/A "}</span> <span style="opacity: 0.6; margin-left: 6px;">pár</span></p>`;
              winapp.innerHTML += `<p style="margin: 3px 20px;"><b>Gyártási átlagidő: </b><span style="color: var(--panelcolor); margin-left: 6px;">${item.average_production ? item.average_production : " N/A "}</span> <span style="opacity: 0.6; margin-left: 6px;">nap</span></p>`;
              winapp.innerHTML += `<p style="margin: 3px 20px;"><b>Legyártott mennyiség: </b><span style="color: var(--panelcolor); margin-left: 6px;">${item.produced_quantity ? item.produced_quantity : " N/A "}</span> <span style="opacity: 0.6; margin-left: 6px;">pár</span></p>`;
              winapp.innerHTML += `<p style="margin: 3px 20px;"><b>Gyártásba került: </b><span style="color: var(--panelcolor); margin-left: 6px;">${item.produced_quantity ? item.produced_quantity : " N/A "}</span> <span style="opacity: 0.6; margin-left: 6px;">alkalom</span></p>`;
              winapp.innerHTML += `<p style="margin: 3px 20px;"><b>Átlag selejtszám: </b><span style="color: var(--panelcolor); margin-left: 6px;">${item.average_scrap ? item.average_scrap : " N/A "}</span> <span style="opacity: 0.6; margin-left: 6px;">pár</span></p>`;
            });

            winapp.innerHTML += '<br clear="all">';
            winapp.innerHTML += '<br clear="all">';
          }

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

    function SaveProduct(item_id) {
      Loading();
      const productboxes = document.querySelectorAll('.productbox');
      let ProductsData = {};
      productboxes.forEach(box => {
        const secondP = box.querySelectorAll('p')[1];
        if (secondP && secondP.id && secondP.isContentEditable) {
          ProductsData[secondP.id] = jsonSafeEncode(secondP.textContent);
        }
      });

      ProductsData["item_id"] = item_id;

      fetch("products.php?saving=1", {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify(ProductsData)
      })
      .then(response => response.json())
      .then(data => {
        if (data.status !== "done") {
          SaveResult(false, data.message);
        } else {
          SaveResult(true);
        }
      })
      .catch(error => SaveResult(false, error));

    }
    function AddTable(table_id, item_id, print_name, Confirmed = false) {
      if (Confirmed) {
        Loading();
        const body = 'func=addtable&table_id='+table_id+'&item_id='+item_id;
        get_POST_information("products.php", body, function(text) {
          let response = JSON.parse(text);
          Loading(false);
          if (response.result == "ok") {
            OpenProduct(item_id);
          } else {
            GenerateAlerts("error", response.result);
          }
        }, function() {
          Loading(false);
          GenerateAlerts("error", "Hálózati hiba!");
        });
      } else {
        var html = `
        <p><b>Biztos benne, hogy hozzá szeretné adni a(z) '${item_id}' cikkszámhoz a(z) '${print_name}' táblázatot?</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('Tábla hozzáadása', html);
        document.getElementById('AlertBtnYes').onclick = function () { AddTable(table_id, item_id, print_name, true); CloseAlertBox(overlay); };
        document.getElementById('AlertBtnNo').onclick = function () { CloseAlertBox(overlay); };
        return;
      }
    }
    function SaveResult(isSuccess, WhyNot = "") {
      Loading(false);
      if (isSuccess) {
        GenerateAlerts("success", "Sikeresen elmentve!");
      } else {
        GenerateAlerts("error", WhyNot);
      }
    }

    function RenameItemID(item_id) {
      var html = `
      <p><b>Biztos benne, hogy módosítani szeretné a '${item_id}' cikkszám azonosítóját?</b></p>
      <button id="AlertBtnNo" style="float: right; margin-left: 15px; width: 60px;">Mégse</button>
      <button id="AlertBtnYes" style="float: right; width: 60px; background: var(--panelcolor); color: #f5f5f5; border: unset;">Igen</button>
      `;
      const overlay = CreateAlertBox('Cikkszám azonosító átnevezése', html);
      document.getElementById('AlertBtnYes').onclick = function () { GetNewItemIDName(item_id); CloseAlertBox(overlay); };
      document.getElementById('AlertBtnNo').onclick = function () { CloseAlertBox(overlay); };
    }
    function GetNewItemIDName(item_id) {
      var html = `
      <p><b>Adja meg, hogy a '${item_id}' cikkszám azonosító helyett mi legyen az új azonosító</b></p>
      <input type="text" id="AlertTextInput" placeholder="Új cikkszám..." value="" autocomplete="off" style="width: 100px;">
      <button id="AlertBtnNo2" style="float: right; margin-left: 15px; width: 60px;">Mégse</button>
      <button id="AlertBtnYes2" style="float: right; width: 60px; background: var(--panelcolor); color: #f5f5f5; border: unset;">Mentés</button>
      `;
      const overlay = CreateAlertBox('Cikkszám azonosító átnevezése', html);
      document.getElementById('AlertBtnYes2').onclick = function () { SaveNewItemIDName(item_id, document.getElementById("AlertTextInput").value); CloseAlertBox(overlay); };
      document.getElementById('AlertBtnNo2').onclick = function () { CloseAlertBox(overlay); };
    }
    function SaveNewItemIDName(item_id, new_item_id) {
      Loading();
      const body = 'func=SaveNewItemIDName&item_id=' + item_id + '&new_item_id=' + new_item_id;
      get_POST_information("products.php", body, function(text) {
        let response = JSON.parse(text);
        Loading(false);
        if (response.result == "ok") {
          GenerateAlerts("success", "Sikeresen módosította a cikkszámot!");
          SendFilter();
          OpenProduct(response.item_id);
        } else {
          GenerateAlerts("error", response.result);
        }
      }, function() {
        Loading(false);
        GenerateAlerts("error", "Hálózati hiba!");
      });
    }

    isCtrl = false;
    document.onkeydown=function(e){
        if(e.keyCode == 17) isCtrl=true;
        if(e.keyCode == 83 && isCtrl == true) {
          if (!win.classList.contains("closed")) {
            SaveProduct(document.getElementById("winapp_item_id").value);
            return false;
          }
        }
    }
    document.onkeyup = function(e) {
      if (e.keyCode == 17) isCtrl = false;
    }

    function GenerateExport() {
      Loading();
      const body = 'func=GenerateExport';
      get_POST_information("products.php", body, function(text) {
        let response = JSON.parse(text);
        if (response.result == "ok") {

          const allHeaders = new Set();
          Object.values(response.data).forEach(productArray => {
            productArray.forEach(item => allHeaders.add(item.name));
          });
          const headers = Array.from(allHeaders);

          const hiddenTable = document.createElement('table');
          hiddenTable.id = 'export-table';
          hiddenTable.style.cssText = 'position: absolute; left: -9999px; visibility: hidden;';

          const thead = hiddenTable.createTHead();
          const headerRow = thead.insertRow();
          headers.forEach(header => {
            const th = document.createElement('th');
            th.textContent = header;
            headerRow.appendChild(th);
          });

          const tbody = hiddenTable.createTBody();
          Object.entries(response.data).forEach(([productId, productArray]) => {
            const row = tbody.insertRow();

            headers.forEach(header => {
              const item = productArray.find(i => i.name === header);
              const cell = row.insertCell(-1);
              cell.textContent = item ? item.value : '';
            });
          });

          document.body.appendChild(hiddenTable);

          exportCSV(headers);
        } else {
          Loading(false);
          GenerateAlerts("error", response.result);
        }
      }, function() {
        GenerateAlerts("error", "Hálózati hiba!");
      });
    }
    function setColumnWidths(ws, headers) {
      const cols = [];

      headers.forEach((header, idx) => {
        const colIdx = idx;
        const headerLen = header.length;
        cols[colIdx] = { wch: Math.max(headerLen + 2, 10) };
      });

      ws['!cols'] = cols;
    }
    function exportCSV(headers) {
      const table = document.getElementById('export-table');

      const workbook = XLSX.utils.table_to_book(table, {sheet: 'Katalógus', raw: true});
      const ws = workbook.Sheets['Katalógus'];
      setColumnWidths(ws, headers);
      ws['!autofilter'] = { ref: ws['!ref'] };

      workbook.Props = {
        Author: "Szaturnusz",
        Title: "Termékkatalógus",
        Subject: new Date().toLocaleDateString('hu-HU'),
        Company: "Szatuna Kft."
      };

      XLSX.writeFile(workbook, 'calalogue_export.xlsx');

      const tableToRemove = document.getElementById('export-table');
      if (tableToRemove) {
        document.body.removeChild(tableToRemove);
      }
      Loading(false);
    }

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