<?php

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

if (!(UserHasPerm('warehouse_editor') || UserHasPerm('warehouse_statistic') || UserHasPerm('warehouse_add'))) {
  if (isset($_GET["boxsize"]) && (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'))) {

  } else {
    StopAndDie();
  }
}

if (isset($_POST["func"])) {
  if (htmlspecialchars($_POST["func"]) == "ShowWarehouseLocation") {
  	$query = "SELECT location, code, full_capacity, warehouse_id FROM warehouse_structure ORDER BY location, code ASC";
  	$result = $conn->query($query);

  	$locations = [];
  	if ($result) {
  		while ($row = $result->fetch_assoc()) {
  			$locations[$row['location']][] = [
  				'code' => $row['code'],
  				'capacity' => intval($row['full_capacity']),
  				'warehouse_id' => intval($row['warehouse_id'])
  			];
  		}
  	}

  	function commonPrefix($str1, $str2) {
  		$len = min(strlen($str1), strlen($str2));
  		for ($i = 0; $i < $len; $i++) {
  			if ($str1[$i] !== $str2[$i]) {
  				return substr($str1, 0, $i);
  			}
  		}
  		return substr($str1, 0, $len);
  	}

  	$commonPrefixes = [];
  	foreach ($locations as $location => $codes) {
  		$firstCode = array_shift($codes);
  		$prefix = $firstCode['code'];
  		$totalCapacity = $firstCode['capacity'];
  		$totalAmount = 0;

  		// Első raktár tartalmának lekérése
  		$amountQuery = "SELECT SUM(amount) as total_amount FROM warehouse WHERE warehouse_id = " . $firstCode['warehouse_id'];
  		$amountResult = $conn->query($amountQuery);
  		if ($amountResult) {
  			$amountRow = $amountResult->fetch_assoc();
  			$totalAmount += intval($amountRow['total_amount']);
  		}

  		foreach ($codes as $codeData) {
  			$prefix = commonPrefix($prefix, $codeData['code']);
  			$totalCapacity += $codeData['capacity'];

  			// Többi raktár tartalmának lekérése
  			$amountQuery = "SELECT SUM(amount) as total_amount FROM warehouse WHERE warehouse_id = " . $codeData['warehouse_id'];
  			$amountResult = $conn->query($amountQuery);
  			if ($amountResult) {
  				$amountRow = $amountResult->fetch_assoc();
  				$totalAmount += intval($amountRow['total_amount']);
  			}

  			if ($prefix === "") break;
  		}

  		$commonPrefixes[$location] = [
  			'prefix' => $prefix,
  			'capacity' => $totalCapacity,
  			'amount' => $totalAmount
  		];
  	}

  	$responseStrLoc = '';
  	$responseStrCode = '';
  	$responseStrCapacity = '';
  	$responseStrAmount = '';

  	foreach ($commonPrefixes as $location => $data) {
  		if ($responseStrLoc != "") {
  			$responseStrLoc .= "|%|";
  			$responseStrCode .= "|%|";
  			$responseStrCapacity .= "|%|";
  			$responseStrAmount .= "|%|";
  		}
  		$responseStrLoc .= $location;
  		$responseStrCode .= $data['prefix'];
  		$responseStrCapacity .= $data['capacity'];
  		$responseStrAmount .= $data['amount'];
  	}

  	echo '{"result": "ok", "loc": "'.$responseStrLoc.'", "code": "'.$responseStrCode.'", "capacity": "'.$responseStrCapacity.'", "amount": "'.$responseStrAmount.'"}';
  } else if (htmlspecialchars($_POST["func"]) == "OpenLoc") {
    $location = htmlspecialchars($_POST["location"]);
    $responseStr = '';
    $query = "SELECT name, warehouse_id, status, code FROM warehouse_structure WHERE location = '$location' ORDER BY CAST(SUBSTRING_INDEX(name, '.', 1) AS UNSIGNED) ASC";
    if ($result = $conn->query($query)) {
      while ($warehouse = $result->fetch_assoc()) {
        if ($responseStr != "") {
          $responseStr = $responseStr."|%|";
        }
        $responseStr = $responseStr.$warehouse["name"]."|".$warehouse["warehouse_id"]."|".$warehouse["status"]."|".$warehouse["code"];
      }
    }
    echo '{"result": "ok", "data": "'.$responseStr.'"}';
  } else if (htmlspecialchars($_POST["func"]) == "OpenWarehouse") {
    $warehouse_id = htmlspecialchars($_POST["id"]);
    $sql = mysqli_query($conn,"SELECT * FROM warehouse_structure WHERE warehouse_id = '$warehouse_id'");
    $warehouse_structure = mysqli_fetch_array($sql);

    $SizeJSON = json_decode(base64_decode($warehouse_structure["size"]), true);
    $size = $SizeJSON['globalSize'];
    $capacity = $SizeJSON['globalCapacity'];

    $inwarehouse = '';
    $query = "SELECT item_id, position, amount FROM warehouse WHERE warehouse_id = '$warehouse_id' and amount != 0 ORDER BY item_id ASC";
    if ($result = $conn->query($query)) {
      while ($warehouse = $result->fetch_assoc()) {
        if ($inwarehouse != "") {
          $inwarehouse = $inwarehouse."|%|";
        }
        $item_id = $warehouse["item_id"];

        $item_name = "";

        $inwarehouse = $inwarehouse.$item_id."|".$warehouse["position"]."|".$warehouse["amount"]."|".$item_name;
      }
    }

    if ($warehouse_structure != null) {
      $json = json_encode([
        "result" => "ok",
        "name" => $warehouse_structure["name"],
        "location" => $warehouse_structure["location"],
        "code" => $warehouse_structure["code"],
        "row" => $warehouse_structure["row"],
        "columns" => $warehouse_structure["columns"],
        "fullcapacity" => $warehouse_structure["full_capacity"],
        "status" => $warehouse_structure["status"],
        "inwarehouse" => $inwarehouse,
        "canedit" => UserHasPerm('warehouse_editor'),
        "canstatistic" => UserHasPerm('warehouse_statistic'),
        "size" => $warehouse_structure["size"]
      ]);
    } else {
      $json = json_encode(["result" => "Nem létezik raktár ezzel az azonosítóval! Próbálja újra."]);
    }

    echo $json;
  } else if (htmlspecialchars($_POST["func"]) == "OpenCell") {
    $warehouse_id = htmlspecialchars($_POST["warehouse_id"]);
    $column = htmlspecialchars($_POST["column"]);
    $row = htmlspecialchars($_POST["row"]);

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

    $sizeJSON = json_decode(base64_decode($warehouse_structure["size"]), true);
    $size = $sizeJSON['globalSize'];
    if (isset($sizeJSON['customSizes'][$column.':'.$row])) {
      $size = $sizeJSON['customSizes'][$column.':'.$row];
    }

    $capacity = $sizeJSON['globalCapacity'];
    if (isset($sizeJSON['customCapacity'][$column.':'.$row])) {
      $capacity = $sizeJSON['customCapacity'][$column.':'.$row];
    }

    $inwarehouse = '';
    $position = ($row + 1).':'.($column + 1);
    $query = "SELECT item_id, amount FROM warehouse WHERE warehouse_id = '$warehouse_id' and position = '$position' and  amount != 0 ORDER BY amount ASC";
    if ($result = $conn->query($query)) {
      while ($warehouse = $result->fetch_assoc()) {
        $inwarehouse = $inwarehouse.'<li>'.$warehouse['item_id'].' - '.$warehouse['amount'].' db</li>';
      }
    }
    if ($inwarehouse == "") {
      $inwarehouse = "<li>Üres</li>";
    }

    if ($warehouse_structure != null) {
      $json = json_encode([
        "result" => "ok",
        "capacity" => $capacity,
        "size" => $size,
        "content" => $inwarehouse,
        "box_stock_taking" => UserHasPerm("box_stock_taking")
      ]);
    } else {
      $json = json_encode(["result" => "Nem létezik raktár ezzel az azonosítóval! Próbálja újra."]);
    }
    echo $json;
  } else if (htmlspecialchars($_POST["func"]) == "SaveNewWarehouse") {
    $name = htmlspecialchars($_POST["name"]);
    $loc = htmlspecialchars($_POST["location"]);
    $code = htmlspecialchars($_POST["code"]);
    $row = $_POST["row"];
    $columns = $_POST["columns"];
    $capacity = $_POST["capacity"];

    $sql = mysqli_query($conn,"SELECT warehouse_id FROM warehouse_structure WHERE name = '$name' and location = '$loc'");
    $warehouse_structure = mysqli_fetch_array($sql);
    if (!UserHasPerm('warehouse_editor')) {
      $json = json_encode(["result" => "Önnek nincsen joga új raktárat létrehozni!"]);
    } else if ($warehouse_structure != null) {
      $json = json_encode(["result" => "Ezen a raktárhelyen létezik ilyen nevű raktár!"]);
    } else if ($name == "" || $loc == "" || $code == "" || $row == "" || $columns == "" || $capacity == "") {
      $json = json_encode(["result" => "Az összes paraméter megadása kötelező!"]);
    } else if (!(ctype_digit($row) && ctype_digit($columns) && ctype_digit($capacity))) {
      $json = json_encode(["result" => "Egyes paraméterek nem felelnek meg a formai követelményeknek!"]);
    } else {
      $size = base64_encode('{"globalSize": "Univerzális", "customSizes": {}, "globalCapacity": "'.$capacity.'", "customCapacity":{}}');
      $sql = mysqli_query($conn,"INSERT INTO warehouse_structure (`name`, `location`, `code`, `row`, `columns`, `size`, `capacity`) VALUES ('$name', '$loc', '$code', '$row', '$columns', '$size', '$capacity')");
      $sql = mysqli_query($conn,"SELECT warehouse_id FROM warehouse_structure WHERE name = '$name' and location = '$loc'");
      $warehouse_structure = mysqli_fetch_array($sql);
      $json = json_encode(["result" => "ok", "wid" => $warehouse_structure["warehouse_id"]]);
    }

    echo $json;
  } else if (htmlspecialchars($_POST["func"]) == "EditWarehouse") {
    $warehouse_id = htmlspecialchars($_POST["warehouse_id"]);

    $sql = mysqli_query($conn,"SELECT * FROM warehouse_structure WHERE warehouse_id = '$warehouse_id'");
    $warehouse_structure = mysqli_fetch_array($sql);
    if ($warehouse_structure == null) {
      $json = json_encode(["result" => "Nem létező raktár azonosító lett megadva! Próbálja újra."]);
    } else if (!UserHasPerm('warehouse_editor')) {
      $json = json_encode(["result" => "Önnek nincsen joga raktárat módosítani!"]);
    } else {
      $sql = mysqli_query($conn,"SELECT count(amount) FROM warehouse WHERE warehouse_id = '$warehouse_id' and amount != 0");
      $isempty = mysqli_fetch_array($sql)[0];
      $canedit = false;
      if ($isempty == 0) {
        $canedit = true;
      }

      $canedit = true; // --> Átmenetileg bekapcsolva

      $json = json_encode([
        "result" => "ok",
        "name" => $warehouse_structure["name"],
        "location" => $warehouse_structure["location"],
        "code" => $warehouse_structure["code"],
        "row" => $warehouse_structure["row"],
        "columns" => $warehouse_structure["columns"],
        "size" => $warehouse_structure["size"],
        "capacity" => $warehouse_structure["capacity"],
        "status" => $warehouse_structure["status"],
        "multiitem_row" => $warehouse_structure["multiitem_row"],
        "canedit" => $canedit,
      ]);
    }

    echo $json;
  } else if (htmlspecialchars($_POST["func"]) == "SaveWarehouse") {
    $name = htmlspecialchars($_POST["name"]);
    $loc = htmlspecialchars($_POST["location"]);
    $code = htmlspecialchars($_POST["code"]);
    $row = $_POST["row"];
    $columns = $_POST["columns"];
    $capacity = $_POST["capacity"];
    $status = $_POST["status"];
    $multiitem_row = $_POST["multiitem_row"];
    $size = htmlspecialchars($_POST["size"]);
    $warehouse_id = htmlspecialchars($_POST["warehouse_id"]);

    $SizeJSON = json_decode(base64_decode($size), true);
    $capacity = $SizeJSON['globalCapacity'];

    $cellcount = intval($row) * intval($columns);
    $fullcapacity = 0;

    foreach ($SizeJSON['customCapacity'] as $key => $cap) {
      $cellcount--;
      $fullcapacity += intval($cap);
    }

    $fullcapacity += $cellcount * intval($capacity);

    if (!UserHasPerm('warehouse_editor')) {
      $json = json_encode(["result" => "Önnek nincsen joga új raktárat módosítani!"]);
    } else if ($name == "" || $loc == "" || $code == "" || $row == "" || $columns == "" || $capacity == "") {
      $json = json_encode(["result" => "Az összes paraméter megadása kötelező!"]);
    } else {
      $sql = mysqli_query($conn,"UPDATE warehouse_structure SET `name`='$name',`location`='$loc',`code`='$code',`row`='$row',`columns`='$columns',`size`='$size',`capacity`='$capacity',`status`='$status',`full_capacity`=$fullcapacity,`multiitem_row`=$multiitem_row  WHERE warehouse_id = '$warehouse_id'");
      $json = json_encode(["result" => "ok"]);
    }

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

  	$item_id = htmlspecialchars(str_replace(' ', '+', $_POST['item_id']));
  	$location = htmlspecialchars($_POST["location"]);

  	$addquery = "";
  	$isfirst = true;

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

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

  	$WarehouseData = array();
    $finded_place = false;

  	if ($location != "") {
  		$locationquery = 'warehouse_id IN (';
  		$query = "SELECT warehouse_id, name, location FROM warehouse_structure WHERE code LIKE '%$location%'";
  		if ($result = $conn->query($query)) {
  			while ($warehouse = $result->fetch_assoc()) {
          $finded_place = true;
  				$locationquery = $locationquery."'".$warehouse["warehouse_id"]."',";
  				$WarehouseData[$warehouse["warehouse_id"]] = [
  					"name" => $warehouse["name"],
  					"location" =>$warehouse["location"]
  				];
  			}
  		}
  		$locationquery = substr($locationquery, 0, -1).')';

      if ($finded_place) {
        if ($isfirst) {
          $addquery = $addquery." WHERE ".$locationquery;
          $isfirst = false;
        } else {
          $addquery = $addquery." AND ".$locationquery;
        }
      }
  	}
    if ($location == "" || !$finded_place) {
  		$query = "SELECT warehouse_id, name, location FROM warehouse_structure";
  		if ($result = $conn->query($query)) {
  			while ($warehouse = $result->fetch_assoc()) {
  				$WarehouseData[$warehouse["warehouse_id"]] = [
  					"name" => $warehouse["name"],
  					"location" =>$warehouse["location"]
  				];
  			}
  		}
  	}

  	if ($isfirst) {
  		$addquery = $addquery." WHERE amount != 0";
  		$isfirst = false;
  	} else {
  		$addquery = $addquery." AND amount != 0";
  	}

  	// Raktár darabszám
  	$countQuery = "SELECT COUNT(*) as total FROM (
  		SELECT item_id, warehouse_id
  		FROM warehouse".$addquery."
  		GROUP BY item_id, warehouse_id
  	) as grouped_results";

  	$sql = mysqli_query($conn, $countQuery);
  	$warehouse_count = mysqli_fetch_array($sql)['total'];

  	// Fóliás darabszám
  	$foil_count = 0;
  	$foil_count_query = "SELECT COUNT(*) as total FROM warehouse_foil WHERE is_active = 1";
  	if ($item_id != "") {
  		$foil_count_query .= " AND item_id LIKE '%".$item_id."%'";
  	}
    if ($location != "") {
      $foil_count_query .= " AND place LIKE '%".$location."%'";
    }
  	$foil_sql = mysqli_query($conn, $foil_count_query);
  	$foil_count = mysqli_fetch_array($foil_sql)['total'];

  	$total_count = $warehouse_count + $foil_count;
  	$maxpage = ceil($total_count / $maxperpage);
  	if (!($cpage >= 1 && $cpage <= $maxpage)) {
  		$cpage = 1;
  	}

  	$responseArr = array();

  	// Raktár adatok lekérdezése
    $offset = ($cpage - 1) * $maxperpage;
    $query = "SELECT item_id, warehouse_id, SUM(amount) as total_amount
          FROM warehouse".$addquery."
          GROUP BY item_id, warehouse_id
          LIMIT $offset, $maxperpage";

    if ($result = $conn->query($query)) {
      while ($warehouse_result = $result->fetch_assoc()) {
        $responseArr[] = [
          "item_id" => $warehouse_result['item_id'],
          "amount" => $warehouse_result['total_amount'],
          "location" => $WarehouseData[$warehouse_result['warehouse_id']]['location'],
          "name" => $WarehouseData[$warehouse_result['warehouse_id']]['name'],
          "warehouse_id" => $warehouse_result['warehouse_id'],
          "type" => "warehouse"
        ];
      }
    }

  	// Ha szükséges fóliás adatok lekérdezése
  	if (count($responseArr) < $maxperpage) {
  		$remaining = $maxperpage - count($responseArr);
  		$foil_offset = max(0, $offset - $warehouse_count);

  		if ($offset < $warehouse_count + $foil_count) {
  			$foil_query = "SELECT wid, item_id, place, right_db, left_db FROM warehouse_foil WHERE is_active = 1";
  			if ($item_id != "") {
  				$foil_query .= " AND item_id LIKE '%".$item_id."%'";
  			}
        if ($location != "") {
          $foil_query .= " AND place LIKE '%".$location."%'";
        }
  			$foil_query .= " LIMIT $foil_offset, $remaining";

  			if ($result = $conn->query($foil_query)) {
  				while ($foil_result = $result->fetch_assoc()) {
  					$min_amount = min(intval($foil_result['left_db']), intval($foil_result['right_db']));
  					$responseArr[] = [
  						"item_id" => $foil_result['item_id'],
  						"amount" => $min_amount,
  						"location" => "Fóliás raktár",
  						"name" => $foil_result['place'],
  						"warehouse_id" => "foil",
  						"type" => "foil"
  					];
  				}
  			}
  		}
  	}

  	$reverse = false;
  	if (!empty($orderby) && $orderby[0] === '!') {
  		$reverse = true;
  		$orderby = substr($orderby, 1);
  	}

  	if ($orderby == "amount") {
  		usort($responseArr, function($a, $b) use ($orderby, $reverse) {
  			$result = $a[$orderby] <=> $b[$orderby];
  			return $reverse ? -$result : $result;
  		});
  	} else {
  		usort($responseArr, function($a, $b) use ($orderby, $reverse) {
  			$result = strcmp($a[$orderby], $b[$orderby]);
  			return $reverse ? -$result : $result;
  		});
  	}

  	$responseStr = "";
  	for ($i=0; $i < count($responseArr); $i++) {
  		if ($responseStr != "") {
  			$responseStr .= "|%|";
  		}
  		$warehouse_id = ($responseArr[$i]['type'] == 'foil') ? 'foil' : $responseArr[$i]['warehouse_id'];
  		$responseStr .= $responseArr[$i]['item_id'].'/!/'.$responseArr[$i]['amount'].'/!/'.$responseArr[$i]['location'].'/!/'.$responseArr[$i]['name'].'/!/'.$warehouse_id;
  	}

  	echo '{"result": "ok", "data": "'.$responseStr.'", "maxpage": "'.$maxpage.'", "cpage": "'.$cpage.'"}';
  } else if (htmlspecialchars($_POST["func"]) == "SearchFoilItem") {
    $item_id = htmlspecialchars(str_replace(' ', '+', $_POST['item_id']));

    $sql = mysqli_query($conn, "SELECT foil_product_place, item_id FROM pr_warehouse_parameters WHERE item_id = '$item_id'");
    $warehouse_foil_param = mysqli_fetch_array($sql);

    if ($warehouse_foil_param == null) {
        echo json_encode(["result" => "A termék nem szerepel a katalógusban!"]);
        exit();
    } else if (preg_replace('/^\s+|\s+$/', '', $warehouse_foil_param['foil_product_place']) == "") {
        echo json_encode(["result" => "A terméknek nincs fóliás raktárhelye"]);
        exit();
    }

    $item_id = $warehouse_foil_param['item_id'];

    $places = array_map('trim', explode(',', $warehouse_foil_param['foil_product_place']));

    $deactivate_sql = mysqli_query($conn, "UPDATE warehouse_foil SET is_active = 0 WHERE item_id = '$item_id' AND place NOT IN ('" . implode("','", $places) . "') AND is_active = 1");

    $result_arr = [];

    foreach ($places as $place) {
        $sql = mysqli_query($conn, "SELECT wid, left_db, right_db FROM warehouse_foil WHERE item_id = '$item_id' AND place = '$place' AND is_active = 1");
        $warehouse_foil = mysqli_fetch_array($sql);

        if ($warehouse_foil == null) {
            $sql = mysqli_query($conn, "SELECT wid FROM warehouse_foil WHERE is_active = 0 LIMIT 1");
            $inactive_foil = mysqli_fetch_array($sql);
            if ($inactive_foil != null) {
              $wid = $inactive_foil['wid'];
              $sql = mysqli_query($conn, "UPDATE warehouse_foil SET left_db = 0, right_db = 0, place = '$place', item_id = '$item_id', is_active = 1 WHERE wid = $wid");
            } else {
              $sql = mysqli_query($conn, "INSERT INTO warehouse_foil(item_id, place, right_db, left_db, is_active) VALUES ('$item_id', '$place', 0, 0, 1)");
              $wid = mysqli_insert_id($conn);
            }

            $left_db = 0;
            $right_db = 0;
        } else {
            $wid = $warehouse_foil['wid'];
            $left_db = $warehouse_foil['left_db'];
            $right_db = $warehouse_foil['right_db'];
        }

        $result_arr[] = [
            'wid' => $wid,
            'place' => $place,
            'left_db' => $left_db,
            'right_db' => $right_db
        ];
    }

    echo json_encode(["result" => "ok", "data" => $result_arr, "warehouse_editor" => UserHasPerm('warehouse_editor')]);
} else if (htmlspecialchars($_POST["func"]) == "EditFoilItem") {
    $left_db = intval($_POST["left"]);
    $right_db = intval($_POST["right"]);

    $reason = htmlspecialchars($_POST["reason"] ?? '');

    $result = array();
    $wid_list = [];

    if (isset($_POST["wid"])) {
      $wid = htmlspecialchars($_POST["wid"]);
      $wid_list = explode('/', $wid);
    } else {
      $item_id = htmlspecialchars(str_replace(' ', '+', $_POST['item_id']));
      $set_item_id = splitSetitem_id($item_id);
      if ($set_item_id != null) {

        $item1 = $set_item_id['item1'];
				$item2 = $set_item_id['item2'];

        $sql = mysqli_query($conn, "SELECT wid FROM warehouse_foil WHERE item_id = '$item1' LIMIT 1 AND is_active = 1");
        $wid_list[] = mysqli_fetch_array($sql)[0];

        $sql = mysqli_query($conn, "SELECT wid FROM warehouse_foil WHERE item_id = '$item2' LIMIT 1 AND is_active = 1");
        $wid_list[] = mysqli_fetch_array($sql)[0];

      } else {
        $sql = mysqli_query($conn, "SELECT wid FROM warehouse_foil WHERE item_id = '$item_id' LIMIT 1 AND is_active = 1");
        $wid_list[] = mysqli_fetch_array($sql)[0];
      }
    }

    for ($i=0; $i < count($wid_list); $i++) {
      $TempWID = $wid_list[$i];

      $sql = mysqli_query($conn,"SELECT * FROM warehouse_foil WHERE wid = '$TempWID' AND is_active = 1");
      $warehouse_sql_foil = mysqli_fetch_array($sql);
      $inWarehouse = max($warehouse_sql_foil['left_db'], $warehouse_sql_foil['right_db']);
      if ($warehouse_sql_foil == null) {
        echo json_encode(['result'=>'error','reset'=>'true','message'=>'Érvénytelen raktár azonosító'], JSON_UNESCAPED_UNICODE);
        exit;
      } else {
        $sql = mysqli_query($conn,"UPDATE warehouse_foil SET left_db = CASE WHEN left_db + $left_db < 0 THEN 0 ELSE left_db + $left_db END, right_db = CASE WHEN right_db + $right_db < 0 THEN 0 ELSE right_db + $right_db END WHERE wid = '$TempWID'");

        $loggerclass->writeLogWarehouse(['reason' => 'Fóliás mennyiség szerkesztése', 'reason_code' => 1,
            'item_id' => $warehouse_sql_foil['item_id'],
            'from_place' => $reason,
            'to_place' => $warehouse_sql_foil['place'],
            'amount_left' => $left_db,
            'amount_right' => $right_db
          ]);
      }
    }

    $TempWID = $wid_list[0];
    $sql = mysqli_query($conn, "SELECT item_id FROM warehouse_foil WHERE wid = '$TempWID'");
    $warehouse_foil = mysqli_fetch_array($sql);

    $result['result'] = "ok";
    $result['item_id'] = $warehouse_foil["item_id"];

    if ($reason != null && $reason != "" ) {
      $reasonData = explode("#", $reason);

      if ($reasonData[0] == "Production") {
        $validCategories = [
          'classic' => 'production_classic',
          'injmold' => 'production_injmold',
          'sporty'  => 'production_sporty',
          'boxing'  => 'production_boxing'
        ];

        if (!array_key_exists($reasonData[1], $validCategories)) {
          $result['result'] = "A termék elhelyezve a raktárban, de az indoklás nem került elmentésre!";
        } else {
          $table = $validCategories[$reasonData[1]];
          $pr_id = htmlspecialchars($reasonData[2]);

          $sql = mysqli_query($conn, "SELECT db_revenue_bulk_r, db_revenue_bulk_l FROM $table WHERE pr_id = $pr_id");
          $db_revenue = mysqli_fetch_array($sql);
          if ($db_revenue != null) {
            $new_db_revenue_bulk_r = intval($right_db) + intval($db_revenue['db_revenue_bulk_r']);
            $new_db_revenue_bulk_l = intval($left_db) + intval($db_revenue['db_revenue_bulk_l']);
            $sql = mysqli_query($conn, "UPDATE $table SET db_revenue_bulk_r = $new_db_revenue_bulk_r, db_revenue_bulk_l = $new_db_revenue_bulk_l WHERE pr_id = $pr_id");
          }
        }
      }

    }

    echo json_encode($result);

  } else if (htmlspecialchars($_POST["func"]) == "statistics") {
    $sql = "
    SELECT
        CASE
            WHEN SUBSTRING_INDEX(item_id, '+', 1) REGEXP '^[0-9]+$' THEN 'classic'
            WHEN SUBSTRING_INDEX(item_id, '+', 1) REGEXP '^CL[P|M]?[0-9]+$' THEN 'climair'
            WHEN SUBSTRING_INDEX(item_id, '+', 1) REGEXP '^FR[0-9]{4}$' THEN 'injmold'
            WHEN SUBSTRING_INDEX(item_id, '+', 1) REGEXP '^F[0-9]{4}$' THEN 'sporty'
            ELSE 'unknown'
        END AS category,
        SUM(CASE WHEN item_id LIKE '%+%' THEN amount * 2 ELSE amount END) AS amount
    FROM warehouse
    GROUP BY category
    UNION ALL
    SELECT 'all' AS category, SUM(CASE WHEN item_id LIKE '%+%' THEN amount * 2 ELSE amount END) AS amount
    FROM warehouse;
    ";
    $db_box = $conn->query($sql);
    $box_arr = [];
    if ($db_box) {
      while ($row = $db_box->fetch_assoc()) {
        $box_arr[$row["category"]] = [
          "category" => $row["category"],
          "amount" => $row["amount"]
        ];
      }
    }

    $sql = "
    SELECT
        CASE
            WHEN item_id  REGEXP '^[0-9]+$' THEN 'classic'
            WHEN item_id  REGEXP '^FR[0-9]{4}$' THEN 'injmold'
            WHEN item_id  REGEXP '^F[0-9]{4}$' THEN 'sporty'
            ELSE 'unknown'
        END AS category,
        SUM(right_db) AS right_db,
    	SUM(left_db) AS left_db
    FROM warehouse_foil WHERE is_active = 1
    GROUP BY category
    UNION ALL
    SELECT 'all' AS category, SUM(right_db) AS right_db, SUM(left_db) AS left_db
    FROM warehouse_foil WHERE is_active = 1;
    ";
    $db_foil = $conn->query($sql);
    $foil_arr = [];
    if ($db_foil) {
      while ($row = $db_foil->fetch_assoc()) {
        $foil_arr[$row["category"]] = [
          "category" => $row["category"],
          "right_db" => $row["right_db"],
          "left_db" => $row["left_db"]
        ];
      }
    }

    $all_arr['classic'] = [
      'amount' => ($box_arr['classic']['amount'] ?? 0) + min($foil_arr['classic']['right_db'] ?? 0, $foil_arr['classic']['left_db'] ?? 0),
      'category' => 'classic'
    ];
    $all_arr['climair'] = [
      'amount' => $box_arr['climair']['amount'] ?? 0,
      'category' => 'climair'
    ];
    $all_arr['injmold'] = [
      'amount' => ($box_arr['injmold']['amount'] ?? 0) + min($foil_arr['injmold']['right_db'] ?? 0, $foil_arr['injmold']['left_db'] ?? 0),
      'category' => 'injmold'
    ];
    $all_arr['sporty'] = [
      'amount' => ($box_arr['sporty']['amount'] ?? 0) + min($foil_arr['sporty']['right_db'] ?? 0, $foil_arr['sporty']['left_db'] ?? 0),
      'category' => 'sporty'
    ];


    $shortage = [];
    $sql = "
    SELECT
        CASE
            WHEN SUBSTRING_INDEX(item_id, '+', 1) REGEXP '^[0-9]+$' THEN 'classic'
            WHEN SUBSTRING_INDEX(item_id, '+', 1) REGEXP '^CL[P|M]?[0-9]+[A-Z]?$' THEN 'climair'
            WHEN SUBSTRING_INDEX(item_id, '+', 1) REGEXP '^FR[0-9]{4}$' THEN 'injmold'
            WHEN SUBSTRING_INDEX(item_id, '+', 1) REGEXP '^F[0-9]{4}$' THEN 'sporty'
            ELSE 'unknown'
        END AS category,
        SUM(CASE WHEN free_stock = 0 THEN 1 ELSE 0 END) AS nullas_db,
        SUM(CASE WHEN free_stock < 0 THEN 1 ELSE 0 END) AS negatv_db
    FROM statistics_daily
    GROUP BY category
    UNION ALL
    SELECT 'all' AS category, SUM(CASE WHEN free_stock = 0 THEN 1 ELSE 0 END), SUM(CASE WHEN free_stock < 0 THEN 1 ELSE 0 END)
    FROM statistics_daily;
    ";
    $db_shortage = $conn->query($sql);
    if ($db_shortage) {
      while ($row = $db_shortage->fetch_assoc()) {
        $shortage[$row["category"]] = [
          'zero' => intval($row['nullas_db']),
          'neg' => intval($row['negatv_db']),
          'category' => $row["category"]
        ];
      }
    }

    echo json_encode([
      "result" => "ok",
      "box" => $box_arr,
      "foil" => $foil_arr,
      "all" => $all_arr,
      "shortage" => $shortage,
    ]);

  } else if (htmlspecialchars($_POST["func"]) == "EditFoilWarehouse") {
    $wid = htmlspecialchars($_POST["wid"] ?? '');
    $new_place = htmlspecialchars($_POST["new_place"] ?? '');

    if ($new_place == "") {
      echo json_encode(array('result' => 'Kötelező megadni egy raktárhelyet!'));
      exit();
    }

    $item_id = "";
    $old_place = "";

    $right_db = 0;
    $left_db = 0;

    $sql = mysqli_query($conn,"SELECT item_id, place, right_db, left_db FROM warehouse_foil WHERE wid = '$wid'");
    $data = mysqli_fetch_array($sql);
    if ($data != null) {
      $item_id = $data['item_id'];
      $old_place = $data['place'];
      $right_db = $data['right_db'];
      $left_db = $data['left_db'];
    } else {
      echo json_encode(array('result' => 'Hiibás raktár azonosító!'));
      exit();
    }

    $foil_product_place = "";

    $sql = mysqli_query($conn,"SELECT foil_product_place FROM pr_warehouse_parameters WHERE item_id = '$item_id'");
    $data = mysqli_fetch_array($sql);
    if ($data != null) {
      $foil_product_place = $data['foil_product_place'];
    } else {
      echo json_encode(array('result' => 'Hiibás cikkszám bejegyzés!'));
      exit();
    }

    $foil_product_place = str_replace($old_place, $new_place, $foil_product_place);

    mysqli_query($conn,"UPDATE pr_warehouse_parameters SET foil_product_place='$foil_product_place' WHERE item_id = '$item_id'");
    mysqli_query($conn,"UPDATE warehouse_foil SET place='$new_place' WHERE wid = '$wid'");

    $loggerclass->writeLogWarehouse(['reason' => 'Fóliás raktárhely szerkesztése', 'reason_code' => 2,
        'item_id' => $item_id,
        'from_place' => $old_place,
        'to_place' => $new_place,
        'amount_left' => $left_db,
        'amount_right' => $right_db
      ]);

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

  } else if (htmlspecialchars($_POST["func"]) == "MoveBox") {
    $wh_id = htmlspecialchars($_POST["wh_id"] ?? '');
    $wh_id_new = htmlspecialchars($_POST["wh_id_new"] ?? '');

    $amount = intval($_POST["amount"] ?? 0);
    $item_id = htmlspecialchars(str_replace(' ', '+', $_POST['item_id']));

    /* -- Jog Ellenőrzés -- */
    if (!UserHasPerm("box_stock_taking")) {
      echo json_encode(array(
        'result' => 'Önnek nincsen joga a művelethez!'
      ));
      exit();
    }

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


    /* -- Raktárhely feldolgozás -- */

    /* Eredeti raktárhely */
    $warehouse_id_old = null;
    $position_old = null;

    $position = substr($wh_id, -3);
    $wcode = substr($wh_id, 0, strlen($wh_id) - 3);

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

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

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

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

      if ($warehouse_box == null) {
        echo json_encode(array(
          'result' => 'A cikkszám nem található meg ezen a raktárazonosítón!'
        ));
        exit();
      } else if ($warehouse_box['amount'] < $amount) {
        echo json_encode(array(
          'result' => 'Nincs elegendő cikkszám a forrás polcon!'
        ));
        exit();
      }
    } else {
      echo json_encode(array(
        'result' => 'Nem létező raktár azonosítót adott meg forrásnak!'
      ));
      exit();
    }

    /* Új raktárhely */
    $warehouse_id_new = null;
    $position_new = null;

    $position = substr($wh_id_new, -3);
    $wcode = substr($wh_id_new, 0, strlen($wh_id_new) - 3);

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

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

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

    } else {
      echo json_encode(array(
        'result' => 'Nem létező raktár azonosítót adott meg célhelynek!'
      ));
      exit();
    }

    /* -- Return -- */
    echo json_encode(array(
      'result' => 'ok',
      'position_old' => $position_old,
      'wid_old' => $warehouse_id_old,
      'position_new' => $position_new,
      'wid_new' => $warehouse_id_new,
      'code_old' =>  $wh_id,
      'item_id' => $item_id,
      'amount' => $amount
    ));

    $loggerclass->writeLogWarehouse(['reason' => 'Doboz áthelyezése', 'reason_code' => 1,
        'item_id' => $item_id,
        'from_place' => $position_old,
        'to_place' => $position_new,
        'amount_left' => $amount,
        'amount_right' => $amount
      ]);

  }


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

  $jsonString = file_get_contents('../managers/prdb.json');
  $data = json_decode($jsonString, true);
  header('Content-Type: application/json; charset=utf-8');
  echo json_encode($data['BoxSizes']);

  exit();
}

