<?php

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

if (!UserHasPerm('warehouse_add')) {
  if (isset($_GET["iframe"])) {
    header('X-Frame-Options: DENY');
  } else {
    StopAndDie();
  }
}

// Távolság kalkulátor (Manhattan)
function min_distance($x, $y, $positions) {
  $min = PHP_INT_MAX;
  foreach ($positions as $pos) {
    [$px, $py] = explode(':', $pos);
    $dist = abs($x - $px) + abs($y - $py);
    if ($dist < $min) $min = $dist;
  }
  return $min;
}

if (isset($_POST["func"])) {
  if (htmlspecialchars($_POST["func"]) == "SearchWarehouse") {
    $item_id = htmlspecialchars(str_replace(' ', '+', $_POST['item_id']));
    $location = htmlspecialchars($_POST["location"]);
    $amount = intval(htmlspecialchars($_POST["amount"])) ?? 1;
    if ($amount == 0) { $amount = 1; }
    $amount_left = $amount;
    $WeHaveToPlaceHere = [];

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

    /*
    --------------------
    Cikkszám adatok
    --------------------*/
    $item_id_config = array();
    $sql = mysqli_query($conn,"SELECT name_in_db, item_id FROM pr_parameters WHERE item_id = '$item_id'");
    $pr_parameters = mysqli_fetch_array($sql);
    if ($pr_parameters != null) {
      $item_id_config["name_in_db"] = $pr_parameters["name_in_db"];
      $item_id = $pr_parameters["item_id"];
      $sql = mysqli_query($conn,"SELECT size FROM pr_warehouse_parameters WHERE item_id = '$item_id'");
      $pr_warehouse_parameters = mysqli_fetch_array($sql);
      if ($pr_warehouse_parameters != null && $pr_warehouse_parameters[0] != "") {
        $item_id_config["size"][] = $pr_warehouse_parameters[0];

        $AcceptableSize = "";
        foreach ($LocalData['BoxSizes'] as $box) {
          if ($box['Name'] === $pr_warehouse_parameters[0]) {
            $AcceptableSize = $box['ACCEPTABLE'];
            break;
          }
        }

        if ($AcceptableSize != "") {
          if (strpos($AcceptableSize, ",") !== false) {
            $item_id_config["size"] = array_merge(explode(",", $AcceptableSize), $item_id_config["size"]);
          } else {
            $item_id_config["size"][] = $AcceptableSize;
          }
        }

      } else {
        echo json_encode(["result" => "A cikkszámhoz nem lett megadva doboz méret!"]);
        exit();
      }
    } else {
      echo json_encode(["result" => "Nem létező cikkszámot adott meg!"]);
      exit();
    }

    /*
    --------------------
    Raktár struktúrák
    --------------------*/
    $warehouse_config = array();
    $query = "SELECT * FROM warehouse_structure";
    if ($result = $conn->query($query)) {
      while ($wh_structure = $result->fetch_assoc()) {
        $warehouse_config[$wh_structure["warehouse_id"]] = [
          "capacity" => $wh_structure["capacity"],
          "location" => $wh_structure["location"],
          "code" => $wh_structure["code"],
          "row" => $wh_structure["row"],
          "columns" => $wh_structure["columns"],
          "status" => $wh_structure["status"],
          "size" => $wh_structure["size"],
          "name" => $wh_structure["name"],
          "multiitem_row" => $wh_structure["multiitem_row"],
          "SizeJSON" => json_decode(base64_decode($wh_structure["size"]), true)
        ];
      }
    }

    /*
    --------------------
    Ha van olyan polc (cella) ahol az adott cikkszám megtalálható és nincsen tele
    --------------------*/
    $FindedWarehouseElement = array();
    $query = "SELECT * FROM warehouse WHERE item_id = '$item_id' and amount != 0";
    if ($result = $conn->query($query)) {
      while ($warehouse = $result->fetch_assoc()) {

        $warehouse_id = $warehouse['warehouse_id'];
        $CanSave = true;

        /* Kapacitás számolása */
        $position = explode(":", $warehouse['position']); //($row + 1).':'.($column + 1);
        $size_key = (intval($position[1]) - 1).':'.(intval($position[0]) - 1); // $column + $row

        $capacity_left = $warehouse_config[$warehouse_id]["SizeJSON"]['globalCapacity'];

        if (isset($warehouse_config[$warehouse_id]["SizeJSON"]['customCapacity'][$size_key])) {
          $capacity_left = $warehouse_config[$warehouse_id]["SizeJSON"]['customCapacity'][$size_key];
        }

        $position = $warehouse['position'];
        $sql = mysqli_query($conn,"SELECT SUM(amount) FROM warehouse WHERE position = '$position' and item_id != '$item_id' and amount != 0 and warehouse_id = '$warehouse_id'");
        $otherElement = mysqli_fetch_array($sql);
        if ($otherElement != null) {
          $capacity_left = $capacity_left - $otherElement[0] - $warehouse['amount'];
        } else {
          $capacity_left = $capacity_left - $warehouse['amount'];
        }
        if ($capacity_left <= 0) {
          $CanSave = false;
        }

        // Ellenőrzés: Doboz mérete
        $slot_size = $warehouse_config[$warehouse_id]["SizeJSON"]['customSizes'][$size_key] ?? $warehouse_config[$warehouse_id]["SizeJSON"]['globalSize'];
        if (!in_array($slot_size, $item_id_config["size"])) $CanSave = false;

        /* Raktár hely ellenőrzése */
        if ($warehouse_config[$warehouse_id]["location"] != $location && $location != "" && $location != "-1") {
          $CanSave = false;
        } else if ($warehouse_config[$warehouse_id]["status"] != 1) {
          $CanSave = false;
        }

        /* Elérhető opció */
        if ($CanSave) {
          $FindedWarehouseElement[] = [
            'wid' => $warehouse['wid'],
            'warehouse_id' => $warehouse_id,
            'position' => $warehouse['position'],
            'amount' => $warehouse['amount'],
            'capacity_left' => $capacity_left
          ];
        }

      }
    }

    usort($FindedWarehouseElement, function($a, $b) use ($amount_left) {
    	$a_enough = $a['capacity_left'] >= $amount_left;
    	$b_enough = $b['capacity_left'] >= $amount_left;

    	if ($a_enough && !$b_enough) return -1;
    	if (!$a_enough && $b_enough) return 1;

    	if ($a_enough && $b_enough) {
    		return $a['capacity_left'] <=> $b['capacity_left'];
    	}

    	return $b['capacity_left'] <=> $a['capacity_left'];
    });

    foreach ($FindedWarehouseElement as $slot) {
      if ($amount_left <= 0) break;

      $can_place = min($slot['capacity_left'], $amount_left);

      if ($can_place > 0) {
        $WeHaveToPlaceHere[] = [
          'warehouse_id' => $slot['warehouse_id'],
          'position' => $slot['position'],
          'placed' => $can_place,
          'size' => $item_id_config["size"]
        ];
        $amount_left -= $can_place;
      }
    }


    /*
    --------------------
    Megkeresi a legközelebbi üres polcot, és oda ajánlja
    --------------------*/
    $existing_positions = [];
    $warehouse_counts = [];

    foreach ($FindedWarehouseElement as $slot) {
      $wid = $slot['warehouse_id'];
      $existing_positions[$wid][] = $slot['position'];
      if (!isset($warehouse_counts[$wid])) $warehouse_counts[$wid] = 0;
      $warehouse_counts[$wid]++;
    }

    // Súlyozás: leggyakoribb warehouse_id előre
    arsort($warehouse_counts);
    $sorted_warehouses = array_keys($warehouse_counts);
    foreach (array_keys($warehouse_config) as $wid) {
      if (!in_array($wid, $sorted_warehouses)) {
        $sorted_warehouses[] = $wid;
      }
    }

    if ($amount_left > 0) {

      foreach ($sorted_warehouses as $wid) {
        if (isset($warehouse_config[$wid]["location"]) && $warehouse_config[$wid]["location"] != $location && $location != "" && $location != "-1") continue;
        if (isset($warehouse_config[$wid]["status"]) && $warehouse_config[$wid]["status"] != 1) continue;
        if (!isset($warehouse_config[$wid])) continue;
        if ($amount_left <= 0) break;

        $row = $warehouse_config[$wid]['row'];
        $cols = $warehouse_config[$wid]['columns'];
        $max_cap = $warehouse_config[$wid]['capacity'];
        $GlobalSize = $warehouse_config[$wid]["SizeJSON"]['globalSize'];

        $candidates = [];

        for ($i = 1; $i <= $row; $i++) {
          for ($j = 1; $j <= $cols; $j++) {
            $pos = "$i:$j";

            // Ellenőrzés: foglalt pozíció?
            $safe_pos = mysqli_real_escape_string($conn, $pos);
            $sql = mysqli_query($conn, "SELECT wid FROM warehouse WHERE position = '$safe_pos' AND warehouse_id = '$wid' AND amount != 0");
            if (mysqli_fetch_array($sql) != null) continue;

            // Ellenőrzés: Doboz mérete
            $size_key = ($j - 1) . ':' . ($i - 1);
            $slot_size = $warehouse_config[$wid]["SizeJSON"]['customSizes'][$size_key] ?? $GlobalSize;
            if (!in_array($slot_size, $item_id_config["size"])) continue;

            // Ellenőrzés: kapacitás
            $cap_left = $warehouse_config[$wid]["SizeJSON"]['customCapacity'][$size_key] ?? $warehouse_config[$wid]["SizeJSON"]['globalCapacity'];
            foreach ($FindedWarehouseElement as $slot) {
              if ($slot['warehouse_id'] === $wid && $slot['position'] === $pos) {
                $cap_left = (int)$slot['capacity_left'];
                break;
              }
            }

            if ($cap_left <= 0) continue;

            $dist = isset($existing_positions[$wid]) ? min_distance($i, $j, $existing_positions[$wid]) : 0;

            $candidates[] = [
              'warehouse_id' => $wid,
              'position' => $pos,
              'capacity_left' => $cap_left,
              'distance' => $dist,
              'size' => $slot_size
            ];
          }
        }

        // Közelebbi pozíciók előnyben, raktárpolc pazarlás számolás
        usort($candidates, function($a, $b) use ($amount_left) {
        	$a_enough = $a['capacity_left'] >= $amount_left;
        	$b_enough = $b['capacity_left'] >= $amount_left;

        	if ($a_enough && !$b_enough) return -1;
        	if (!$a_enough && $b_enough) return 1;

        	$distCmp = $a['distance'] <=> $b['distance'];
        	if ($distCmp !== 0) return $distCmp;

        	if ($a_enough && $b_enough) {
        		return $a['capacity_left'] <=> $b['capacity_left'];
        	}

        	return $b['capacity_left'] <=> $a['capacity_left'];
        });


        foreach ($candidates as $c) {
          if ($amount_left <= 0) break;

          $exists = false;
          foreach ($WeHaveToPlaceHere as $existing) {
            if ($existing['warehouse_id'] == $c['warehouse_id'] && $existing['position'] == $c['position']) {
              $exists = true;
              break;
            }
          }
          if ($exists) continue;

          $can_place = min($amount_left, $c['capacity_left']);
          $WeHaveToPlaceHere[] = [
            'warehouse_id' => $c['warehouse_id'],
            'position' => $c['position'],
            'placed' => $can_place,
            'size' => $c['size']
          ];
          $amount_left -= $can_place;
        }

      }
    }


    /*
    --------------------
    A legközelebbi még nem teli polcra ajánlja
    --------------------*/
    if ($amount_left > 0) {
      function candidate_exists($candidates, $warehouse_id, $position) {
        foreach ($candidates as $c) {
          if ($c['warehouse_id'] === $warehouse_id && $c['position'] === $position) {
            return true;
          }
        }
        return false;
      }

      foreach ($sorted_warehouses as $wid) {
        if (isset($warehouse_config[$wid]["location"]) && $warehouse_config[$wid]["location"] != $location && $location != "" && $location != "-1") continue;
        if (isset($warehouse_config[$wid]["status"]) && $warehouse_config[$wid]["status"] != 1) continue;
        if (!isset($warehouse_config[$wid])) continue;
        if ($amount_left <= 0) break;

        $row = $warehouse_config[$wid]['row'];
        $cols = $warehouse_config[$wid]['columns'];
        $max_cap = $warehouse_config[$wid]['capacity'];
        $GlobalSize = $warehouse_config[$wid]["SizeJSON"]['globalSize'];

        $candidates = [];

        for ($i = intval($warehouse_config[$wid]["multiitem_row"]); $i <= $row; $i++) {
          for ($j = 1; $j <= $cols; $j++) {
            $pos = "$i:$j";

            //Ellenőrzés: Tettünk e már ide
            if (candidate_exists($WeHaveToPlaceHere, $wid, $pos)) continue;

            // Ellenőrzés: Doboz mérete
            $size_key = ($j - 1) . ':' . ($i - 1);
            $slot_size = $warehouse_config[$wid]["SizeJSON"]['customSizes'][$size_key] ?? $GlobalSize;
            if (!in_array($slot_size, $item_id_config["size"])) continue;

            // Ellenőrzés: 1 termék van a polcon?
            $safe_pos = mysqli_real_escape_string($conn, $pos);
            $sql = mysqli_query($conn, "SELECT COUNT(wid), SUM(amount) FROM warehouse WHERE position = '$safe_pos' AND warehouse_id = '$wid' AND amount != 0");
            $sqlres = mysqli_fetch_array($sql);

            if ($sqlres[0] == 0) continue;

            // Ellenőrzés: kapacitás
            $cap_left = intval($warehouse_config[$wid]["SizeJSON"]['customCapacity'][$size_key] ?? $warehouse_config[$wid]["SizeJSON"]['globalCapacity']) - $sqlres[1];
            if ($cap_left <= 0) continue;

            $dist = isset($existing_positions[$wid]) ? min_distance($i, $j, $existing_positions[$wid]) : 0;

            $candidates[] = [
              'warehouse_id' => $wid,
              'position' => $pos,
              'capacity_left' => $cap_left,
              'distance' => $dist,
              'wid_count' => $sqlres[0],
              'size' => $slot_size
            ];
          }
        }

        usort($candidates, function($a, $b) use ($amount_left) {
        	if ($a['wid_count'] !== $b['wid_count']) {
        		return $a['wid_count'] <=> $b['wid_count'];
        	}

        	$a_enough = $a['capacity_left'] >= $amount_left;
        	$b_enough = $b['capacity_left'] >= $amount_left;

        	if ($a_enough && !$b_enough) return -1;
        	if (!$a_enough && $b_enough) return 1;

        	$distCmp = $a['distance'] <=> $b['distance'];
        	if ($distCmp !== 0) return $distCmp;

        	if ($a_enough && $b_enough) {
        		return $a['capacity_left'] <=> $b['capacity_left'];
        	}
        	return $b['capacity_left'] <=> $a['capacity_left'];
        });


        foreach ($candidates as $c) {
          if ($amount_left <= 0) break;

          $exists = false;
          foreach ($WeHaveToPlaceHere as $existing) {
            if ($existing['warehouse_id'] == $c['warehouse_id'] && $existing['position'] == $c['position']) {
              $exists = true;
              break;
            }
          }
          if ($exists) continue;

          $can_place = min($amount_left, $c['capacity_left']);
          $WeHaveToPlaceHere[] = [
            'warehouse_id' => $c['warehouse_id'],
            'position' => $c['position'],
            'placed' => $can_place,
            'size' => $c['size']
          ];
          $amount_left -= $can_place;
        }
      }

    }

    /*
    --------------------
    Végső simítások
    --------------------*/
    $toplace = array();
    foreach ($WeHaveToPlaceHere as $place) {
      $warehouse_id = $place["warehouse_id"];

      $toplace[] = [
        "warehouse_loc" => $warehouse_config[$place["warehouse_id"]]["location"],
        "warehouse_code" => $warehouse_config[$place["warehouse_id"]]["code"],
        "warehouse_name" => $warehouse_config[$place["warehouse_id"]]["name"],
        "warehouse_id" => $place["warehouse_id"],
        "position" => $place["position"],
        "placed" => $place["placed"],
        "size" => $place["size"]
      ];
    }

    usort($toplace, function ($a, $b) {
      $loc_cmp = strcmp($a['warehouse_loc'], $b['warehouse_loc']);
      if ($loc_cmp !== 0) return $loc_cmp;

      $name_cmp = strcmp($a['warehouse_name'], $b['warehouse_name']);
      if ($name_cmp !== 0) return $name_cmp;

      list($a_row, $a_col) = explode(":", $a['position']);
      list($b_row, $b_col) = explode(":", $b['position']);

      if ((int)$a_col === (int)$b_col) {
        return (int)$a_row - (int)$b_row;
      }
      return (int)$a_col - (int)$b_col;
    });

    echo json_encode(["result" => "ok", "toplace" => $toplace, "amount_left" => $amount_left, "item_id" => $item_id]);

  } else if (htmlspecialchars($_POST["func"]) == "PlaceIntoWarehouse") {
    $item_id = htmlspecialchars(str_replace(' ', '+', $_POST['item_id']));
    $placed = htmlspecialchars($_POST["placed"]);
    $warehouse_id = htmlspecialchars($_POST["warehouse_id"]);
    $position = htmlspecialchars($_POST["position"]);
    $reason = htmlspecialchars($_POST["reason"]);

    $result = array();

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

    $sql = mysqli_query($conn, "SELECT sum(amount) as amount FROM warehouse WHERE position = '$position' AND warehouse_id = '$warehouse_id'");
    $intheloc = mysqli_fetch_array($sql);

    $sizeJSON = json_decode(base64_decode($WarehouseData["size"]), true);

    $capacity = intval($sizeJSON['globalCapacity']);
    if (isset($sizeJSON['customCapacity'][intval(explode(':', $position)[1])-1 . ':' . intval(explode(':', $position)[0])-1])) {
      $capacity = intval($sizeJSON['customCapacity'][intval(explode(':', $position)[1])-1 . ':' . intval(explode(':', $position)[0])-1]);
    }

    if ($intheloc != null && $intheloc["amount"] != null) {
      $freespace = $capacity - $intheloc["amount"];
    } else {
      $freespace = $capacity;
    }

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

    $LocSize = '';
    if (isset($sizeJSON['customSizes'][intval(explode(':', $position)[1])-1 . ':' . intval(explode(':', $position)[0])-1])) {
        $LocSize = $sizeJSON['customSizes'][intval(explode(':', $position)[1])-1 . ':' . intval(explode(':', $position)[0])-1];
    } else {
        $LocSize = $sizeJSON['globalSize'];
    }

    if ($WarehouseData == null || $WarehouseData["status"] != 1) {
      $result['result'] = "Nem létező, vagy inaktív raktárba szeretne betenni elemet!";
    } else if ($ItemSize == null || $ItemSize[0] == "") {
      $result['result'] = "A megadott terméknek nem lett megadva dobozméret!";
    } else if ($freespace < $placed) {
      $result['result'] = "A kijelölt helyen nincsen elegendő hely!";
    } else {
      $item_id = $ItemSize['item_id'];
      $sql = mysqli_query($conn, "SELECT wid, amount FROM warehouse WHERE item_id = '$item_id' and warehouse_id = '$warehouse_id' and position = '$position'");
      $IsThereProduct = mysqli_fetch_array($sql);
      if ($IsThereProduct != null) {
        $newamount = $placed + $IsThereProduct[1];
        $wid = $IsThereProduct[0];
        $sql = mysqli_query($conn, "UPDATE warehouse SET amount = '$newamount' WHERE wid = '$wid'");
      } else {
        $sql = mysqli_query($conn, "SELECT wid FROM warehouse WHERE amount = 0 LIMIT 1");
        $WeCanUpdateOld = mysqli_fetch_array($sql);
        if ($WeCanUpdateOld != null) {
          $wid = $WeCanUpdateOld[0];
          $sql = mysqli_query($conn, "UPDATE warehouse SET item_id = '$item_id', warehouse_id = '$warehouse_id', position = '$position', amount = '$placed' WHERE wid = '$wid'");
        } else {
          $sql = mysqli_query($conn, "INSERT INTO warehouse(item_id, warehouse_id, position, amount) VALUES ('$item_id', '$warehouse_id', '$position', '$placed')");
        }
      }

      $loggerclass->writeLogWarehouse(['reason' => 'Doboz elhelyezés', 'reason_code' => 1,
          'item_id' => $item_id,
          'from_place' => $reason,
          'to_place' => $WarehouseData['code'] . chr(64 + intval(explode(':', $position)[0])) . explode(':', $position)[1],
          'amount_left' => $placed,
          'amount_right' => $placed
        ]);

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

      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 FROM $table WHERE pr_id = $pr_id");
            $db_revenue = mysqli_fetch_array($sql);
            if ($db_revenue != null) {
              $new_db_revenue = intval($placed) + intval($db_revenue[0]);
              $sql = mysqli_query($conn, "UPDATE $table SET db_revenue = $new_db_revenue WHERE pr_id = $pr_id");
            }
          }
        }

      }
    }

    echo json_encode($result);

  }


  exit();
}

$WarehouseLocSelect = '<option value="-1">-- 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>';
  }
}

?>

<!DOCTYPE html>
<html lang="hu" dir="ltr">
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="../css/panel.css">
    <title>Kezelőfelület</title>
  </head>
  <style>
    .clearfix::after {
      content: "";
      display: table;
      clear: both;
    }

    input:disabled {
      color: #333333;
      cursor: not-allowed;
    }
    .plusbtn {
      width: calc(93% / 5);
      border-radius: 12px;
      font-weight: bold;
      background: #3bb143 !important;
      color: var(--toppanel);
    }
    .minusbtn {
      width: calc(93% / 5);
      border-radius: 12px;
      font-weight: bold;
      background: #e3242b !important;
      color: var(--toppanel);
    }

  </style>
  <body>
    <?php echo isset($_GET["iframe"]) ? '' : $menuhtml; ?>
    <div class="window closed" id="win">
      <div class="topbar">
        <p id="wintitle">Title</p>
        <div class="btn fullscrn" onclick="fullscrn();" id="fullscrnbtn"></div>
        <div class="btn close" onclick="closewin();"></div>
      </div>
      <div class="wapp" id="winapp"><div id="errorDIV"></div></div>
      <div class="loading" id="winloading"></div>
    </div>
    <div class="loadingBG" id="loadingBG"><img src="../img/loading.gif"></div>
    <div class="content" style="margin-right: 30px;">
      <div id="errorDIV" style="z-index: 100; top: 50px; position: fixed; width: calc(100% - 260px);"></div>

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

      <!-- KATEGÓRIA GOMBOK -->
      <div class="category-tabs" style="grid-template-columns: repeat(2, 1fr);">

        <div class="category-tab active" onclick="switchCategory(this, 'box')" id="category_tab_box">
          <div class="category-tab-icon">
            <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAACXBIWXMAAAsTAAALEwEAmpwYAAAEDklEQVR4nO1ZX2hTVxj/tWLBtdnmElpaoTKTNelaE2vWEqSEdN1KRB+kxY5saC3bZDBQUddg2DqH0IywUtjqQ2Uvg3W0FSeUOgp72MA9iQ8ixfWhD2KRreDGEJ/8wyff4STc3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90T05OUnDw8NZ8rdtfvJ6Yy7iVJA5Li0t0fLyMv8HLew8O0KhEAWDwayAETjPRpgbc4xGoxSJRPiY5X12PCvwtvM1p9kzI57U1NJCB/vfE+C6dDrNyIgneerqqDkYFOC6UwV4CvGsqKhY1KdGXnOUGfF8Dmg1HHVWg0UaAAAAAElFTkSuQmCC" alt="external-Storage-furniture-beshi-color-kerismaker">
          </div>
          <div class="category-tab-title">Dobozos raktár</div>
          <div class="category-tab-desc">Dobozos raktárba tétel</div>
        </div>

        <div class="category-tab" onclick="switchCategory(this, 'foil')" id="category_tab_foil">
          <div class="category-tab-icon">
            <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAACXBIWXMAAAsTAAALEwEAmpwYAAAFa0lEQVR4nO3bf0zUZRwH8Pf3933tFIKVabMy3QDBOZIcrYz+0C9McBpTKpw0MrGNO/QPWc0ZpFsm/mCTKQ0USChD8dcaP0xMbdVoyhmJVvhrZVP5sklpm8Idx6c91+kUEe88BiTPZ/vsdrt7nufzvJ7nbvfHfYAHh6pKQqUoCJ0A6FYKgFuVxBMAxmOIB+Xmim2Gsexhx2dYNbnzozmTKP/NKbdz7bzJNHG01SWLwn4M4fjbMEJMI77InGm4TcOwnUlI0PydY8O08SGur7Jepp75zivPkSqLZzFE4o19zeMSas/ctcGrhjHOnBlfaRrx3W0z41e2z5gR5O+8G6KeDur6ODmKembSlDEBAZAjMgL9GPOqTh+Yv+dUwj3rxMXJbYaR8zBzPiNJUuudn/2eKQiCC8AMfyemxvBEcoRfJUf4Sw9TmN/r5eaKfg+yWCw1sbGxzvLyCtq3b/89WVm5k9LS0khRlOsArH4X5ZiU7ndRgArgcQAhAPy+zv6tpKrtxcXFZJpt983m5ubbt0HTtGu6rp9TVXUngLcBjAmwhCcALJAkaYeu6y2SJHX0cgu7NU1r03X9OwAfApgGQOoXAEVRrpeUlPYJcPLkfwCrVq2mqqrdtH79ekpNTXWHhoZ6irVYLC0A8gC8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OAX/2KBZFjg5y9NU7OiR5LuiL9hkc8CqaND+nsrXU2I+55BvArHvHIZM3TuT2ap/PmT6awp0Z2abJYhUc8NFkUdouC4Lz7sw+3JosOAM8OdoGBxL9TX9WsNMQWeQAAAABJRU5ErkJggg==" alt="external-foil-camping-flaticons-lineal-color-flat-icons-4">
          </div>
          <div class="category-tab-title">Fóliás raktár</div>
          <div class="category-tab-desc">Fóliás raktár szerkesztő</div>
        </div>

      </div>

      <!-- DOBOZOS -->
      <div id="box" class="cat-tab form-section active">
        <div class="form-title">Dobozos raktár</div>

        <div style="width: 100%; min-height: 85px;">
          <div style="display: inline; float: left;">
            <p>Cikkszám: </p>
            <input type="text" id="filter-item_id" placeholder="Cikkszám..." onkeyup="SyncItemID(this.value);" onkeydown="if (event.keyCode == 13) {SearchWarehouse();}" autocomplete="off" style="width: 147px; height: 17px;">
          </div><div style="display: inline; float: left; padding-left: 15px;">
            <p>Mennyiség: </p>
            <input type="number" min="1" id="filter-amount" placeholder="Mennyiség..." onkeydown="if (event.keyCode == 13) {SearchWarehouse();}" autocomplete="off" style="width: 147px; height: 17px;">
          </div><div style="display: inline; float: left; padding-left: 15px;">
            <p>Raktárhely: </p>
            <select id="filter-location"><?php echo $WarehouseLocSelect;?></select>
          </div><div style="display: inline; float: left; padding-left: 15px;">
            <p style="color: #f5f5f5;">: </p>
            <button onclick="SearchWarehouse();">Optimális hely keresése</button>
          </div>
        </div>

        <br clear="all"><br>
        <div class="form-desc">Keressen optimális helyet, majd helyezze el a rendszer által ajánlott helyekre</div>

        <div id="result_div" class="clearfix" style="display: none; visibility: invisible;">

          <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 style="background-color: #ddd; width: 100px; color: #333; border: none; text-align: center;">Cikkszám</th>
                    <th>Mennyiség</th>
                    <th>Helye</th>
                    <th style="width: 100px;">Elhelyezés</th>
                  </tr>
                </thead>

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

        </div>

      </div>

      <!-- FÓLIÁS -->
      <div id="foil" class="cat-tab form-section">
        <div class="form-title">Fóliás raktár adatlekérő</div>

        <div style="width: 100%; min-height: 85px;">
          <div style="display: inline; float: left;">
            <p>Cikkszám: </p>
            <input type="text" id="item_id_foil_warehouse" placeholder="Cikkszám..." onkeyup="SyncItemID(this.value);" onkeydown="if (event.keyCode == 13) {SearchFoilItem();}" autocomplete="off" style="width: 147px; height: 17px;">
          </div><div style="display: inline; float: left; padding-left: 15px;">
            <p style="color: #f5f5f5;">: </p>
            <button onclick="SearchFoilItem();">Lekérés</button>
          </div>
        </div>

        <br clear="all"><br>
        <div class="form-desc">Írja be a keresett cikkszámot és kérje le az adatokat</div>

        <div id="result_div_foil" class="clearfix" style="display: none; visibility: invisible;">

          <div style="width: 100%; margin-left: 10px; margin-top: 10px; display: inline; float: left;">
            <div class="tables" style="width: 100%">
              <table id="table_foil">
                <thead>
                  <tr style="top: 0px; position: sticky; z-index: 1;">
                    <th style="background-color: #ddd; width: 75px; color: #333; border: none; text-align: center;">Helye</th>
                    <th style="width: 250px; text-align: center;">Bal oldal <span style="opacity: 0.6; font-size: small;">db</span></th>
                    <th style="width: 250px; text-align: center;">Jobb oldal <span style="opacity: 0.6; font-size: small;">db</span></th>
                  </tr>
                </thead>

                <tbody>
                </tbody>
              </table>
            </div>
          </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 ActiveCategory = "warranty";
    var IsIframe = <?php echo isset($_GET["iframe"]) ? 'true' : 'false'; ?>;

    function switchCategory(element, categoryId) {
      document.querySelectorAll('.category-tab').forEach(tab => tab.classList.remove('active'));
      element.classList.add('active');

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

      ActiveCategory = categoryId;

      sendHeight();
    }

    /* Doboz */
    function SearchWarehouse() {
      Loading();

      var item_id = document.getElementById("filter-item_id").value;
      var location = document.getElementById("filter-location").value;
      var amount = document.getElementById("filter-amount").value;

      const body = 'func=SearchWarehouse&item_id=' + encodeURIComponent(item_id).replace(/%20/g, '+') + '&location=' + encodeURIComponent(location).replace(/%20/g, '+') + '&amount=' + amount;
      get_POST_information("wh_add.php", body, function(text) {
        let response = JSON.parse(text);
        Loading(false);
        if (response.result == "ok") {
          document.getElementById("result_div").style.display = "unset";
          document.getElementById("result_div").style.visibility = "visible";

          var table = document.getElementById('table').getElementsByTagName('tbody')[0];
          table.innerHTML = "";
          const data = response.toplace;
          data.forEach(item => {
            const warehouse_loc = item.warehouse_loc;
            const warehouse_code = item.warehouse_code;
            const warehouse_name = item.warehouse_name;
            const position = item.position;
            const placed = item.placed;
            const warehouse_id = item.warehouse_id;

            var PlaceCode = warehouse_code + NumberToABC(position.split(":")[0]) + padWithZero(position.split(":")[1]);

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

            var RowID = item_id+'-'+placed+'-'+warehouse_id+'-'+position;
            newRow.id = RowID;

            newCell_1.innerHTML = response.item_id;
            newCell_1.setAttribute('style', 'text-align: center; background-color: #f2f2f2; border: none; color: #818181; width: 100px;');

            newCell_2.innerHTML = placed;
            newCell_2.style.padding = "8px 16px";

            newCell_5.innerHTML = PlaceCode;
            newCell_5.style.cursor = "pointer";
            newCell_5.title = warehouse_loc + " / " + warehouse_name + " / " + NumberToABC(position.split(":")[0]) + ":" + padWithZero(position.split(":")[1]);
            newCell_5.setAttribute('ondblclick', 'CreateAlertBox("Raktár hely", "<p>"+ this.title +"</p>");');
            newCell_5.style.padding = "8px 16px";

            newCell_6.innerHTML = "<span style='color: var(--panelcolor); cursor: pointer;' onclick='PlaceIntoWarehouse(\""+response.item_id+"\", \""+placed+"\", \""+warehouse_id+"\", \""+position+"\", \""+RowID+"\")'>Elhelyeztem</span>";

          });

          if (response.amount_left != 0) {
            GenerateAlerts("warning", "Nem sikerült elhelyezni " + response.amount_left + " elemet!", false);
          }

          sendHeight();

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

    }
    var InSavingProgress = [];
    function PlaceIntoWarehouse(item_id, placed, warehouse_id, position, RowID = "") {
      if (InSavingProgress.includes(RowID)) {
        GenerateAlerts("info", "Mentés folyamatban...");
      } else {
        InSavingProgress.push(RowID);
        var reason = "<?php echo $_GET["reason"] ?? ''; ?>";
        const body = 'func=PlaceIntoWarehouse&item_id=' + encodeURIComponent(item_id).replace(/%20/g, '+') + '&placed=' + placed + '&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);
          if (response.result == "ok") {
            if (RowID != "") {
              const index = InSavingProgress.indexOf(RowID);
              if (index > -1) {
                InSavingProgress.splice(index, 1);
              }
              document.getElementById(RowID).classList.add('strike-row');
            }
            window.parent.postMessage({ iframeBox: placed }, '*');
          } else {
            GenerateAlerts("error", response.result);
          }
        }, function() {
          Loading(false);
          GenerateAlerts("error", "Hálózati hiba!");
        });
      }
    }

    /* Foliás */
    function SearchFoilItem() {
      Loading();
      var item_id = document.getElementById("item_id_foil_warehouse").value;
      const body = 'func=SearchFoilItem&item_id=' + encodeURIComponent(item_id).replace(/%20/g, '+');
      get_POST_information("warehouse.php", body, function(text) {
        Loading(false);
        let response = JSON.parse(text);
        if (response.result == "ok") {

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

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

          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 newRow = table.insertRow();
            var newCell_2 = newRow.insertCell(0);
            var newCell_3 = newRow.insertCell(1);
            var newCell_4 = newRow.insertCell(2);


            newCell_2.innerHTML = warehouse.place;
            newCell_2.setAttribute('style', 'text-align: center; background-color: #f2f2f2; border: none; color: #818181; width: 75px;');

            newCell_3.innerHTML = `
              <button class="plusbtn" onclick="EditFoilItem(1, 0, ${warehouse.wid});">+1</button>
              <button class="plusbtn" onclick="EditFoilItem(10, 0, ${warehouse.wid});">+10</button>
              <span style="display: inline-block; width: calc(93% / 5); text-align: center; font-weight: bold;">${warehouse.left_db}</span>
              <button class="minusbtn" onclick="EditFoilItem(-1, 0, ${warehouse.wid});" id="right_minus_btn_foil_warehouse_${index}" ${leftDisabled}>-1</button>
              <button class="minusbtn" onclick="EditFoilItem(-10, 0, ${warehouse.wid});" id="right_minus_btn_foil_warehouse_${index}" ${left10Disabled}>-10</button>`;
            newCell_3.style.padding = "5px 0px";

            newCell_4.innerHTML = `
              <button class="plusbtn" onclick="EditFoilItem(0, 1, ${warehouse.wid});">+1</button>
              <button class="plusbtn" onclick="EditFoilItem(0, 10, ${warehouse.wid});">+10</button>
              <span style="display: inline-block; width: calc(93% / 5); text-align: center; font-weight: bold;">${warehouse.right_db}</span>
              <button class="minusbtn" onclick="EditFoilItem(0, -1, ${warehouse.wid});" id="right_minus_btn_foil_warehouse_${index}" ${rightDisabled}>-1</button>
              <button class="minusbtn" onclick="EditFoilItem(0, -10, ${warehouse.wid});" id="right_minus_btn_foil_warehouse_${index}" ${right10Disabled}>-10</button>`;
            newCell_4.style.padding = "5px 0px";

          });

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

          sendHeight();

        } else {
          GenerateAlerts("error", response.result);
        }
      }, function() {
        Loading(false);
        GenerateAlerts("error", "Hálózati hiba!");
      });
    }
    function EditFoilItem(left, right, wid) {
      Loading();
      var reason = "<?php echo $_GET["reason"] ?? ''; ?>";
      const body = 'func=EditFoilItem&left=' + left + '&right=' + right + '&wid=' + wid + '&reason=' + encodeURIComponent(reason).replace(/%20/g, '+');
      get_POST_information("warehouse.php", body, function(text) {
        let response = JSON.parse(text);
        if (response.result != "ok") {
          GenerateAlerts("error", response.result);
        } else {
          window.parent.postMessage({ iframeLeft: left }, '*');
          window.parent.postMessage({ iframeRight: right }, '*');
          document.getElementById("item_id_foil_warehouse").value = response.item_id;
          SearchFoilItem();
        }
      }, function() {
        GenerateAlerts("error", "Hálózati hiba!");
      });
    }

    /* Egyéb */
    function SyncItemID(item_id) {
      if (<?php echo isset($_GET["item_id"]) ? 'true' : 'false'; ?>) {
        item_id = "<?php echo $_GET["item_id"] ?? ''; ?>";

        document.getElementById("filter-item_id").value = item_id;
        document.getElementById("item_id_foil_warehouse").value = item_id;

        document.getElementById("filter-item_id").disabled = true;
        document.getElementById("item_id_foil_warehouse").disabled = true;

        SearchFoilItem();
      } else {
        document.getElementById("filter-item_id").value = item_id;
        document.getElementById("item_id_foil_warehouse").value = item_id;

        document.getElementById("result_div").style.display = "none";
        document.getElementById("result_div").style.visibility = "hidden";

        document.getElementById("result_div_foil").style.display = "none";
        document.getElementById("result_div_foil").style.visibility = "hidden";
      }

    }
    SyncItemID('');

    function sendHeight(height = null) {
      var c_height = height;
      if (IsIframe) {
        if (c_height == null) {
          c_height = document.querySelector('.content').scrollHeight;
        }
        window.parent.postMessage({ iframeHeight: c_height }, '*');
      }
    }
    if (IsIframe) {

      const content = document.querySelector('.content');
      document.body.style.height = "unset";
      document.documentElement.style.height = "unset";

      content.style.marginLeft = "15px";
      content.style.marginRight = "15px";
      content.style.width = "calc(100% - 30px)";
      content.style.position = "absolute";

      var allowed_functions = '<?php echo isset($_GET["functions"]) ? $_GET["functions"] : ''; ?>';
      var functions = allowed_functions.split(',');
      functions = functions.filter(item => item === 'box' || item === 'foil');

      if (functions.length == 0) {
        sendHeight(0);
        document.getElementById("category_tab_box").style.display = 'none';
        document.getElementById("category_tab_foil").style.display = 'none';
        document.getElementById("box").style.display = 'none';
        document.getElementById("foil").style.display = 'none';
      } else {
        if (!functions.includes('box')) {
          document.getElementById("category_tab_box").style.display = 'none';
          document.getElementById("box").style.display = 'none';
          document.getElementById("category_tab_foil").click();
        }
        if (!functions.includes('foil')) {
          document.getElementById("category_tab_foil").style.display = 'none';
          document.getElementById("foil").style.display = 'none';
        }

        sendHeight();
      }
    }

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