$WarehouseLocSelect = '<option value="">-- Bármely --</option>';
$query = "SELECT DISTINCT location FROM warehouse_structure ORDER BY location ASC";
if ($result = $conn->query($query)) {
  while ($warehouse = $result->fetch_assoc()) {
    $WarehouseLocSelect = $WarehouseLocSelect.'<option value="'.$warehouse["location"].'">'.$warehouse["location"].'</option>';
  }
}

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

?>

<!DOCTYPE html>
<html lang="hu" dir="ltr">
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="../css/panel.css">
    <script src="../js/feather-icons.js"></script>
    <title>Kezelőfelület</title>
  </head>
  <style>
    .warehouse {
      display: flex;
      flex-direction: column;
      gap: 5px;
      padding: 10px;
      background-color: #f4f4f4;
      width: fit-content;
      max-width: calc(70% - 50px);
      border-radius: 5px;
    }

    .shelf-row {
      display: flex;
      flex-direction: row;
      gap: 5px;
    }

    .shelf-cell {
      overflow: hidden;
      width: 45px;
      height: 40px;
      background-color: #c2c2c2;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
    }
    .shelf-cell:hover {
      background: var(--panelcolor) !important;
      opacity: 0.7;
      transition: 0.2s;
    }
    .shelf-cell:active {
      opacity: 1;
      transition: 0.05s;
    }

    .number {
      color: #c2c2c2;
      background-color: #ffffff;
      cursor: default;
    }
    .number:hover {
      background: #ffffff !important;
      opacity: 1 !important;
    }

    .number-corner {
      background-color: transparent;
      cursor: default;
    }
    .number-corner:hover {
      background: transparent !important;
      opacity: 1 !important;
    }

    .panelloader {
      position: absolute;
      right: 15px;
      width: 23%;
      top: 130px;
      display: flex;
    }
    .panelloader .overlay {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(51, 51, 51, 0.3);
      display: none;
      justify-content: center;
      align-items: center;
      pointer-events: none;
      z-index: 10;
      border-radius: 5px;
    }
    .panelloader.active .overlay {
      display: flex;
      pointer-events: all;
      animation: fadeIn 0.2s ease-in-out;
    }
    .panelloader.active .overlay::before {
      content: "";
      width: 30px;
      height: 30px;
      border: 4px solid var(--panelcolor);
      border-top: 4px solid transparent;
      border-radius: 50%;
      animation: spin 1s linear infinite;
    }
    @keyframes fadeIn {
      from { opacity: 0; }
      to { opacity: 1; }
    }

    @keyframes spin {
      to { transform: rotate(360deg); }
    }
    li::marker {
      color: #333;
    }
    input:disabled {
      color: #333333;
      cursor: not-allowed;
    }
    .plusbtn {
      width: 50px;
      border-radius: 12px;
      font-weight: bold;
      background: #3bb143 !important;
    }
    .minusbtn {
      width: 50px;
      border-radius: 12px;
      font-weight: bold;
      background: #e3242b !important;
    }
    .OpenLocBox {
      width: 200px;
      height: 90px;
      cursor: pointer;
    }
    .OpenLocBox:hover {
      transition: 0.2s;
      box-shadow: 3px 3px 3px rgb(0 0 0 / 0.2);
      transform: translateY(-3px);
    }

    .InfoBox .panel {
      transition: all 0.2s ease;
      overflow: hidden;
      padding-left: 15px;
      padding-right: 15px;
    }

    .InfoBox .panel-header {
      transition: 0.2s;
      text-align: center;
      font-size: 23px;
      font-weight: bold;
    }

    .InfoBox .panel-content {
      transition: max-height 0.2s ease, opacity 0.2s ease;
      overflow: hidden;
    }

    .InfoBox .panel-expanded .panel-content {
      opacity: 1;
    }

  </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 -->

      <input type="hidden" id="current_warehouse_id" value="">
      <h1 id="page_title">Raktárak</h1>

      <div style="position: absolute; float: right; top: 65px; right: 15px;">
        <?php
        if (UserHasPerm("box_stock_taking")) {
          echo '<a title="Doboz áthelyezés" style="margin-right: 15px;" onclick="MoveBoxApp()"><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAACXBIWXMAAAsTAAALEwEAmpwYAAACMUlEQVR4nO2Yv08UQRTHJxTqX0BBhUoBimBHTa2VcW283N511FQiR6iIJJLQUwr+aE5vNuYuVIC3b9aExuzde6cWmqgoFdFSC8fM7NxF4SJyMce+ZD/JN9nbTd7M53ZndnaEyMjIyMjI6IEPDwV8fCR0n1IX/5s+dl6bHNuhQCEEirQE/CaBnpTh1SAvAcDQCLQjAbdZCbR5FrWGpaIDI/G8/uaC4CZgCIBqRqACdE1wFJAK15JHCWd4CgAtWAGgJZ4Cinw3mNdZClTC1vRxM1GqBaRqjiSPEL5jKVCtvj0rAX8GQD8WtR5gJ2AIgPbtVBq2hgRLAYW7ViDCqW7XwxWh+xlxYgHAsh3ICj2uAqt2IEc0y1Mgolk3E62yFJAKPSdQZilQiXDKrYd2eQqErSG3HtpnKbCo9UAA9N280La23p9jJ2AwS4lkKm2OCI4CEnDbvY2nWQoEitaTO0A+TwGgpWRZTQs8BRTOuOXE2hGB+6Ler87XV8SLngTMR72bSmvm9+QdhKtzpCc7wSR3UU90yRWb5h8Znz+chr7cJZdMSu3ENmOlWI+W4n/fpXsaNi66MXAgX74+bzp/2gJjpfiEWyyKdtqbXSwFHmzC4EZNPd6owtfry41TFxidj3sbD4e57ReXc35R/x5zLu21O+T8wmdT+MbNWza2kXzxi0h57Q65fGHvSCN+8ZNIee2/3uZcvnBPpLx2B8/zztiGzL+VL+yZY3NOpLx2RkaGSBe/ANpDs+M4gJJKAAAAAElFTkSuQmCC" alt="move-by-trolley"></a>';
        }
        ?>

        <a title="Statisztika" style="margin-right: 15px;" onclick="Statistics()"><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAACXBIWXMAAAsTAAALEwEAmpwYAAAECklEQVR4nO2Yy0/UQBzHuyzC7pKoEbaJ3o0Jd6/yHyjp6kHey/stL+XgRWM8kNYAZ2+KCO4CCspDkPfyRsWTiF4wclEjGKMXkzHTdrrt7vzaDrKAZn/J9zYbPp/pb37TwnHxile84vXfFi+IIV4QZ7h/tXifhHD2/y83r4W45jconDXEXcN5jRw4V1+peYkcTTiryNG0ghyNKyihcVlJw5KaRZRQj7OAEuoWkLNuHjnr5pDzCk5ISe2smhmUWIMzraR6CiVWT8pxVo0zPEkm8FVr8HoCPg+CO6PAVfiqCTXjDE8Sw6vgnAW4Bg+AJxBww67bAZ/UwI9U4rxgENgP8FodeA0NfEIDl1MxZl/AHvgyA3jIGrxaB15lBFcyyiJgB3yJAXzWAJ6xvIMyt5Ah5xa3VXACHwaXU/6cQcAW+CID+IxhxyPhM9UYdz0MniRnhEEgRuCkVUCBCjp4UhnOsH2BqJFYvzeznPQ4LDBKBZdTOsQgsMtZTsDTe7fQ2akdQ9J7Pmk9DgkkAeBKBlkEzCZLyHKWR8KTkB4HBcro4Eklgyi55BmDwG5mue4SAgXUkQgLDFPB5RQ/ZRD4y1kOC+AeH4UFSungSgbsC1jN8rT2DXTy7qYhaW3vtEsIFFAPKChQQgdPLsLpZxAwuYTwjkfCk5BLCBIgBxQSSAbAcVyFTxgELGY5LKBcQqCAekBBgWI6uJLHLALmsxwUUC8iUEA9oLDAABXc5cfpsy9gdgnhHgcFykflHocFcI8PwgJF/chVpAOX4fuUFPQyCAAfFKTHIQHS45AAOaCQgIsG7u9FroIeOQwC9A8K0uNpbevRU6j1rdbj6cGP0TdxYFM7oBkLX6PgM+a+UMAVeHdBELnzgwwCwAeF9rJVrntnkW/PEctLKPqAAq3i14P3yODu/IAc2wKGD4rKvQbvZwAPKvB5j+TYFwA+KOY+fEOxrtD65yhwd143cud2MwgA7+WzG7EXmMUCeQEDuCe3Sw6DgPl7OWmXZK1dzFrFOMvNWyUQ3nUduCfnoRzbArsC119CRX8L3m0A9+R0Ik92J4OAxXt5+IAawc0nizLLzcDdALgn+4EcBgG7k8UOuHGWk5FIB++ignuyOlBKVgeDQOnQTKxmeeRk8UT0OQ08Jes+8ly+N83FqrzCHR/5TzTvk95zHHLQ1vE+cZ2s8/pEgTssxQtSjw7sBrTO65NuhkXFIHcY6kR2+1GvIP4kYKmXWs5Aa9OEltOaqCD9Onah9fj+0tKgfFKhtquCuGy1nhekFU3ioujnDrq8gjima4t6q/W8IDWEn4I4xh10eQXph7r7v1PPt5yyWo/X4LWqxHfuoMsriLcxiNcn3bL7G16QrvOCtM3ym3jFK14ctf4Ag4Cuu9EcaaIAAAAASUVORK5CYII=" alt="marketing"></a>

        <a title="Raktárhely cimke generátor" style="margin-right: 15px;" target="_blank" href="./labelmaker"><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAACXBIWXMAAAsTAAALEwEAmpwYAAABrklEQVR4nO2YTUrDQBTHZ+MqJ/AAQ4zXsNKkbXDahbhw57YpLlxMtnGvC8GKXdSVHsKFIHgJwY82Nn5U8AhPGhMp06Sx1Ekz+v7wg2mG5r1f+shACZkh9WeosgCeWAAgg40AfBaARWQlKgCS6UsTiItovANLu0chmtv5dQkiWyBuPiZJbFa0sQexOAFXEQHNVXyEmGQICqRk+fQR8oDIivICTPURYn9FQIsOrPgVOvqctE7aE1+/mnCvXATEQyxtnbaXdo2hACGkxb1Kk3u+wz0QEU/i7zFwO4nrpL2JEXInRyip9ldP+2amQFrz4wKycVLqN7nXyxQQv1Su1UHXdaCU5iZAKQ1rjmqL/cwssGIY4Q1H5HWQ0aieYazOLzD+C+QpoOs6mHZjfoGiQVCAowCgwLQsukEHBfjim3RQgBcXggIcBWAa7bML6AcvcO8P4PCkq5ZAy/Vg8DqEzZsPaFwN4fahp6bA9vU7bF2+qSfgcA+Ou+fhCN35AzhoKzZCzg/IFNhp7kGRIVkpWba/btlQSEw7+1+JtYptlqxav4jNl8rVcqYABoPBYP5VPgESqq4jShUL5QAAAABJRU5ErkJggg==" alt="label-printer"></a>
      </div>

      <div id="warehouse" class="warehouse"></div>
      <div id="box_div"></div>
      <br clear="all"><br clear="all">
      <div id="searcher">
        <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);">Raktár kereső</p>

        <div style="width: 100%; min-height: 85px; margin-left: 10px;">
          <div style="display: inline; float: left;">
            <p>Cikkszám: </p>
            <input type="text" id="search-item_id" placeholder="Cikkszám..." onkeydown="if (event.keyCode == 13) {SearchInWarehouse();}" autocomplete="off" style="width: 147px; height: 17px;">
          </div><div style="display: inline; float: left; padding-left: 15px;">
            <p>Raktárhely: </p>
            <input type="text" id="search-location" placeholder="Raktárhely..." onkeydown="if (event.keyCode == 13) {SearchInWarehouse();}" autocomplete="off" style="width: 147px; height: 17px;">
          </div><div style="display: inline; float: left; padding-left: 15px;">
            <p>Oldalanként: </p>
            <select id="search-perpage" onchange="SearchInWarehouse();"><?php echo $perpageselect;?></select>
          </div><div style="display: inline; float: left; padding-left: 15px;">
            <p style="color: #f5f5f5;">: </p>
            <button class="Feedback" id="search-button" style="width: 70px;" onclick="SearchInWarehouse();">
              <span class="button-text">Keresés</span>
              <div class="loader"></div>
              <div class="checkmark">&#10004;</div>
              <div class="crossmark">&#10006;</div>
            </button>
          </div>
        </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="search_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_amount" onclick="orderby_filter('amount');" style="cursor: pointer;">Mennyiség</th>
                  <th id="table_head_location" onclick="orderby_filter('location');" style="cursor: pointer;">Raktárhely</th>
                  <th id="table_head_name" onclick="orderby_filter('name');" style="cursor: pointer;">Szektor</th>
                  <th>Link</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>
      <div id="log_div">
        <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);">Raktártartalom</p>
        <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>Cikkszám</th>
                  <th>Mennyiség</th>
                  <th>Helye <small style="opacity: 0.6;"><small>(Sor:Oszlop)</small></small></th>
                </tr>
              </thead>
              <tbody>
              </tbody>
            </table>
          </div>
        </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;

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

    var currentCapacity = 0;
    var currentSize = '';
    var currentEditable = false;
    var currentDisable = 'disabled';
    var currentStatus = '';
    var currentWarehouseCapacity = 0;
    var currentLoc = '';
    let WarehouseSizeJSON = null;
    var currentFullness = 0;
    var orderby = '!item_id';
    var currentCode = '';

    function HideAllDiv() {
      document.getElementById('box_div').style.visibility = "invisible";
      document.getElementById('box_div').style.display = "none";
      document.getElementById('box_div').innerHTML = "";

      document.getElementById('warehouse').style.visibility = "invisible";
      document.getElementById('warehouse').style.display = "none";
      document.getElementById('warehouse').innerHTML = "";

      document.getElementById('log_div').style.visibility = "invisible";
      document.getElementById('log_div').style.display = "none";

      document.getElementById('searcher').style.visibility = "invisible";
      document.getElementById('searcher').style.display = "none";

      winapp.innerHTML = "";
      closewin();
      currentCapacity = 0;
      currentWarehouseCapacity = 0;
      currentSize = '';
      currentEditable = false;
      currentDisable = 'disabled';
      WarehouseSizeJSON = null;
      currentStatus = '';
      currentLoc = '';
      currentFullness = 0;
      document.getElementById("current_warehouse_id").value = "";
    }

    /* Kereső */
    function SearchInWarehouse() {
      document.getElementById('cpage').innerHTML = '1';
      LoadSearchTable();
    }
    function left() {
      var cpage = document.getElementById("cpage").innerHTML;
      if ((parseInt(cpage) - 1) >= 1) {
        document.getElementById("cpage").innerHTML = parseInt(cpage) - 1;
        LoadSearchTable();
      }
    }
    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;
        LoadSearchTable();
      }
    }
    function orderby_filter(by = 'item_id') {
      if (orderby.slice(1) == by && orderby[0] === '!') {
        orderby = by;
      } else if (orderby == by) {
        orderby = '!' + by;
      } else {
        orderby = by;
      }

      document.getElementById('cpage').innerHTML = '1';

      document.getElementById('table_head_item_id').innerHTML = "Cikkszám";
      document.getElementById('table_head_amount').innerHTML = "Mennyiség";
      document.getElementById('table_head_location').innerHTML = "Raktárhely";
      document.getElementById('table_head_name').innerHTML = "Szektor";

      if (orderby == "!amount") {
        document.getElementById('table_head_amount').innerHTML = "Mennyiség <small><small style='opacity: 0.6;'>321</small></small>";
      } else if (orderby == "!location") {
        document.getElementById('table_head_location').innerHTML = "Raktárhely <small><small style='opacity: 0.6;'>cba</small></small>";
      } else if (orderby == "!name") {
        document.getElementById('table_head_name').innerHTML = "Szektor <small><small style='opacity: 0.6;'>cba</small></small>";
      } else if (orderby == "!item_id") {
        document.getElementById('table_head_item_id').innerHTML = "Cikkszám <small><small style='opacity: 0.6;'>cba</small></small>";
      } else if (orderby == "amount") {
        document.getElementById('table_head_amount').innerHTML = "Mennyiség <small><small style='opacity: 0.6;'>123</small></small>";
      } else if (orderby == "location") {
        document.getElementById('table_head_location').innerHTML = "Raktárhely <small><small style='opacity: 0.6;'>abc</small></small>";
      } else if (orderby == "name") {
        document.getElementById('table_head_name').innerHTML = "Szektor <small><small style='opacity: 0.6;'>abc</small></small>";
      } else {
        document.getElementById('table_head_item_id').innerHTML = "Cikkszám <small><small style='opacity: 0.6;'>abc</small></small>";
      }

      LoadSearchTable();
    }
    function LoadSearchTable() {
      FeedbackButtonStatus("loading", "search-button");

      var item_id = document.getElementById("search-item_id").value;
      var location = document.getElementById("search-location").value;
      var perpage = document.getElementById("search-perpage").value;
      var cpage = document.getElementById("cpage").innerHTML;

      const body = 'func=search&perpage=' + perpage + '&cpage=' + cpage + '&orderby=' + orderby + '&location=' + encodeURIComponent(location).replace(/%20/g, '+') + '&item_id=' + encodeURIComponent(item_id).replace(/%20/g, '+');
      get_POST_information("warehouse.php", body, function(text) {
        let response = JSON.parse(text);
        if (response.result == "ok") {
          FeedbackButtonStatus("complete", "search-button");
          var table = document.getElementById('search_table').getElementsByTagName('tbody')[0];
          table.innerHTML = "";
          document.getElementById("cpage").innerHTML = response.cpage;
          document.getElementById("maxpage").innerHTML = response.maxpage;

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

              var newRow = table.insertRow();
              var newCell_1 = newRow.insertCell(0);
              var newCell_2 = newRow.insertCell(1);
              var newCell_3 = newRow.insertCell(2);
              var newCell_4 = newRow.insertCell(3);
              var newCell_5 = newRow.insertCell(4);

              newCell_1.innerHTML = datas[0];
              newCell_2.innerHTML = datas[1];
              newCell_3.innerHTML = datas[2];
              newCell_4.innerHTML = datas[3];
              if (datas[4] != 'foil') {
                newCell_5.innerHTML = '<a style="cursor: pointer;" onclick="navigateTo(\''+ datas[4] +'\', () => OpenWarehouse(\'' + datas[4] + '\'))">Ugrás oda</button>';
              } else {
                newCell_5.innerHTML = '<span style="opacity: 0.8;"> - </span>';
              }
            }
          }
        } else {
          FeedbackButtonStatus("failed", "search-button");
          GenerateAlerts("error", response.result);
        }
      }, function() {
        FeedbackButtonStatus("failed", "search-button");
        GenerateAlerts("error", "Hálózati hiba!");
      });
    }

    /* Dobozos raktár */
    function ShowWarehouseLocation() {
      HideAllDiv();
      document.getElementById('box_div').style.visibility = "visible";
      document.getElementById('box_div').style.display = "unset";
      document.getElementById('page_title').innerHTML = "Raktárak <?php if (UserHasPerm("warehouse_editor")) { echo "<span style='opacity:0.8; cursor: pointer; color: var(--panelcolor); font-weight: normal;' onclick='CreateWarehouse();'>+</span>";}  ?>";
      Loading();
      const body = 'func=ShowWarehouseLocation';
      get_POST_information("warehouse.php", body, function(text) {
        Loading(false);
        let response = JSON.parse(text);
        if (response.result == "ok") {
          var location_div = document.getElementById('box_div');
          location_div.innerHTML = "";
          var tableresponse = response.loc;
          var code = response.code;
          var capacity = response.capacity;
          var amount = response.amount;
          if (tableresponse != "") {
            if (tableresponse.includes("|%|")) {
              var tablearr = tableresponse.split("|%|");
              var codearr = code.split("|%|");
              var capacityarr = capacity.split("|%|");
              var amountarr = amount.split("|%|");
            } else {
              var tablearr = [tableresponse];
              var codearr = [code];
              var capacityarr = [capacity];
              var amountarr = [amount];
            }
            for (var i = 0; i < tablearr.length; i++) {
              const percent = (parseInt(amountarr[i]) / parseInt(capacityarr[i]) * 100 ).toFixed(2)

              location_div.innerHTML += `
              <div class="box" style="width: 300px; height: 170px;">
                <h1 style="margin-bottom: 0px; margin-top: 1px; font-size: 26px;">${tablearr[i]}</h1>
                <p style="margin-top: 0px;"><b>${codearr[i]}</b> - Raktárhely</p>
                <p title="Raktár töltöttség" style="cursor: help; position: absolute; float: right; right: 15px; bottom: 15px; opacity: 0.8; margin: 0px; font-size: 14px;">${amountarr[i]} / ${capacityarr[i]} <span style="opacity:0.6;">doboz</span> <span style="margin-left: 15px">${percent} %</span></p>
                <button style="position: absolute; bottom: 15px;" onclick="navigateTo('${tablearr[i]}', () => OpenLoc('${tablearr[i]}'))">Megnyitás</button>
              </div>`;
            }
          }
          location_div.innerHTML += '<div class="boxpc" style="width: 300px; height: 170px;"><h1 style="margin-bottom: 0px; margin-top: 1px; font-size: 26px;">Fóliás raktár</h1><p style="margin-top: 0px;">Raktárhely</p><button style="position: absolute; bottom: 15px;" onclick="OpenFoilWarehouse();">Megnyitás</button></div>';

          document.getElementById('searcher').style.visibility = "visible";
          document.getElementById('searcher').style.display = "unset";

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

    function OpenLoc(LocationName) {
      HideAllDiv();
      document.getElementById('box_div').style.visibility = "visible";
      document.getElementById('box_div').style.display = "unset";
      document.getElementById('page_title').innerHTML = "<span style='opacity:0.8; cursor: pointer;' onclick='navigateTo(\"\", ShowWarehouseLocation)'>Raktárak</span> / "+LocationName+" <?php if (UserHasPerm("warehouse_editor")) { echo "<span style='opacity:0.8; cursor: pointer; color: var(--panelcolor); font-weight: normal;' onclick='CreateWarehouse();'>+</span>";}?>";
      Loading();
      const body = 'func=OpenLoc&location='+encodeURIComponent(LocationName).replace(/%20/g, '+');
      get_POST_information("warehouse.php", body, function(text) {
        Loading(false);
        let response = JSON.parse(text);
        if (response.result == "ok") {
          currentLoc = LocationName;
          var location_div = document.getElementById('box_div');
          location_div.innerHTML = "";
          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 arr = tablearr[i].split("|");
              if (arr[2] == "1") {
                location_div.innerHTML += '<div class="box OpenLocBox" onclick="navigateTo(\''+ arr[1] +'\', () => OpenWarehouse(\'' + arr[1] + '\'))"><h1 style="margin-bottom: 0px; margin-top: 1px; font-size: 26px;">'+arr[0]+'</h1><p style="margin-top: 0px;"><b>'+arr[3]+'</b> - Szektor</p></div>';
              } else {
                location_div.innerHTML += '<div class="box OpenLocBox" onclick="navigateTo(\''+ arr[1] +'\', () => OpenWarehouse(\'' + arr[1] + '\'))"><h1 style="margin-bottom: 0px; margin-top: 1px; font-size: 26px;">'+arr[0]+'</h1><p style="margin-top: 0px;"><b>'+arr[3]+'</b> - Szektor - <i>Inaktív</i></p></div>';
              }
            }
          }

          document.getElementById('searcher').style.visibility = "visible";
          document.getElementById('searcher').style.display = "unset";

        } else {
          GenerateAlerts("error", response.result);
        }
      }, function() {
        Loading(false);
        GenerateAlerts("error", "Hálózati hiba!");
      });
    }
    function OpenWarehouse(warehouse_id) {
      HideAllDiv();
      Loading();
      const body = 'func=OpenWarehouse&id='+warehouse_id;
      get_POST_information("warehouse.php", body, function(text) {
        Loading(false);
        let response = JSON.parse(text);
        if (response.result == "ok") {

          WarehouseSizeJSON = JSON.parse(decodeURIComponent(escape(atob(response.size))));

          document.getElementById('current_warehouse_id').value = warehouse_id;
          document.getElementById('page_title').innerHTML = "<span style='opacity:0.8; cursor: pointer;' onclick='navigateTo(\"\", ShowWarehouseLocation)'>Raktárak</span> / <span style='opacity:0.8; cursor: pointer;' onclick='navigateTo(\""+response.location+"\", () => OpenLoc(\""+response.location+"\"))'>"+response.location+"</span> / "+response.name;
          if (response.canedit) {
            document.getElementById('page_title').innerHTML += "<i data-feather='settings' style='display: inline-block; width: 20px; height: 20px; margin-left: 10px; cursor: pointer; color: var(--panelcolor);' onclick='EditWarehouse("+warehouse_id+");'></i>";
            feather.replace();
          }
          document.getElementById('warehouse').style.visibility = "visible";
          document.getElementById('warehouse').style.display = "flex";
          generateShelf(response.columns,response.row, "warehouse");

          document.getElementById('box_div').style.visibility = "visible";
          document.getElementById('box_div').style.display = "unset";

          if (response.status == "1") {currentStatus = "Aktív";} else {currentStatus = "Inaktív";}
          currentWarehouseCapacity = response.fullcapacity;
          currentCapacity = WarehouseSizeJSON['globalCapacity'];
          currentFullness = 0;
          currentSize = WarehouseSizeJSON['globalSize'];
          currentCode = response.code;

          if (response.canstatistic) {
            document.getElementById('log_div').style.visibility = "visible";
            document.getElementById('log_div').style.display = "unset";
          }


          var table = document.getElementById('table').getElementsByTagName('tbody')[0];
          table.innerHTML = "";

          var inwarehouse = response.inwarehouse;
          if (inwarehouse != "") {
            if (inwarehouse.includes("|%|")) {
              var tablearr = inwarehouse.split("|%|");
            } else {
              var tablearr = [inwarehouse];
            }
            for (var i = 0; i < tablearr.length; i++) {
            	var datas = tablearr[i].split("|");
            	currentFullness += parseInt(datas[2]);

            	var newRow = table.insertRow();
            	var newCell_1 = newRow.insertCell(0);
            	var newCell_2 = newRow.insertCell(1);
            	var newCell_3 = newRow.insertCell(2);

            	newCell_1.innerHTML = '<span style="color: #' + MD5(datas[0]).substring(0, 6) + '">♦</span> ' + datas[0] + '<span style="opacity: 0.6; font-size: 14px;">' + datas[3] + '</span>';
            	newCell_2.innerHTML = datas[2];
            	newCell_3.innerHTML = NumberToABC(datas[1].split(":")[0]) + ":" + padWithZero(datas[1].split(":")[1]);

              var CustomCapKey = (parseInt(datas[1].split(":")[1]) - 1) + ":" + (parseInt(datas[1].split(":")[0]) - 1);

              const capacityValue = (WarehouseSizeJSON['customCapacity']?.[CustomCapKey] !== undefined)
              	? WarehouseSizeJSON['customCapacity'][CustomCapKey]
              	: WarehouseSizeJSON['globalCapacity'];

            	const HexColor = '#' + MD5(datas[0]).substring(0, 6);
            	const percent = (datas[2] / capacityValue) * 100;

            	const elementId = warehouse_id + ':' + (parseInt(datas[1].split(":")[1]) - 1) + ':' + (parseInt(datas[1].split(":")[0]) - 1) + ':warehouse';
            	const el = document.getElementById(elementId);

            	const existingPercent = parseFloat(el.dataset.fill) || 0;
            	const existingColors = el.dataset.colors ? el.dataset.colors.split('|||') : [];
            	const existingPercents = el.dataset.percents ? el.dataset.percents.split('|||').map(p => parseFloat(p)) : [];

            	let background;
            	const percentTotal = existingPercent + percent;

            	if (existingPercent != 0) {
            		existingColors.push(HexColor);
            		existingPercents.push(percent);

            		let gradientStops = [];
            		let currentPosition = 0;

            		for (let j = 0; j < existingPercents.length; j++) {
            			gradientStops.push(`${existingColors[j]} ${currentPosition}%`);
            			gradientStops.push(`${existingColors[j]} ${currentPosition + existingPercents[j]}%`);
            			currentPosition += existingPercents[j];
            		}
            		gradientStops.push(`#c2c2c2 ${currentPosition}%`);
            		gradientStops.push(`#c2c2c2 100%`);

            		background = `linear-gradient(to top, ${gradientStops.join(', ')})`;

            		el.dataset.colors = existingColors.join('|||');
            		el.dataset.percents = existingPercents.join('|||');
            	} else {
            		background = `linear-gradient(to top,
            			${HexColor} 0%,
            			${HexColor} ${percent}%,
            			#c2c2c2 ${percent}%,
            			#c2c2c2 100%)`;

            		el.dataset.colors = HexColor;
            		el.dataset.percents = percent;
            	}

            	el.style.background = background;
            	el.dataset.fill = percentTotal;
            }

          }

          if (currentWarehouseCapacity == 0) {
            document.getElementById('box_div').innerHTML = '<div id="loader" class="panelloader"><div class="overlay"></div><div class="box" id="cellinfo" style="width: calc(100% - 43px);"><p style="font-weight: bold;">Jellemzők</p><p>Kapacitás: <span style="color: var(--panelcolor);">Ömlesztett</span></p><p>Állapot: <span style="color: var(--panelcolor);">'+currentStatus+'</span></p></div></div>';
          } else {
            document.getElementById('box_div').innerHTML = '<div id="loader" class="panelloader"><div class="overlay"></div><div class="box" id="cellinfo" style="width: calc(100% - 43px);"><p style="font-weight: bold;">Jellemzők</p><p>Kapacitás: <span style="color: var(--panelcolor);">'+currentFullness+' / '+currentWarehouseCapacity+' doboz <small style="float: right;">'+(parseInt(currentFullness) / parseInt(currentWarehouseCapacity) * 100 ).toFixed(2)+'%</small></span></p><p>Polconként: <span style="color: var(--panelcolor);">'+WarehouseSizeJSON['globalCapacity']+' doboz</span></p><p>Alapértelmezett méret: <span style="color: var(--panelcolor);">'+WarehouseSizeJSON['globalSize']+'</span></p><p>Állapot: <span style="color: var(--panelcolor);">'+currentStatus+'</span></p></div></div>';
          }

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

    var LocName = [];
    var CodeList = [];
    function CreateWarehouse(isedit = false) {
      openwin();
      wintitle.innerHTML = "Szektor létrehozása";
      winapp.innerHTML = '<div id="errorDIV"></div>';
      if (isedit) {winapp.innerHTML += '<h1>Szektor módosítása</h1>';} else {
        winapp.innerHTML += '<h1>Szektor létrehozása</h1>';
        winapp.innerHTML += '<p style="width: calc(100% - 35px); border-bottom: 1px solid #bdc3c7; display: inline-block; margin-right: 15px; ">Paraméterek</p>';

        var parameters = '<div style="display: inline; float: left; padding-left: 15px; margin-top: 10px;">';
        parameters += '<p class="label">Szektor elnevezése:</p>';
        parameters += '<input id="winapp_name" type="text" autocomplete="off" spellcheck="false" placeholder="Szektor elnevezése..." style="width: 150px;"><br>';

        parameters += '</div><div style="display: inline; float: left; padding-left: 15px; margin-top: 10px;">';
        parameters += '<p class="label">Raktár helye:</p>';
        parameters += '<input id="winapp_location" type="text" autocomplete="off" spellcheck="false" placeholder="Raktár helye..." style="width: 150px;" list="location_list" value="'+currentLoc+'" oninput="AutoWriteLoc(this.id)"><br>';

        parameters += '</div><div style="display: inline; float: left; padding-left: 15px; margin-top: 10px;">';
        parameters += '<p class="label">Raktár kódja:</p>';
        parameters += '<input id="winapp_code" type="text" autocomplete="off" spellcheck="false" placeholder="Raktár kódja..." style="width: 150px;" list="code_list" oninput="AutoWriteLoc(this.id)"><br>';

        parameters += '</div><div style="display: inline; float: left; padding-left: 15px; margin-top: 10px;">';
        parameters += '<p class="label">Oszlopok száma:</p>';
        parameters += '<input id="winapp_columns" type="number" min="1" autocomplete="off" spellcheck="false" placeholder="Oszlopok száma..." style="width: 150px;"><br>';

        parameters += '</div><div style="display: inline; float: left; padding-left: 15px; margin-top: 10px;">';
        parameters += '<p class="label">Sorok száma:</p>';
        parameters += '<input id="winapp_row" type="number" min="1" autocomplete="off" spellcheck="false" placeholder="Sorok száma..." style="width: 150px;"><br>';

        parameters += '</div><div style="display: inline; float: left; padding-left: 15px; margin-top: 10px;">';
        parameters += '<p class="label">Polconkénti maximum:</p>';
        parameters += '<input id="winapp_capacity" type="number" min="1" autocomplete="off" spellcheck="false" placeholder="Polconkénti maximum darabszám..." style="width: 150px;"><br>';

        winapp.innerHTML += parameters + "</div>";

        setTimeout(function() { AutoWriteLoc(); }, 300);

      }

      if (!isedit) {winapp.innerHTML += '<br clear="all"><br clear="all"><button onclick="SaveNewWarehouse();" style="margin-top: 10px;">Raktár létrehozása</button><br clear="all"><br clear="all">';}

      Loading();
      const body = 'func=ShowWarehouseLocation';
      get_POST_information("warehouse.php", body, function(text) {
        if (!isedit) {Loading(false);}
        let response = JSON.parse(text);
        if (response.result == "ok") {
          var tableresponse = response.loc;
          var code = response.code;
          if (tableresponse != "") {
            if (tableresponse.includes("|%|")) {
              var tablearr = tableresponse.split("|%|");
              var codearr = code.split("|%|");
            } else {
              var tablearr = [tableresponse];
              var codearr = [code];
            }
            LocName = tablearr;
            CodeList = codearr;

            var datalist = '<datalist id="location_list" role="listbox">';
            for (var i = 0; i < tablearr.length; i++) {
              datalist += '<option value="'+tablearr[i]+'">';
            }
            datalist += '</datalist>';
            winapp.innerHTML += datalist;

            var datalist = '<datalist id="code_list" role="listbox">';
            for (var i = 0; i < codearr.length; i++) {
              datalist += '<option value="'+codearr[i]+'">';
            }
            datalist += '</datalist>';
            winapp.innerHTML += datalist;
          }
        } else {
          GenerateAlerts("error", response.result);
        }
      }, function() {
        Loading(false);
        GenerateAlerts("error", "Hálózati hiba!");
      });

    }
    function SaveNewWarehouse() {
      Loading();
      var name = document.getElementById('winapp_name').value;
      var location = document.getElementById('winapp_location').value;
      var code = document.getElementById('winapp_code').value
      var row = document.getElementById('winapp_row').value;
      var columns = document.getElementById('winapp_columns').value;
      var capacity = document.getElementById('winapp_capacity').value;

      const body = 'func=SaveNewWarehouse&name=' + encodeURIComponent(name).replace(/%20/g, '+') + '&location=' + encodeURIComponent(location).replace(/%20/g, '+') + '&code=' + encodeURIComponent(code).replace(/%20/g, '+') + '&row=' + row + '&columns=' + columns + '&capacity=' + capacity;
      get_POST_information("warehouse.php", body, function(text) {
        Loading(false);
        let response = JSON.parse(text);
        if (response.result == "ok") {
          closewin();
          OpenWarehouse(response.wid);
        } else {
          GenerateAlerts("error", response.result);
        }
      }, function() {
        Loading(false);
        GenerateAlerts("error", "Hálózati hiba!");
      });
    }

    function AutoWriteLoc(CurrentEditParam = "") {
      var LocInput = document.getElementById("winapp_location");
      var CodeInput = document.getElementById("winapp_code");

      if (LocInput != null && CodeInput != null) {
        if (LocInput.value == "" && CodeList.indexOf(CodeInput.value) !== -1 && CurrentEditParam != "winapp_location") {
          LocInput.value = LocName[CodeList.indexOf(CodeInput.value)];
        } else if (CodeInput.value == "" && LocName.indexOf(LocInput.value) !== -1 && CurrentEditParam != "winapp_code") {
          CodeInput.value = CodeList[LocName.indexOf(LocInput.value)];
        }
      }
    }

    function EditWarehouse(warehouse_id) {
      fullscrn(true);
      CreateWarehouse(true);
      wintitle.innerHTML = "Szektor módosítása";

      const body = 'func=EditWarehouse&warehouse_id='+warehouse_id;
      get_POST_information("warehouse.php", body, function(text) {
        Loading(false);
        let response = JSON.parse(text);
        if (response.result == "ok") {
          WarehouseSizeJSON = JSON.parse(decodeURIComponent(escape(atob(response.size))));

          if (response.canedit) {
            winapp.innerHTML += '<p style="width: calc(100% - 35px); border-bottom: 1px solid #bdc3c7; display: inline-block; margin-right: 15px; ">Paraméterek - <span style="color: var(--panelcolor);">Szerkeszthető</span></p>';
          } else {
            winapp.innerHTML += '<p style="width: calc(100% - 35px); border-bottom: 1px solid #bdc3c7; display: inline-block; margin-right: 15px; ">Paraméterek - <span style="color: var(--panelcolor);">Korlátozva szerkeszthető</span></p>';
          }
          var parameters = '<div style="display: inline; float: left; padding-left: 15px; margin-top: 10px;">';
          parameters += '<p class="label">Szektor elnevezése:</p>';
          parameters += '<input id="winapp_name" type="text" autocomplete="off" spellcheck="false" placeholder="Szektor elnevezése..." value="'+response.name+'" style="width: 150px;"><br>';

          parameters += '</div><div style="display: inline; float: left; padding-left: 15px; margin-top: 10px;">';
          parameters += '<p class="label">Raktár helye:</p>';
          parameters += '<input id="winapp_location" type="text" autocomplete="off" spellcheck="false" placeholder="Raktár helye..." value="'+response.location+'" style="width: 150px;" list="location_list" oninput="AutoWriteLoc(this.id)"><br>';

          parameters += '</div><div style="display: inline; float: left; padding-left: 15px; margin-top: 10px;">';
          parameters += '<p class="label">Raktár kódja:</p>';
          parameters += '<input id="winapp_code" type="text" autocomplete="off" spellcheck="false" placeholder="Raktár kódja..." value="'+response.code+'" style="width: 150px;"  list="code_list" oninput="AutoWriteLoc(this.id)"><br>';

          parameters += '</div><div style="display: inline; float: left; padding-left: 15px; margin-top: 10px;">';
          parameters += '<p class="label">Oszlopok száma:</p>';
          parameters += '<input onchange="UpdateShelf();" id="winapp_columns" type="number" min="1" autocomplete="off" spellcheck="false" placeholder="Oszlopok száma..." value="'+response.columns+'" style="width: 150px;"><br>';

          parameters += '</div><div style="display: inline; float: left; padding-left: 15px; margin-top: 10px;">';
          parameters += '<p class="label">Sorok száma:</p>';
          parameters += '<input onchange="UpdateShelf();" id="winapp_row" type="number" min="1" autocomplete="off" spellcheck="false" placeholder="Sorok száma..." value="'+response.row+'" style="width: 150px;"><br>';

          parameters += '</div><div style="display: inline; float: left; padding-left: 15px; margin-top: 10px;">';
          parameters += '<p class="label" title="Hányadik sortól lehet több cikkszámot a polcra helyezni" style="cursor: help;">Több cikkszám elhelyezése:</p>';
          parameters += '<input  id="winapp_multiitem_row" type="number" min="0" autocomplete="off" spellcheck="false" placeholder="Hányadik sortól lehet több cikkszámot a polcra helyezni..." value="'+response.multiitem_row+'" style="width: 150px;"><br>';

          parameters += '</div><div style="display: inline; float: left; padding-left: 15px; margin-top: 10px;">';
          parameters += '<p class="label">Állapot:</p>';
          if (response.status == '1') {
            parameters += '<select id="winapp_status" style="width: calc(150px + 18px); max-width: unset;"><option value="0">Inaktív</option><option value="1" selected>Aktív</option></select><br>';
          } else {
            parameters += '<select id="winapp_status" style="width: calc(150px + 18px); max-width: unset;"><option value="0" selected>Inaktív</option><option value="1">Aktív</option></select><br>';
          }

          winapp.innerHTML += parameters + "</div>";

          if (response.canedit) {
            document.getElementById("winapp_row").disabled = false;
            document.getElementById("winapp_columns").disabled = false;
            currentEditable = true;
            currentDisable = '';
          } else {
            document.getElementById("winapp_row").disabled = true;
            document.getElementById("winapp_columns").disabled = true;
            currentDisable = 'disabled';
          }

          if (response.canedit) {
            winapp.innerHTML += '<p style="width: calc(100% - 35px); border-bottom: 1px solid #bdc3c7; display: inline-block; margin-right: 15px; ">Méretek - <span style="color: var(--panelcolor);">Szerkeszthető</span></p><br clear="all"><br clear="all"><div style="display: inline; float: left; padding-left: 15px; width: calc(70% - 50px);"><div id="winapp_size" class="warehouse" style="width: fit-content; max-width: 100%;"></div></div>';
          } else {
            winapp.innerHTML += '<p style="width: calc(100% - 35px); border-bottom: 1px solid #bdc3c7; display: inline-block; margin-right: 15px; ">Méretek</p><br clear="all"><br clear="all"><div style="display: inline; float: left; padding-left: 15px; width: calc(70% - 50px);"><div id="winapp_size" class="warehouse" style="width: fit-content; max-width: 100%;"></div></div>';
          }
          generateShelf(response.columns, response.row, "winapp_size");

          var GenerateOptions = '';
          for (var i = 0; i < SizeOptions.length; i++) {
            if (SizeOptions[i] == WarehouseSizeJSON.globalSize) {
              GenerateOptions += '<option value="'+SizeOptions[i]+'" selected>'+SizeOptions[i]+'</option>';
            } else {
              GenerateOptions += '<option value="'+SizeOptions[i]+'">'+SizeOptions[i]+'</option>';
            }
          }

          winapp.innerHTML += `
          <div style="display: inline; float: right; padding-left: 15px;">
            <div id="winapp_size_editor" class="panelloader" style="top: unset;">
              <div class="overlay"></div>
              <div class="box" id="cellsizeinfo" style="width: calc(100% - 43px);">
                <p style="font-weight: bold;">Jellemzők - Alapértelmezett</p>
                <p>Polc mérete:</p>
                <select id="winapp_size_select" onchange="UpdateNewCellSize();" ${currentDisable}>${GenerateOptions}</select>
                <p>Polc kapacitás:</p>
                <input id="winapp_capacity" type="number" min="1" autocomplete="off" spellcheck="false" placeholder="Polconkénti maximum darabszám..." value="${WarehouseSizeJSON.globalCapacity}" style="width: 150px;" ${currentDisable}  oninput="UpdateNewCellSize()">
              </div>
            </div>
          </div>`;

          ColorCellSize();

          winapp.innerHTML += '<br clear="all"><br clear="all"><button onclick="SaveWarehouse();" style="margin-top: 10px;">Raktár elmentése</button><br clear="all"><br clear="all">';
        } else {
          GenerateAlerts("error", response.result);
        }
      }, function() {
        Loading(false);
        GenerateAlerts("error", "Hálózati hiba!");
      });

    }
    function UpdateShelf() {
      var row = document.getElementById('winapp_row').value;
      var columns = document.getElementById('winapp_columns').value;
      generateShelf(columns, row, "winapp_size");
      ColorCellSize();
    }

    function generateShelf(columns, rows, divid) {
      const warehouse = document.getElementById(divid);
      var warehouse_id = document.getElementById("current_warehouse_id").value;
      warehouse.innerHTML = '';

      const headerRow = document.createElement('div');
      headerRow.className = 'shelf-row';
      const cornerCell = document.createElement('div');
      cornerCell.className = 'shelf-cell number-corner';
      headerRow.appendChild(cornerCell);

      for (let col = 0; col < columns; col++) {
        const headerCell = document.createElement('div');
        headerCell.className = 'shelf-cell number';
        headerCell.innerText = col + 1;
        headerRow.appendChild(headerCell);
      }
      warehouse.appendChild(headerRow);

      for (let row = 0; row < rows; row++) {
        const shelfRow = document.createElement('div');
        shelfRow.className = 'shelf-row';
        const rowLabel = document.createElement('div');
        rowLabel.className = 'shelf-cell number';
        rowLabel.innerText = NumberToABC(row + 1);
        shelfRow.appendChild(rowLabel);

        for (let col = 0; col < columns; col++) {
          const cell = document.createElement('div');
          cell.className = 'shelf-cell';
          cell.id = `${warehouse_id}:${col}:${row}:${divid}`;
          cell.setAttribute("onclick", `OpenCell(${col}, ${row}, '${divid}')`);
          shelfRow.appendChild(cell);
        }
        warehouse.appendChild(shelfRow);
      }
    }

    function OpenCell(column, row, divid) {
      if (divid != "warehouse") {
        EditCellSize(column, row);
      } else {
        const cellinfo = document.getElementById("cellinfo");
        var warehouse_id = document.getElementById("current_warehouse_id").value;
        document.getElementById("loader").classList.add('active');

        const body = 'func=OpenCell&warehouse_id='+warehouse_id+'&column='+column+'&row='+row;
        get_POST_information("warehouse.php", body, function(text) {
          document.getElementById("loader").classList.remove('active');
          let response = JSON.parse(text);
          if (response.result == "ok") {
            cellinfo.innerHTML = '<p style="font-weight: bold;">Jellemzők - '+NumberToABC(row+1)+':'+padWithZero(column+1)+'</p>';

            cellinfo.innerHTML += '<p>Kapacitás: <span style="color: var(--panelcolor);">'+response.capacity+' doboz</span></p>';

            cellinfo.innerHTML += '<p>Méret: <span style="color: var(--panelcolor);">'+response.size+'</span></p>';

            var ShelfContent = '<p style="margin-bottom: 0px;">Polc tartalma:</p><ul style="color: var(--panelcolor); margin-top: 0px; list-style-type: circle;">'+response.content;

            if (response.box_stock_taking == true) {
              ShelfContent += `<li onclick="AddItemToCell(${column}, ${row})"><i data-feather='plus-circle' style='position: absolute; display: inline-block; width: 40px; height: 40px; opacity: 0.6; cursor: pointer; color: var(--panelcolor);'></i></li>`;
            }
            ShelfContent += '</ul>';
            cellinfo.innerHTML += ShelfContent;

            feather.replace();
          } else {
            GenerateAlerts("error", response.result);
          }
        }, function() {
          Loading(false);
          GenerateAlerts("error", "Hálózati hiba!");
        });
      }
    }
    function AddItemToCell(column, row, item_id = "", amount = 0, pos = '', ToScrap = null, wid = '') {
      if (item_id != "" && amount != 0) {
        Loading();
        if (pos != '') {
          var position = pos;
        } else {
          var position = (row + 1) + ":" + (column + 1);
        }
        if (wid != '') {
          var warehouse_id = wid;
        } else {
          var warehouse_id = document.getElementById("current_warehouse_id").value;
        }
        var reason = 'Manual#<?php echo $userName; ?>';

        const body = 'func=PlaceIntoWarehouse&item_id=' + encodeURIComponent(item_id).replace(/%20/g, '+') + '&placed=' + amount + '&warehouse_id=' + warehouse_id + '&position=' + position + '&reason=' + encodeURIComponent(reason).replace(/%20/g, '+');

        get_POST_information("wh_add.php", body, function(text) {
          let response = JSON.parse(text);
          Loading(false);
          if (response.result == "ok") {
            if (ToScrap != null) {
              ScrapRemoval(ToScrap.item_id, ToScrap.amount, amount, ToScrap.code_old);
            } else {
              OpenWarehouse(warehouse_id);
            }
          } else {
            GenerateAlerts("error", response.result);
          }
        }, function() {
          Loading(false);
          GenerateAlerts("error", "Hálózati hiba!");
        });

      } else {
        var printplace = NumberToABC(row+1) + ':' + padWithZero(column+1);
        var thisid = GenerateID();

        if (amount == 0) amount = "";

        var html = `
        <p><b>Cikkszám hozzáadása</b><br>Adjon hozzá manuálisan cikkszámot a(z) <b>${printplace}</b> helyhez</p><br>
        <input type="text" id="AlertTextInput_${thisid}" placeholder="Cikkszám..." autocomplete="off" style="width: 100px;" value="${item_id}">
        <input type="number" id="AlertNumberInput_${thisid}" placeholder="Mennyiség..." autocomplete="off" min="1" style="width: 100px;" value="${amount}">
        <br clear="all"><br>
        <button id="AlertBtnNo_${thisid}" style="float: right; margin-left: 15px; width: 80;">Mégsem</button>
        <button id="AlertBtnYes_${thisid}" style="float: right; width: 60px; background: var(--panelcolor); color: #f5f5f5; border: unset;">Mentés</button>
        `;
        const overlay = CreateAlertBox('Hozzáadás', html);
        document.getElementById('AlertBtnYes_' + thisid).onclick = function () { AddItemToCell(column, row, (document.getElementById("AlertTextInput_" + thisid).value), (document.getElementById("AlertNumberInput_" + thisid).value)); CloseAlertBox(overlay); };
        document.getElementById('AlertBtnNo_' + thisid).onclick = function () { CloseAlertBox(overlay); };
        return;
      }
    }
    var CurrentEditingSize = '';
    function EditCellSize(column, row) {
      CurrentEditingSize = column+":"+row;
      const cellinfo = document.getElementById("cellsizeinfo");
      var warehouse_id = document.getElementById("current_warehouse_id").value;
      cellinfo.innerHTML = '<p style="font-weight: bold;">Jellemzők - '+NumberToABC(row+1)+':'+padWithZero(column+1)+'</p>';
      var GenerateOptions = '<option value="-1">Alapértelmezett</option>';
      var TargetPrintSize = 'Globális';
      if (WarehouseSizeJSON.customSizes[column+":"+row] != null) {
        TargetPrintSize = WarehouseSizeJSON.customSizes[column+":"+row];
      }
      for (var i = 0; i < SizeOptions.length; i++) {
        if (SizeOptions[i] == TargetPrintSize) {
          GenerateOptions += '<option value="'+SizeOptions[i]+'" selected>'+SizeOptions[i]+'</option>';
        } else {
          GenerateOptions += '<option value="'+SizeOptions[i]+'">'+SizeOptions[i]+'</option>';
        }
      }
      cellinfo.innerHTML += `
        <p>Polc mérete:</p>
        <select id="winapp_size_select" onchange="UpdateNewCellSize();"  ${currentDisable}>${GenerateOptions}</select>
        <p>Polc kapacitás:</p>
        <select id="winapp_capacity_mode" onchange="toggleCustomCapacity(this.value)" ${currentDisable}>
      		<option value="default">Alapértelmezett</option>
      		<option value="custom">Egyedi érték</option>
      	</select>
        <input id="winapp_capacity" type="number" min="1" autocomplete="off" spellcheck="false" placeholder="Polconkénti maximum darabszám..." value="${WarehouseSizeJSON.globalCapacity}" style="width: 150px; display: none;" oninput="UpdateNewCellSize()">
        `;

      if (WarehouseSizeJSON.customCapacity[column+":"+row] != null) {
        document.getElementById("winapp_capacity").value = WarehouseSizeJSON.customCapacity[column+":"+row];
        document.getElementById("winapp_capacity_mode").value = 'custom';
        toggleCustomCapacity('custom');
      }

    }
    function toggleCustomCapacity(val) {
      const input = document.getElementById('winapp_capacity');
      if (val === 'custom') {
        input.style.display = 'inline-block';
        input.disabled = false;
      } else {
        input.style.display = 'none';
        input.disabled = true;
        input.value = WarehouseSizeJSON.globalCapacity;
      }
      UpdateNewCellSize();
    }
    function UpdateNewCellSize() {
      warehouse_id = document.getElementById("current_warehouse_id").value;
      if (warehouse_id != "") {
        if (CurrentEditingSize == "") {
          WarehouseSizeJSON.globalSize = document.getElementById("winapp_size_select").value;
          WarehouseSizeJSON.globalCapacity = document.getElementById("winapp_capacity").value;
        } else {
          if (document.getElementById("winapp_size_select").value == "-1") {
            delete WarehouseSizeJSON.customSizes[CurrentEditingSize];
          } else {
            WarehouseSizeJSON.customSizes[CurrentEditingSize] = document.getElementById("winapp_size_select").value;
         }

         if (document.getElementById("winapp_capacity_mode").value == "default") {
           delete WarehouseSizeJSON.customCapacity[CurrentEditingSize];
         } else {
           WarehouseSizeJSON.customCapacity[CurrentEditingSize] = document.getElementById("winapp_capacity").value;
         }
       }

       ColorCellSize();
      }
    }
    function ColorCellSize() {
      var shelfCells = document.querySelectorAll('.shelf-cell[id$=":winapp_size"]');
      shelfCells.forEach(function(cell) {
        cell.style.backgroundColor = '';
        cell.style.backgroundImage = '';
      });

      for (var key in WarehouseSizeJSON.customSizes) {
        if (WarehouseSizeJSON.customSizes.hasOwnProperty(key)) {
          var value = WarehouseSizeJSON.customSizes[key];
          var id = document.getElementById("current_warehouse_id").value+":"+key+":winapp_size";
          if (document.getElementById(id) != null) {
            document.getElementById(id).style.backgroundColor = "#" + MD5(value).substring(0, 6);
          }
        }
      }

      for (var key in WarehouseSizeJSON.customCapacity) {
      	if (WarehouseSizeJSON.customCapacity.hasOwnProperty(key)) {
      		var value = WarehouseSizeJSON.customCapacity[key];
      		var id = document.getElementById("current_warehouse_id").value+":"+key+":winapp_size";
      		if (document.getElementById(id) != null) {
      			var elem = document.getElementById(id);
      			var CapColor = "#" + MD5(value).substring(0, 6);

            elem.style.backgroundImage = `repeating-linear-gradient(
            	45deg,
            	${CapColor} 0px,
            	${CapColor} 2px,
            	transparent 2px,
            	transparent 6px
            )`;

      			elem.style.backgroundSize = '100% 100%';
      			elem.style.backgroundRepeat = 'repeat';
      			elem.style.backgroundBlendMode = 'overlay';
      		}
      	}
      }

    }

    function SaveWarehouse() {
      Loading();
      var warehouse_id = document.getElementById('current_warehouse_id').value;
      var name = document.getElementById('winapp_name').value;
      var location = document.getElementById('winapp_location').value;
      var code = document.getElementById('winapp_code').value;
      var row = document.getElementById('winapp_row').value;
      var columns = document.getElementById('winapp_columns').value;
      var capacity = WarehouseSizeJSON.globalCapacity;
      var status = document.getElementById('winapp_status').value;
      var multiitem_row = document.getElementById('winapp_multiitem_row').value;
      var jsonString = JSON.stringify(WarehouseSizeJSON);
      var size = btoa(unescape(encodeURIComponent(jsonString)));

      const body = 'func=SaveWarehouse&name=' + encodeURIComponent(name).replace(/%20/g, '+') + '&location=' + encodeURIComponent(location).replace(/%20/g, '+') + '&code=' + encodeURIComponent(code).replace(/%20/g, '+') + '&row=' + row + '&columns=' + columns + '&capacity=' + capacity + '&status=' + status + '&size=' + encodeURIComponent(size).replace(/%20/g, '+') + '&warehouse_id=' + warehouse_id + '&multiitem_row=' + multiitem_row;
      get_POST_information("warehouse.php", body, function(text) {
        Loading(false);
        let response = JSON.parse(text);
        if (response.result == "ok") {
          closewin();
          OpenWarehouse(warehouse_id);
          GenerateAlerts("success", "Sikeresen módosította a szektort!");
        } else {
          GenerateAlerts("error", response.result);
        }
      }, function() {
        Loading(false);
        GenerateAlerts("error", "Hálózati hiba!");
      });
    }


    /* Fóliás raktár */
    function OpenFoilWarehouse() {
      openwin();
      wintitle.innerHTML = "Fóliás raktár";
      winapp.innerHTML = '<div id="errorDIV"></div>';
      winapp.innerHTML += `
      <h1>Fóliás raktár</h1>
      <div class="box" style="width: 300px; height: 160px;">
        <h2 style="text-align: center;">Adatlekérés</h2>
        <p class="strong">Cikkszám:</p>
        <input type="text" id="item_id_foil_warehouse" placeholder="Cikkszám..." autocomplete="off" spellcheck="false" autocapitalize="off" autocorrect="off" onkeydown="if (event.key === 'Enter') {SearchFoilItem();}">
        <button style="height: 34px; margin-left: 5px;" onclick="SearchFoilItem();">Lekérés</button>
        <br clear="all"><br>
      </div>

      <div class="box" style="width: 300px; height: 190px; display: none;" id="data_box_foil_warehouse">
        <h2 style="text-align: center;">Adatok</h2>

        <div style="display: inline-block; float: right; width: calc(50% - 5px); border-left: 1px solid #d3dce4; text-align: center;">
          <p><span style="font-weight: bold;">Jobb: </span><span style="color: var(--panelcolor);" id="right_db_foil_warehouse">12</span> db</p>
          <button class="plusbtn" onclick="EditFoilItem(0, 1);">+1</button><button class="minusbtn" onclick="EditFoilItem(0, -1);" style="margin-left: 15px;" id="right_minus_btn_foil_warehouse">-1</button>
        </div>
        <div style="display: inline-block; float: left; width: 50%; text-align: center;">
          <p><span style="font-weight: bold;">Bal: </span><span style="color: var(--panelcolor);" id="left_db_foil_warehouse">10</span> db</p>
          <button class="plusbtn" onclick="EditFoilItem(1, 0);">+1</button><button class="minusbtn" onclick="EditFoilItem(-1, 0);" style="margin-left: 15px;" id="left_minus_btn_foil_warehouse">-1</button>
        </div>

        <br clear="all"><p style="text-align: center; opacity: 0.8; margin-top: 10px;"><b>Helye:</b> <span id="place"></span></p>

      </div>
      `;
    }
    function SearchFoilItem() {
      Loading();
      const DataBox = document.getElementById("data_box_foil_warehouse");
      DataBox.style.display = "none";
      var item_id = document.getElementById("item_id_foil_warehouse").value;
      const body = 'func=SearchFoilItem&item_id=' + encodeURIComponent(item_id).replace(/%20/g, '+');
      OpenFoilWarehouse();
      get_POST_information("warehouse.php", body, function(text) {
        Loading(false);
        let response = JSON.parse(text);
        if (response.result == "ok") {

          response.data.forEach((warehouse, index) => {
            let rightDisabled = warehouse.right_db <= 0 ? 'disabled' : '';
            let leftDisabled = warehouse.left_db <= 0 ? 'disabled' : '';

            let right10Disabled = warehouse.right_db <= 9 ? 'disabled' : '';
            let left10Disabled = warehouse.left_db <= 9 ? 'disabled' : '';

            var SettingsText = ``;
            if (response.warehouse_editor == true) {
              SettingsText = `<span onclick='EditFoilWarehouse("${warehouse.wid}", "${warehouse.place}");'><i data-feather='edit-3' style='position: absolute; display: inline-block; width: 20px; height: 20px; margin-left: 10px; cursor: pointer; color: var(--panelcolor);'></i></span>`;
            }

            winapp.innerHTML += `
              <div class="box" style="width: 300px; height: 160px;" id="data_box_foil_warehouse_${index}">
                <p style="text-align: center; margin-top: 10px; margin-bottom: 0px;"><b>Raktárhely:</b> <span id="place_${index}">${warehouse.place}</span>${SettingsText}</p>
                <br clear="all">

                <div style="display: inline-block; float: right; width: calc(50% - 5px); border-left: 1px solid #d3dce4; text-align: center;">
                  <p style="margin-top: 0px;"><span style="font-weight: bold;">Jobb: </span><span style="color: var(--panelcolor);" id="right_db_foil_warehouse_${index}">${warehouse.right_db}</span> db</p>
                  <button class="plusbtn" onclick="EditFoilItem(0, 1, ${warehouse.wid});">+1</button>
                  <button class="minusbtn" onclick="EditFoilItem(0, -1, ${warehouse.wid});" style="margin-left: 15px;" id="right_minus_btn_foil_warehouse_${index}" ${rightDisabled}>-1</button>
                  <br clear="all">
                  <button class="plusbtn" onclick="EditFoilItem(0, 10, ${warehouse.wid});">+10</button>
                  <button class="minusbtn" onclick="EditFoilItem(0, -10, ${warehouse.wid});" style="margin-left: 15px;" id="right_minus_btn_foil_warehouse_${index}" ${right10Disabled}>-10</button>
                </div>
                <div style="display: inline-block; float: left; width: 50%; text-align: center;">
                  <p style="margin-top: 0px;"><span style="font-weight: bold;">Bal: </span><span style="color: var(--panelcolor);" id="left_db_foil_warehouse_${index}">${warehouse.left_db}</span> db</p>
                  <button class="plusbtn" onclick="EditFoilItem(1, 0, ${warehouse.wid});">+1</button>
                  <button class="minusbtn" onclick="EditFoilItem(-1, 0, ${warehouse.wid});" style="margin-left: 15px;" id="left_minus_btn_foil_warehouse_${index}" ${leftDisabled}>-1</button>
                  <br clear="all">
                  <button class="plusbtn" onclick="EditFoilItem(10, 0, ${warehouse.wid});">+10</button>
                  <button class="minusbtn" onclick="EditFoilItem(-10, 0, ${warehouse.wid});" style="margin-left: 15px;" id="left_minus_btn_foil_warehouse_${index}" ${left10Disabled}>-10</button>
                </div>

              </div>
            `;
          });

          document.getElementById("item_id_foil_warehouse").value = item_id;
          feather.replace();

        } else {
          GenerateAlerts("error", response.result);
        }
      }, function() {
        Loading(false);
        GenerateAlerts("error", "Hálózati hiba!");
      });
    }
    function EditFoilItem(left, right, wid) {
      Loading();
      const body = 'func=EditFoilItem&left=' + left + '&right=' + right + '&wid=' + wid;
      get_POST_information("warehouse.php", body, function(text) {
        let response = JSON.parse(text);
        if (response.result != "ok") {
          GenerateAlerts("error", response.result);
        } else {
          document.getElementById("item_id_foil_warehouse").value = response.item_id;
          SearchFoilItem();
        }
      }, function() {
        GenerateAlerts("error", "Hálózati hiba!");
      });
    }
    function EditFoilWarehouse(wid, current_place, new_place = "") {
      if (new_place != "" && current_place != new_place) {
        Loading();

        const body = 'func=EditFoilWarehouse&wid=' + wid + '&new_place=' + encodeURIComponent(new_place).replace(/%20/g, '+');
        get_POST_information("warehouse.php", body, function(text) {
          let response = JSON.parse(text);
          Loading(false);
          if (response.result == "ok") {
            SearchFoilItem();
          } else {
            GenerateAlerts("error", response.result);
          }
        }, function() {
          Loading(false);
          GenerateAlerts("error", "Hálózati hiba!");
        });

      } else {
        var thisid = GenerateID();
        var html = `
        <p><b>Raktárhely szerkesztő</b><br>Alább átírhatja a raktárhelyet.</p><br>
        <input type="text" id="AlertTextInput_${thisid}" placeholder="Raktárhely..." autocomplete="off" value="${current_place}">
        <br clear="all"><br>
        <button id="AlertBtnNo_${thisid}" style="float: right; margin-left: 15px; width: 80;">Mégsem</button>
        <button id="AlertBtnYes_${thisid}" style="float: right; width: 60px; background: var(--panelcolor); color: #f5f5f5; border: unset;">Mentés</button>
        `;
        const overlay = CreateAlertBox('Szerkesztés!', html, false);
        document.getElementById('AlertBtnYes_' + thisid).onclick = function () { EditFoilWarehouse(wid, current_place, (document.getElementById("AlertTextInput_" + thisid).value).toUpperCase()); CloseAlertBox(overlay); };
        document.getElementById('AlertBtnNo_' + thisid).onclick = function () { CloseAlertBox(overlay); };
        return;
      }
    }

    /* Doboz áthelyezés */
    function MoveBoxApp() {
      openwin();
      wintitle.innerHTML = "Doboz áthelyezés";
      winapp.innerHTML = '<div id="errorDIV"></div>';
      winapp.innerHTML = `
      <p style="color: #333333; margin-bottom: 0px; margin-left: 0px; font-size: 23px; font-weight: bold;">Doboz áthelyezés</p>
      <p style="opacity: 0.8; margin-top: 0px;">Töltse ki a mezőket, hogy át tudjon helyezni egy dobozt</p><br>
      <p style="width: calc(100% - 35px); border-bottom: 1px solid #bdc3c7; margin-top: 5px;"></p>
      <div style="display: flex; align-items: stretch;" class="InfoBox">

        <div id="productionPanel" class="panel panel-expanded" style="flex: 1; position: relative; padding-bottom: 35px;">
          <p class="panel-header">Forrás <small style="opacity: 0.8;">(Honnan)</small></p>
          <div class="panel-content">
            <p style="">Raktárhely:</p>
            <input id="winapp_wh_id" type="text" placeholder="Raktárhely" autocomplete="off" value="${currentCode}">
            <br>

            <p style="">Cikkszám:</p>
            <input id="winapp_item_id" type="text" placeholder="Cikkszám" autocomplete="off" value="">
            <br>

            <p style="">Mennyiség:</p>
            <input id="winapp_amount" type="number" min='1' placeholder="Mennyiség" autocomplete="off" value="">
            <br>
          </div>
        </div>

        <div style="width: 1px; background-color: #bdc3c7; margin: 0 8px;"></div>

        <div id="boxingPanel" class="panel panel-expanded" style="flex: 1; position: relative; padding-bottom: 35px;">
          <p class="panel-header">Célhely <small style="opacity: 0.8;">(Hova)</small></p>
          <div class="panel-content">
            <p style="">Raktárhely:</p>
            <input id="winapp_wh_id_new" type="text" placeholder="Új raktárhely" autocomplete="off" value="">
            <br>

            <button onclick="MoveBox();" style="position: absolute; bottom: 0px; right: 0px;">Doboz áthelyezése</button>

          </div>
        </div>

      </div>`;

    }
    function MoveBox() {
      var wh_id = document.getElementById("winapp_wh_id").value;
      var item_id = document.getElementById("winapp_item_id").value;
      var amount = document.getElementById("winapp_amount").value;

      var wh_id_new = document.getElementById("winapp_wh_id_new").value;

      Loading(true);
      const body = 'func=MoveBox&wh_id=' + encodeURIComponent(wh_id).replace(/%20/g, '+') + '&item_id=' + encodeURIComponent(item_id).replace(/%20/g, '+') + '&amount=' + amount + '&wh_id_new=' + encodeURIComponent(wh_id_new).replace(/%20/g, '+');
      get_POST_information("warehouse.php", body, function(text) {
        Loading(false);
        let response = JSON.parse(text);
        if (response.result == "ok") {
          AddItemToCell(0, 0, response.item_id, response.amount, response.position_new, response, response.wid_new);
        } else {
          GenerateAlerts("error", response.result);
        }
      }, function() {
        Loading(false);
        GenerateAlerts("error", "Hálózati hiba!");
      });
    }
    function ScrapRemoval(item_id, right, left, warehouse_code) {
      Loading();
      const body = 'func=ScrapRemoval&item_id=' + encodeURIComponent(item_id).replace(/%20/g, '+') + '&left=' + left + '&right=' + right + '&warehouse_code=' + encodeURIComponent(warehouse_code).replace(/%20/g, '+');
      get_POST_information("wh_remove.php", body, function(text) {
        let response = JSON.parse(text);
        Loading(false);
        if (response.result == "ok") {
          GenerateAlerts("success", "Sikeresen áthelyezte a cikkszámot.");
        } else {
          GenerateAlerts("error", response.result);
        }
      }, function() {
        Loading(false);
        GenerateAlerts("error", "Hálózati hiba!");
      });
    }

    /* Statisztika */
    function Statistics() {
      openwin();
      wintitle.innerHTML = "Statisztika";

      winapp.innerHTML = `<div id="errorDIV"></div>
      <div class="statistics">

        <div class="container"><div class="header"><h1>Raktár statisztika</h1><p>Valós idejű termék készlet monitorozás</p></div>

        <div class="sections">

          <div class="section-group"><h2 class="section-group-title">Raktár</h2>
            <div class="section"><h3 class="section-name">Dobozos</h3><div class="section-articles" id="warehousestat_box"></div></div>
            <div class="section"><h3 class="section-name">Fóliás</h3><div class="section-articles" id="warehousestat_foil"></div></div>
            <div class="section"><h3 class="section-name">Összesen</h3><div class="section-articles" id="warehousestat_all"></div></div>
            <div class="section" style="border-top: 15px solid var(--bgcolor);"><h3 class="section-name">Szabad raktárkészlet</h3><div class="section-articles" id="warehousestat_shortage"></div></div>
          </div>

        </div>

      </div>`;

      const body = 'func=statistics';
      get_POST_information("warehouse.php", body, function(text) {
        let response = JSON.parse(text);
        if (response.result == "ok") {
          const sectionMap = {
            type: {
              'classic': 'Classic',
              'climair': 'ClimAir',
              'injmold': 'Fröccsöntött',
              'sporty': 'Sporty',
              'all': 'Összesen',
              'unknown': 'Ismeretlen'
            }
          };

          Object.keys(response.box).forEach(key => {
            let item = response.box[key];
            CreateStatElement('warehousestat_box', sectionMap.type[item.category], [item.amount, 'Pár']);
          });

          Object.keys(response.foil).forEach(key => {
            let item = response.foil[key];
            CreateStatElement('warehousestat_foil', sectionMap.type[item.category], [item.right_db, 'Jobb'], [item.left_db, 'Bal']);
          });

          Object.keys(response.all).forEach(key => {
            let item = response.all[key];
            if (parseInt(item.amount) > 0) {
              CreateStatElement('warehousestat_all', sectionMap.type[item.category], [item.amount, 'Pár']);
            }
          });

          Object.keys(response.shortage).forEach(key => {
            let item = response.shortage[key];
            if (parseInt(item.zero) > 0 || parseInt(item.neg) > 0) {
              CreateStatElement('warehousestat_shortage', sectionMap.type[item.category], [item.zero, 'Nullás'], [item.neg, 'Mínuszos']);
            }
          });

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

    }
    function CreateStatElement(section_id, item_id, value, value2 = null) {
      if (value2 != null) {
        const section = document.getElementById(section_id);
          section.innerHTML += `
          <div class="article-card">
            <div class="article-card-code">${item_id}</div>
              <div class="article-card-stats">
                <div class="article-card-stat">
                  <span class="article-card-label">${value2[1]}:</span>
                  <span class="article-card-value right">${value2[0]}</span>
                </div>
                <div class="article-card-stat">
                  <span class="article-card-label">${value[1]}:</span>
                  <span class="article-card-value left">${value[0]}</span>
                </div>
              </div>
            </div>`;
      } else {
        const section = document.getElementById(section_id);
          section.innerHTML += `
          <div class="article-card">
            <div class="article-card-code">${item_id}</div>
              <div class="article-card-stats">
                <div class="article-card-stat">
                  <span class="article-card-label">${value[1]}:</span>
                  <span class="article-card-value right">${value[0]}</span>
                </div>
              </div>
            </div>`;
      }
    }

    document.addEventListener("click", function(event) {
      const cellinfo = document.getElementById("cellinfo");
      const WarehouseDiv = document.getElementById("warehouse");

      const cellsizeinfo = document.getElementById("cellsizeinfo");
      const winapp_size = document.getElementById("winapp_size");
      if (cellinfo != null && !cellinfo.contains(event.target) && !WarehouseDiv.contains(event.target)) {
        if (currentWarehouseCapacity == 0) {
          cellinfo.innerHTML = '<p style="font-weight: bold;">Jellemzők</p><p>Kapacitás: <span style="color: var(--panelcolor);">Ömlesztett</span></p><p>Állapot: <span style="color: var(--panelcolor);">'+currentStatus+'</span></p>';
        } else {
          cellinfo.innerHTML = '<p style="font-weight: bold;">Jellemzők</p><p>Kapacitás: <span style="color: var(--panelcolor);">' + currentFullness + ' / '+currentWarehouseCapacity+' doboz <small style="float: right;">'+(parseInt(currentFullness) / parseInt(currentWarehouseCapacity) * 100 ).toFixed(2)+'%</small></span></p><p>Polconként: <span style="color: var(--panelcolor);">'+currentCapacity+' doboz</span></p><p>Alapértelmezett méret: <span style="color: var(--panelcolor);">'+currentSize+'</span></p><p>Állapot: <span style="color: var(--panelcolor);">'+currentStatus+'</span></p>';
        }
      }
      if (cellsizeinfo != null && !cellsizeinfo.contains(event.target) && !winapp_size.contains(event.target) && WarehouseSizeJSON != null) {
        var GenerateOptions = '';
        CurrentEditingSize = '';
        for (var i = 0; i < SizeOptions.length; i++) {
          if (SizeOptions[i] == WarehouseSizeJSON.globalSize) {
            GenerateOptions += '<option value="'+SizeOptions[i]+'" selected>'+SizeOptions[i]+'</option>';
          } else {
            GenerateOptions += '<option value="'+SizeOptions[i]+'">'+SizeOptions[i]+'</option>';
          }
        }
        cellsizeinfo.innerHTML = `
        <p style="font-weight: bold;">Jellemzők - Alapértelmezett</p>
        <p>Polc mérete:</p>
        <select id="winapp_size_select" onchange="UpdateNewCellSize();" ${currentDisable}>${GenerateOptions}</select>
        <p>Polc kapacitás:</p>
        <input id="winapp_capacity" type="number" min="1" autocomplete="off" spellcheck="false" placeholder="Polconkénti maximum darabszám..." value="${WarehouseSizeJSON.globalCapacity}" style="width: 150px;" ${currentDisable}  oninput="UpdateNewCellSize()">
        `;

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

    let historyEntries = [];
    let currentIndex = -1;
    function navigateTo(levelName, func) {
      historyEntries = historyEntries.slice(0, currentIndex + 1);
      historyEntries.push({ level: levelName, func: func });
      currentIndex = historyEntries.length - 1;
      history.pushState({ index: currentIndex, level: levelName }, "", "#" + levelName);
      func();
    }
    window.addEventListener("popstate", function(event) {
      if (event.state?.index !== undefined) {
        const targetIndex = event.state.index;
        if (targetIndex >= 0 && targetIndex < historyEntries.length) {
          currentIndex = targetIndex;
          const entry = historyEntries[currentIndex];
          entry.func();
        }
      }
    });
    window.addEventListener('load', () => { navigateTo('', ShowWarehouseLocation); });

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