<?php

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

if (!(UserHasPerm('removal_from_warehouse') || UserHasPerm('warehouse_reservation') || UserHasPerm('warehouse_reservation_order'))) {
  StopAndDie();
}

if (isset($_POST["func"])) {
  if (htmlspecialchars($_POST["func"]) == "table") {
  	$maxperpage = isset($_POST['perpage']) ? intval($_POST['perpage']) : 25;
  	$cpage = intval(htmlspecialchars($_POST['cpage'] ?? 1));
  	$reason = htmlspecialchars($_POST['reason'] ?? '');
    $fulfill = htmlspecialchars($_POST['fulfill'] ?? 'ALL');
  	$orderby = htmlspecialchars($_POST['orderby'] ?? 'LAST');
    $is_active = htmlspecialchars($_POST['is_active'] ?? '1');

    $date = '';
    if (!empty($_POST['date'])) {
      $date_raw = htmlspecialchars($_POST['date']);
      if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $date_raw)) {
        $date = $date_raw;
      }
    }

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

    if ($is_active == "1") {
      $is_active = "is_active = 1";
      $return_is_active = 1;
    } else {
      $is_active = "is_active = 0";
      $return_is_active = 0;
    }
  	$where = "WHERE ".$is_active;
  	if ($reason !== '') {
  		$where .= " AND reason LIKE '%" . $conn->real_escape_string($reason) . "%'";
  	}

    if ($date !== '') {
  		$where .= " AND DATE(FROM_UNIXTIME(date_create)) = '$date'";
  	}

  	$countSql = "SELECT COUNT(DISTINCT CONCAT(reason, '|', DATE(FROM_UNIXTIME(date_create)))) FROM warehouse_reservation $where";
  	$countRes = $conn->query($countSql);
  	$totalReasons = $countRes->fetch_row()[0];
  	$maxpage = ($totalReasons > 0) ? ceil($totalReasons / $maxperpage) : 1;
  	if ($cpage < 1 || $cpage > $maxpage) {
  		$cpage = 1;
  	}
  	$offset = ($cpage - 1) * $maxperpage;

  	$orderbySQL = 'ORDER BY reason ASC, DATE(FROM_UNIXTIME(date_create)) ASC';
  	switch ($orderby) {
  		case 'CBA':
  			$orderbySQL = 'ORDER BY reason DESC, DATE(FROM_UNIXTIME(date_create)) ASC';
  			break;

  		case 'FIRST':
  			$orderbySQL = 'ORDER BY DATE(FROM_UNIXTIME(date_create)) ASC, reason';
  			break;

  		case 'LAST':
  			$orderbySQL = 'ORDER BY DATE(FROM_UNIXTIME(date_create)) DESC, reason';
  			break;

  		case 'ABC':
  		default:
  			$orderbySQL = 'ORDER BY reason ASC, DATE(FROM_UNIXTIME(date_create)) ASC';
  			break;
  	}

  	$sql_reasons = "SELECT DISTINCT reason, DATE(FROM_UNIXTIME(date_create)) as order_date FROM warehouse_reservation $where $orderbySQL LIMIT ? OFFSET ?";

  	$stmt1 = $conn->prepare($sql_reasons);
  	$stmt1->bind_param('ii', $maxperpage, $offset);
  	$stmt1->execute();
  	$res1 = $stmt1->get_result();

  	$reason_date_combinations = [];
  	while ($row = $res1->fetch_assoc()) {
  		$reason_date_combinations[] = [
  			'reason' => $row['reason'],
  			'order_date' => $row['order_date']
  		];
  	}

  	if (empty($reason_date_combinations)) {
  		echo json_encode([
  			'result' => 'ok',
  			'cpage' => $cpage,
  			'maxpage' => $maxpage,
  			'data' => []
  		], JSON_UNESCAPED_UNICODE|JSON_NUMERIC_CHECK);
  		exit;
  	}

  	$conditions = [];
  	$bind_params = [];
  	foreach ($reason_date_combinations as $combo) {
  		$conditions[] = "(reason = ? AND DATE(FROM_UNIXTIME(date_create)) = ?)";
  		$bind_params[] = $combo['reason'];
  		$bind_params[] = $combo['order_date'];
  	}

  	$sql_items = "
  		SELECT reason, reserv_id, item_id, amount, date_create, taken_out,
  		DATE(FROM_UNIXTIME(date_create)) as order_date
  		FROM warehouse_reservation
  		WHERE $is_active
  		AND (" . implode(' OR ', $conditions) . ")
  		$orderbySQL, item_id
  	";

  	$stmt2 = $conn->prepare($sql_items);
  	$types = str_repeat('s', count($bind_params));
  	$stmt2->bind_param($types, ...$bind_params);
  	$stmt2->execute();
  	$res2 = $stmt2->get_result();

  	$data = [];
  	while ($row = $res2->fetch_assoc()) {
  		$key = $row['reason'] . '|' . $row['order_date'];
  		$item_id = $row['item_id'];
  		$amount = intval($row['amount']);

  		if (!isset($data[$key])) {
  			$data[$key] = [
  				'megrendelo' => $row['reason'] . ' <small style="opacity: 0.6; margin-left: 10px;">' . str_replace('-', '. ', $row['order_date']) . '.</small>',
  				'rendelesek' => []
  			];
  		}

  		$found = false;
  		foreach ($data[$key]['rendelesek'] as &$rendeles) {
  			if ($rendeles['cikkszam'] === $item_id) {
  				$rendeles['mennyiseg'] += $amount;
  				$rendeles['total_taken'] += intval($row['taken_out']);
  				$found = true;
  				break;
  			}
  		}
  		unset($rendeles);

  		if (!$found) {
  			$data[$key]['rendelesek'][] = [
  				'cikkszam' => $item_id,
  				'mennyiseg' => $amount,
  				'total_taken' => intval($row['taken_out']),
  				'levetel' => $coderclass->encode($row['reason'] . '|' . $row['order_date'], "SZ4TUN4")
  			];
  		}
  	}

  	$instock = [];

    $hidden = 0;

  	foreach ($data as $index => &$megrendelo) {
      $OrderCount = 0;
      $InsufficientStockCount = 0;

  		$hasInProcess = false;

  		foreach ($megrendelo['rendelesek'] as &$rendeles) {
  			$item_id = $rendeles['cikkszam'];
  			$required_amount = $rendeles['mennyiseg'];
  			$taken_amount = $rendeles['total_taken'];
  			$remaining_amount = $required_amount - $taken_amount;

  			if ($rendeles['total_taken'] > 0) {
  				$hasInProcess = true;
  			}

  			if (!isset($instock[$item_id])) {
          $sql = mysqli_query($conn,"SELECT saleable_quantity FROM statistics_daily WHERE item_id = '$item_id'");
          $result = mysqli_fetch_array($sql);
          if ($result == null) {
            $sql = mysqli_query($conn, "SELECT SUM(amount) AS total_amount FROM warehouse WHERE item_id = '$item_id' GROUP BY item_id");
            $result = mysqli_fetch_array($sql);
          }
  				$instock[$item_id] = $result ? intval($result[0]) : 0;
  			}

  			$available_stock = $instock[$item_id];
  			$free_space = $available_stock - $remaining_amount;

        $OrderCount++;

  			if ($free_space < 0) {
  				$InsufficientStockCount++;
  				$shortage = abs($free_space);
          if ($is_active != "is_active = 0") {
            $rendeles['cikkszam'] .= "<i class='icon' title='Nincsen elegendő termék a raktárban! " . $shortage . " db termék hiányzik!'><i data-feather='alert-octagon'></i></i>";
          }
  			}
  		}
  		unset($rendeles);

  		if ($hasInProcess && $is_active != "is_active = 0") {
  			$megrendelo['megrendelo'] .= "<i class='icon' title='Folyamatban lévő kiszedés' style='color: var(--toppanel);'><i data-feather='loader'></i></i>";
  		}

      $hasInsufficientStock = false;
      if ($InsufficientStockCount != 0) {
        $hasInsufficientStock = true;
      }

  		if ($hasInsufficientStock && $hasInProcess && $is_active != "is_active = 0") {
        if ($InsufficientStockCount == $OrderCount) {
          $megrendelo['megrendelo'] .= "<i class='icon' title='A rendelés nem teljesíthető!' style='color: #FF0000; margin-left: 38px;'><i data-feather='alert-triangle'></i></i>";
          if (!in_array($fulfill, ['ALL', 'NOFULFILL'])) {
              unset($data[$index]);
              $hidden++;
          }
        } else {
          $megrendelo['megrendelo'] .= "<i class='icon' title='A rendelés részben nem teljesíthető!' style='color: #FF4D00; margin-left: 38px;'><i data-feather='alert-octagon'></i></i>";
          if (!in_array($fulfill, ['ALL', 'PARTFULFILL'])) {
              unset($data[$index]);
              $hidden++;
          }
        }
  		} else if ($hasInsufficientStock && $is_active != "is_active = 0") {
        if ($InsufficientStockCount == $OrderCount) {
          $megrendelo['megrendelo'] .= "<i class='icon' title='A rendelés nem teljesíthető!' style='color: #FF0000;'><i data-feather='alert-triangle'></i></i>";
          if (!in_array($fulfill, ['ALL', 'NOFULFILL'])) {
              unset($data[$index]);
              $hidden++;
          }
        } else {
          $megrendelo['megrendelo'] .= "<i class='icon' title='A rendelés részben nem teljesíthető!' style='color: #FF4D00;'><i data-feather='alert-octagon'></i></i>";
          if (!in_array($fulfill, ['ALL', 'PARTFULFILL'])) {
              unset($data[$index]);
              $hidden++;
          }
        }
  		} else if (!$hasInsufficientStock && !$hasInProcess && $is_active != "is_active = 0") {
        $megrendelo['megrendelo'] .= "<i class='icon' title='Teljesíthető rendelés' style='color: #15954b;'><i data-feather='check-circle'></i></i>";
        if (!in_array($fulfill, ['ALL', 'CANFULFILL'])) {
            unset($data[$index]);
            $hidden++;
        }
      }

  	}
  	unset($megrendelo);

  	$output = array_values($data);

  	header('Content-Type: application/json; charset=utf-8');
  	echo json_encode([
  		'result' => 'ok',
  		'cpage' => $cpage,
  		'maxpage' => $maxpage,
      'is_active' => $return_is_active,
      'hidden' => $hidden,
  		'data' => $output
  	], JSON_UNESCAPED_UNICODE|JSON_NUMERIC_CHECK);


  } else if (htmlspecialchars($_POST["func"]) == "Generatepicking_list") {
    require_once __DIR__ . '/../managers/OrderProcessor.php';

  	// Input adat előkészítése
  	$inputData = [];

  	// Manual pick feldolgozása
  	$manualPickRaw = $_POST["manual_pick"] ?? "";

  	if ($manualPickRaw !== "") {
  		$tmp = json_decode($manualPickRaw, true);
  		if (is_array($tmp)) {
  			$manualPick = [];

  			foreach ($tmp as $row) {
  				if (!isset($row["item_id"], $row["amount"], $row["primary_source"], $row["amount_type"])) {
  					continue;
  				}

  				$itemId = htmlspecialchars(str_replace(' ', '+', trim($row["item_id"])));
  				$amt = intval($row["amount"]);
  				$primarySource = intval(trim($row["primary_source"]));
  				$amountType = intval(trim($row["amount_type"]));

  				if ($itemId === "" || $amt <= 0) {
  					continue;
  				}

  				$manualPick[] = [
  					"item_id" => $itemId,
  					"amount" => $amt,
  					"primary_source" => $primarySource,
  					"amount_type" => $amountType
  				];
  			}

  			if (!empty($manualPick)) {
  				$inputData['manual'] = $manualPick;
  			}
  		}
  	}

  	// Reason mód (ha nem manual)
  	if (empty($inputData) && isset($_POST['reason'])) {
  		$inputData['reason'] = $_POST['reason'];
  	}

  	// Generálás
  	$result = PickingListGenerator::generate($conn, $inputData, $coderclass);

  	// JSON kiírás
  	echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_NUMERIC_CHECK);
  } else if (htmlspecialchars($_POST["func"]) == "RemoveFromWarehouse") {
  	require_once __DIR__ . '/../managers/OrderProcessor.php';

  	$inputData = [
  		'wid' => $_POST['wid'] ?? '',
  		'amount' => $_POST['amount'] ?? '',
  		'item_id' => $_POST['item_id'] ?? '',
  		'corrigate' => $_POST['corrigate'] ?? 'false',
  		'overal_order_id' => $_POST['overal_order_id'] ?? '',
  		'reason' => $_POST['reason'] ?? ''
  	];

  	$result = WarehouseRemover::remove($conn, $inputData, $coderclass);

    echo json_encode($result, JSON_UNESCAPED_UNICODE);

    /* LOG-olás */
    $amount = $_POST['amount'] ?? '0';
    $amount_left = $amount;
    $amount_right = $amount;
    if (substr($amount, 0, 1) == "J") {
      $amount_left = 0;
      $amount_right = substr($amount, 1);
    } else if (substr($amount, 0, 1) == "B") {
      $amount_left = substr($amount, 1);
      $amount_right = 0;
    }

    $encoded = htmlspecialchars($_POST['reason'] ?? '');
    $to_place = $coderclass->decode($encoded, "SZ4TUN4");

    $loggerclass->writeLogWarehouse(['reason' => 'Kivét rendelés miatt', 'reason_code' => 1,
        'item_id' => $_POST['item_id'],
        'from_place' => $_POST['tcHely'],
        'to_place' => $to_place,
        'amount_left' => intval($amount_left),
        'amount_right' => intval($amount_right)
      ]);

  } else if (htmlspecialchars($_POST["func"]) == "Summarizepicking_list") {
    $encoded = htmlspecialchars($_POST['reason'] ?? '');
    $is_active = intval(htmlspecialchars($_POST['is_active'] ?? 1));
    $decoded = $coderclass->decode($encoded, "SZ4TUN4");
    $parts = explode('|', $decoded);
    if (count($parts) !== 2) {
      echo json_encode(['result'=>'error','message'=>'Érvénytelen azonosító'], JSON_UNESCAPED_UNICODE);
      exit;
    }
    $reason = $parts[0];
    $order_date = $parts[1];

    $sql = "
      SELECT
        IFNULL(order_id,'')   AS order_id,
        IFNULL(order_name,'') AS order_name,
        IFNULL(order_mail,'') AS order_mail,
        item_id,
        amount,
        taken_out,
        is_active
      FROM warehouse_reservation
      WHERE reason = ?
        AND DATE(FROM_UNIXTIME(date_create)) = ? AND is_active = ?
      ORDER BY order_name, order_id, item_id
    ";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('ssi', $reason, $order_date, $is_active);
    $stmt->execute();
    $res = $stmt->get_result();

    $lists = [];
    $is_active = null;
    while ($r = $res->fetch_assoc()) {
      $is_active = $r['is_active'];
      $hasOrder = $r['order_id'] !== '' || $r['order_name'] !== '' || $r['order_mail'] !== '';
      if ($hasOrder) {
        $key = $r['order_id'].'|'.$r['order_name'].'|'.$r['order_mail'];
        $label = $r['order_name'].' - '.$r['order_id'];
      } else {
        $key = 'maradek';
        $label = '!&maradek&! ';
      }

      if (!isset($lists[$key])) {
        $lists[$key] = [
          'overal_order_id' => $label,
          'picking_list' => []
        ];
      }

      if (intval($r['taken_out']) > 0) {
        $lists[$key]['picking_list'][] = [
          'wid' => 0,
          'item_id' => $r['item_id'],
          'amount' => intval($r['taken_out'])
        ];
      }

      $remaining = intval($r['amount']) - intval($r['taken_out']);
      if ($remaining > 0) {
        $lists[$key]['picking_list'][] = [
          'wid' => -1,
          'item_id' => $r['item_id'],
          'amount' => $remaining
        ];
      }
    }
    $stmt->close();

    $all = array_values($lists);

    echo json_encode([
      'result' => 'ok',
      'is_active' => $is_active,
      'reason' => $reason,
      'date' => $order_date,
      'all_picking_lists'  => $all
    ], JSON_UNESCAPED_UNICODE|JSON_NUMERIC_CHECK);

  } else if (htmlspecialchars($_POST["func"]) == "CopyExcel") {
    $encoded = htmlspecialchars($_POST['reason'] ?? '');
    $decoded = $coderclass->decode($encoded, "SZ4TUN4");
    $parts = explode('|', $decoded);
    if (count($parts) !== 2) {
      echo json_encode(['result'=>'error','message'=>'Érvénytelen azonosító'], JSON_UNESCAPED_UNICODE);
      exit;
    }
    $reason = $parts[0];
    $order_date = $parts[1];

    $sql = "
      SELECT
        IFNULL(order_id,'')   AS order_id,
        IFNULL(order_name,'') AS order_name,
        IFNULL(order_mail,'') AS order_mail,
        item_id,
        amount,
        taken_out,
        is_active
      FROM warehouse_reservation
      WHERE reason = ?
        AND DATE(FROM_UNIXTIME(date_create)) = ?
      ORDER BY order_name, order_id, item_id
    ";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('ss', $reason, $order_date);
    $stmt->execute();
    $res = $stmt->get_result();

    $lists = [];
    $is_active = null;
    while ($r = $res->fetch_assoc()) {
      $is_active = $r['is_active'];
      $hasOrder = $r['order_id'] !== '' || $r['order_name'] !== '' || $r['order_mail'] !== '';
      if ($hasOrder) {
        $key = $r['order_id'].'|'.$r['order_name'].'|'.$r['order_mail'];
      } else {
        $key = 'maradek';
      }

      if (!isset($lists[$key])) {
        if ($hasOrder) {
          $lists[$key] = [
            'order_id' => $r['order_id'],
            'order_name' => $r['order_name'],
            'order_mail' => $r['order_mail'],
            'picking_list' => []
          ];
        } else {
          $lists[$key] = [
            'order_id' => $label,
            'order_name' => $label,
            'order_mail' => $label,
            'picking_list' => []
          ];
        }
      }

      if (intval($r['taken_out']) > 0) {
        $lists[$key]['picking_list'][] = [
          'wid' => 0,
          'item_id' => $r['item_id'],
          'amount' => intval($r['taken_out'])
        ];
      }
    }
    $stmt->close();

    $lists = array_filter($lists, function($list) {
      return !empty($list['picking_list']);
    });
    $all = array_values($lists);

    echo json_encode([
      'result' => 'ok',
      'is_active' => $is_active,
      'reason' => $reason,
      'date' => $order_date,
      'all_picking_lists'  => $all
    ], JSON_UNESCAPED_UNICODE|JSON_NUMERIC_CHECK);

  } else if (htmlspecialchars($_POST["func"]) == "Closepicking_list") {
    $mode = intval($_POST['mode']);
    $encoded = htmlspecialchars($_POST['reason'] ?? '');
    $decoded = $coderclass->decode($encoded, "SZ4TUN4");
    $parts = explode('|', $decoded);

    if (count($parts) !== 2) {
      echo json_encode(['result'=>'error','message'=>'Érvénytelen azonosító'], JSON_UNESCAPED_UNICODE);
      exit;
    }

    $reason = $parts[0];
    $order_date = $parts[1];

    // 1. Lekérdezzük az eredeti rekordok reserv_id-jeit
    $sql_orig = "
      SELECT reserv_id
      FROM warehouse_reservation
      WHERE reason = ?
        AND DATE(FROM_UNIXTIME(date_create)) = ?
        AND is_active = 1
    ";
    $stmt_orig = $conn->prepare($sql_orig);
    $stmt_orig->bind_param('ss', $reason, $order_date);
    $stmt_orig->execute();
    $res_orig = $stmt_orig->get_result();

    $orig_ids = [];
    while ($row = $res_orig->fetch_assoc()) {
      $orig_ids[] = $row['reserv_id'];
    }
    $stmt_orig->close();

    if ($mode === 0) {
      // MODE 0: Csak eredeti rendelések lezárása
      if (!empty($orig_ids)) {
        $date_end = time();
        $placeholders = implode(',', array_fill(0, count($orig_ids), '?'));
        $types = str_repeat('i', count($orig_ids));
        $sql_close = "UPDATE warehouse_reservation SET is_active = 0, date_end = $date_end WHERE reserv_id IN ($placeholders)";
        $stmt_close = $conn->prepare($sql_close);
        $stmt_close->bind_param($types, ...$orig_ids);
        $stmt_close->execute();
        $stmt_close->close();
      }
      echo json_encode(['result'=>'ok','message'=>'Rendelések lezárva'], JSON_UNESCAPED_UNICODE);
    } else {

      // MODE 1 és 2: Újrarendelés logika
      $sql = "
          SELECT item_id, order_id, order_name, order_mail, (amount - taken_out) AS remaining, receipt_method, note, primary_source, amount_type, note
          FROM warehouse_reservation
          WHERE reason = ?
            AND DATE(FROM_UNIXTIME(date_create)) = ?
            AND is_active = 1
            AND (amount - taken_out) > 0
      ";
      $stmt = $conn->prepare($sql);
      $stmt->bind_param('ss', $reason, $order_date);
      $stmt->execute();
      $res = $stmt->get_result();

      $new_reservations = [];
      while ($row = $res->fetch_assoc()) {
        $new_reservations[] = $row;
      }
      $stmt->close();

      if (empty($new_reservations)) {
        // Ha nincs újrarendelendő tétel, csak az eredeti rekordok lezárása
        if (!empty($orig_ids)) {
          $placeholders = implode(',', array_fill(0, count($orig_ids), '?'));
          $types = str_repeat('i', count($orig_ids));
          $date_end = time();
          $sql_close = "UPDATE warehouse_reservation SET is_active = 0, date_end = $date_end WHERE reserv_id IN ($placeholders)";
          $stmt_close = $conn->prepare($sql_close);
          $stmt_close->bind_param($types, ...$orig_ids);
          $stmt_close->execute();
          $stmt_close->close();
        }
        echo json_encode(['result'=>'ok','message'=>'Nincs újrarendelendő tétel, rendelések lezárva'], JSON_UNESCAPED_UNICODE);
      } else {
        // Beszúrjuk az újrarendelt tételeket
        if ($order_date === date('Y-m-d', time())) {
        	$current_time = time() + 24 * 60 * 60;
        } else {
        	$current_time = time();
        }

        $success_count = 0;
        foreach ($new_reservations as $item) {
          $sql_insert = "
            INSERT INTO warehouse_reservation
              (item_id, amount, taken_out, reason, date_create, is_active, order_id, order_name, order_mail, receipt_method, note, primary_source, amount_type)
            VALUES (?, ?, 0, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?)
          ";
          $stmt_insert = $conn->prepare($sql_insert);

          $savingReason = $reason;

          if ($item['order_name'] != "" && strpos($reason, " - ") === false) {
            $savingReason .= " - ".$item['order_name'];
          }

          $stmt_insert->bind_param(
            'sisisssssii',
            $item['item_id'],
            $item['remaining'],
            $savingReason,
            $current_time,
            $item['order_id'],
            $item['order_name'],
            $item['order_mail'],
            $item['receipt_method'],
            $item['note'],
            $item['primary_source'],
            $item['amount_type']
          );
          if ($stmt_insert->execute()) {
            $success_count++;
          }
          $stmt_insert->close();
        }

        // MODE 2: Email értesítés a hiányzókról
        $sent_count = 0;
        if ($mode === 2) {
          $missing_items = [];
          foreach ($new_reservations as $row) {
            $email = trim($row['order_mail']);
            if ($email !== '') {
              if (!isset($missing_items[$email])) {
                $missing_items[$email] = [
                  'name' => $row['order_name'],
                  'order_id' => $row['order_id'],
                  'items' => []
                ];
              }
              $missing_items[$email]['items'][] = [
                'item_id'   => $row['item_id'],
                'remaining' => $row['remaining']
              ];
            }
          }
          if (!empty($missing_items) && file_exists(__DIR__ . '/../managers/mail.php')) {
            require_once __DIR__ . '/../managers/mail.php';
            if (function_exists('sendFormattedEmail')) {
              foreach ($missing_items as $email => $data) {

                $c_order_id = $data['order_id'];
                $c_mail = $email;
                $c_name = $data['name'];
                $subject = "Rendelése nem teljesíthető - " . $c_order_id . " / Out of stock - ". $c_order_id;

                /* MAGYAR */

                $content  = "<h2>Kedves " . htmlspecialchars($c_name) . "!</h2>";
                $content .= "Köszönjük a rendelését!<br><br>Sajnos az Ön által megrendelt légterelő jelenleg elfogyott, ezért most nem tudjuk feladni.<br>A termék várhatóan <strong>néhány héten belül</strong> újra raktárra kerül.";
                $content .= "<p>Az alábbi tételek nem állnak rendelkezésre a(z) <strong>". htmlspecialchars($c_order_id) . "</strong> rendelésből:</p>";
                $content .= "<table border='1' cellpadding='10' style='border-collapse:collapse;width:100%;'>";
                $content .= "<tr><th>Cikkszám</th><th>Hiányzó mennyiség</th></tr>";
                foreach ($data['items'] as $it) {
                  $content .= "<tr><td>" . htmlspecialchars($it['item_id']) . "</td>" . "<td>" . $it['remaining'] . " db</td></tr>";
                }
                $content .= "</table>";
                $content .= "<br><p><strong>Kérjük, kattintással jelezze felénk, hogyan szeretne tovább haladni:</strong></p>";

                $content .= '<a href="mailto:kapcsolat@szatuna.hu' .
                     '?subject=' . rawurlencode("Rendelés megtartása / Keeping order") .
                     '&body=' . rawurlencode("Megvárom, amíg a(z) '".$c_order_id."' szereplő cikkszámok újra elérhetőek nem lesznek.") .
                     '">Megvárom, amíg újra elérhető lesz</a><br>';
                $content .= '<a href="mailto:kapcsolat@szatuna.hu' .
                     '?subject=' . rawurlencode("Rendelés törlése / Cancel order") .
                     '&body=' . rawurlencode("Kérem a(z) '".$c_order_id."' rendelésem törlését.") .
                     '">Kérem a rendelés törlését</a>';

                $content .= "<br><p>Köszönjük megértését és türelmét!<br><br>Üdvözlettel,<br>Haluskai Csilla<br>ügyfélkapcsolat</p>";

                /* ANGOL */

                $content .= "<div style='border-top: 1px solid #eee; width: 100%; margin-top: 20px; margin-bottom: 20px;'></div>";

                $content .= "<h2>Dear " . htmlspecialchars($c_name) . "!</h2>";
                $content .= "Thank you for your order!<br><br>Unfortunately, the wind deflector you ordered is currently out of stock, so we are unable to ship it right now.<br>The product is expected to be available again in a <strong>few weeks</strong>.";
                $content .= "<p>The following items are not available from order no. <strong>". htmlspecialchars($c_order_id) . "</strong>:</p>";
                $content .= "<table border='1' cellpadding='10' style='border-collapse:collapse;width:100%;'>";
                $content .= "<tr><th>Item number</th><th>Quantity</th></tr>";
                foreach ($data['items'] as $it) {
                  $content .= "<tr><td>" . htmlspecialchars($it['item_id']) . "</td>" . "<td>" . $it['remaining'] . " db</td></tr>";
                }
                $content .= "</table>";
                $content .= "<br><p><strong>Please click below to let us know how you would like to proceed:</strong></p>";

                $content .= '<a href="mailto:kapcsolat@szatuna.hu' .
                     '?subject=' . rawurlencode("Rendelés megtartása / Keeping order") .
                     '&body=' . rawurlencode("I will wait until the item numbers listed under '".$c_order_id."' are available again.") .
                     '">I’m happy to wait until it’s back in stock</a><br>';
                $content .= '<a href="mailto:kapcsolat@szatuna.hu' .
                     '?subject=' . rawurlencode("Rendelés törlése / Cancel order") .
                     '&body=' . rawurlencode("Please cancel my order '".$c_order_id."'.") .
                     '">I would like to cancel my order</a>';

                $content .= "<br><p>Thank you for your understanding!<br><br>Kind regards,<br>Csilla Haluskai<br>customer relations manager</p>";

                $res_mail = sendFormattedEmail($email, $data['name'], $subject, $content);
                if ($res_mail['success']) {
                  $sent_count++;
                }
              }
            } else {
              echo json_encode(['result'=>'error','message'=>'sendFormattedEmail nincs definiálva'], JSON_UNESCAPED_UNICODE);
              exit;
            }
          }
        }

        if (!empty($orig_ids)) {
          $placeholders = implode(',', array_fill(0, count($orig_ids), '?'));
          $types = str_repeat('i', count($orig_ids));
          $date_end = time();
          $sql_close = "UPDATE warehouse_reservation SET is_active = 0, date_end = $date_end WHERE reserv_id IN ($placeholders)";
          $stmt_close = $conn->prepare($sql_close);
          $stmt_close->bind_param($types, ...$orig_ids);
          $stmt_close->execute();
          $stmt_close->close();
        }

        $message = "$success_count tétel újrarendelve";
        if ($mode === 2) {
          $message .= ", $sent_count email elküldve";
        }
        echo json_encode(['result'=>'ok','message'=>$message], JSON_UNESCAPED_UNICODE);

      }

    }
    /* Automata összeglő levél */

    $sql = "
      SELECT
        IFNULL(order_id,'')   AS order_id,
        IFNULL(order_name,'') AS order_name,
        IFNULL(order_mail,'') AS order_mail,
        item_id,
        amount,
        taken_out,
        receipt_method,
        note,
        is_active
      FROM warehouse_reservation
      WHERE reason = ?
        AND DATE(FROM_UNIXTIME(date_create)) = ?
      ORDER BY order_name, order_id, item_id
    ";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('ss', $reason, $order_date);
    $stmt->execute();
    $res = $stmt->get_result();

    $lists = [];
    $is_active = null;
    while ($r = $res->fetch_assoc()) {
      $is_active = $r['is_active'];
      $hasOrder = $r['order_id'] !== '' || $r['order_name'] !== '' || $r['order_mail'] !== '';
      if ($hasOrder) {
        $key = $r['order_id'].'|'.$r['order_name'].'|'.$r['order_mail'];
        $label = $r['order_name'].' - '.$r['order_id'];
      } else {
        $key = 'maradek';
        $label = '';
      }

      if (!isset($lists[$key])) {
        if ($hasOrder) {
          $lists[$key] = [
            'order_id' => $r['order_id'],
            'order_name' => $r['order_name'],
            'order_mail' => $r['order_mail'],
            'picking_list' => []
          ];
        } else {
          $lists[$key] = [
            'order_id' => $label,
            'order_name' => $label,
            'order_mail' => $label,
            'picking_list' => []
          ];
        }
      }

      if (intval($r['taken_out']) > 0) {
        $lists[$key]['picking_list'][] = [
          'wid' => 0,
          'item_id' => $r['item_id'],
          'receipt_method' => $r['receipt_method'],
          'note' => $r['note'],
          'amount' => intval($r['taken_out'])
        ];
      }
    }
    $stmt->close();

    $lists = array_filter($lists, function($list) {
      return !empty($list['picking_list']);
    });
    $all = array_values($lists);

    // HTML táblázat generálása a kimenetre
    $html_table = '<table border="1" cellpadding="4" cellspacing="0" style="border-collapse: collapse; width:100%;">';
    $html_table .= '<thead><tr>';
    $html_table .= '<th>Cikkszám</th><th>Mennyiség</th><th>Indok</th><th>Rendelés azonosító</th><th>Rendelés név</th><th>Rendelés e-mail</th><th>Átvételi mód</th><th>Megjegyzés</th>';
    $html_table .= '</tr></thead><tbody>';

    foreach ($all as $list) {
      foreach ($list['picking_list'] as $item) {
        $html_table .= '<tr>';
        $html_table .= '<td>' . htmlspecialchars($item['item_id']) . '</td>';
        $html_table .= '<td>' . htmlspecialchars($item['amount']) . '</td>';
        $html_table .= '<td>' . htmlspecialchars($reason) . '</td>';
        $html_table .= '<td>' . htmlspecialchars($list['order_id']) . '</td>';
        $html_table .= '<td>' . htmlspecialchars($list['order_name']) . '</td>';
        $html_table .= '<td>' . htmlspecialchars($list['order_mail']) . '</td>';
        $html_table .= '<td>' . htmlspecialchars($item['receipt_method']) . '</td>';
        $html_table .= '<td>' . htmlspecialchars($item['note']) . '</td>';
        $html_table .= '</tr>';
      }
    }

    $html_table .= '</tbody></table>';

    // Levél küldése

    if (!empty($html_table) && file_exists(__DIR__ . '/../managers/mail.php')) {
      require_once __DIR__ . '/../managers/mail.php';
      if (function_exists('sendFormattedEmail')) {
        $subject = "Lezárt rendelés - " . $reason;

        $content  = "<h2>Tisztelt címzett!</h2>";
        $content .= "<p>Az alábbi tételek kerültek kiadásra a(z) <strong>". $reason . "</strong> (" . str_replace('-', '. ', $order_date) . ") rendelésből:</p>";
        $content .= $html_table;
        $content .= "<p>Az excelbe történő beillesztéshez jelölje ki a táblázatot, másolja ki majd illesze be egy excel-be</p>";
        $content .= "<p>Üdvözlettel,<br>Szaturnusz Rendszer</p>";

        $res_mail = sendFormattedEmail("rendeles@szatuna.hu", "Szatuna Kft", $subject, $content);

      } else {
        echo json_encode(['result'=>'error','message'=>'sendFormattedEmail nincs definiálva'], JSON_UNESCAPED_UNICODE);
        exit;
      }
    }

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

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

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

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

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

    echo $json;
  } else if (htmlspecialchars($_POST["func"]) == "openreport" && UserHasPerm('warehouse_reservation')) {
    $encoded = htmlspecialchars($_POST['reason'] ?? '');
    $decoded = $coderclass->decode($encoded, "SZ4TUN4");
    $parts = explode('|', $decoded);

    if (count($parts) !== 2) {
      echo json_encode(['result'=>'error','message'=>'Érvénytelen azonosító'], JSON_UNESCAPED_UNICODE);
      exit;
    }

    $reason = $parts[0];
    $order_date = $parts[1];

    $responseStr = '';
    $query = "SELECT * FROM warehouse_reservation WHERE reason = '$reason' and DATE(FROM_UNIXTIME(date_create)) = '$order_date' and is_active = 1";
    if ($result = $conn->query($query)) {
      while ($reserv_report = $result->fetch_assoc()) {

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

        $order_id = empty($reserv_report['order_id']) ? ' - ' : $reserv_report['order_id'];
        $order_name = empty($reserv_report['order_name']) ? ' - ' : $reserv_report['order_name'];
        $order_mail = empty($reserv_report['order_mail']) ? ' - ' : $reserv_report['order_mail'];

        $receipt_method = empty($reserv_report['receipt_method']) ? ' - ' : $reserv_report['receipt_method'];
        $order_note = empty($reserv_report['note']) ? ' - ' : $reserv_report['note'];
        $primary_source = empty($reserv_report['primary_source']) ? 0 : $reserv_report['primary_source'];
        $primary_warehouse = empty($reserv_report['primary_warehouse']) ? "FŐ" : $reserv_report['primary_warehouse'];

        $responseStr .= $reserv_report['reason'].'/!/'.$reserv_report['amount'].'/!/'.date("Y. m. d.", $reserv_report['date_create']).'/!/'.$reserv_report['reserv_id'].'/!/'.$order_id.'/!/'.$order_name.'/!/'.$order_mail.'/!/'.$reserv_report['item_id'].'/!/'.$receipt_method.'/!/'.$order_note.'/!/'.$primary_source.'/!/'.$primary_warehouse;
      }
    }

    echo '{"result": "ok", "data": "'.$responseStr.'", "name_in_db": "'.$reason.'", "date": "'.str_replace('-', '. ', $order_date).'."}';

  } else if (htmlspecialchars($_POST["func"]) == "reservitem" && UserHasPerm('warehouse_reservation_order')) {
    $item_id = htmlspecialchars(str_replace(' ', '+', $_POST['item_id']));
    $amount = intval(htmlspecialchars($_POST["amount"]));
    $reason = preg_replace('/[^a-zA-Z0-9áéíóöőúüűÁÉÍÓÖŐÚÜŰ .-]/u', '', htmlspecialchars($_POST["reason"]));

    $order_id = empty(htmlspecialchars($_POST["order_id"])) ? null : htmlspecialchars($_POST["order_id"]);
    $order_name = empty(htmlspecialchars($_POST["order_name"])) ? null : htmlspecialchars($_POST["order_name"]);
    $order_mail = empty(htmlspecialchars($_POST["order_mail"])) ? null : htmlspecialchars($_POST["order_mail"]);

    $primary_source = intval($_POST["primary_source"] ?? 0);
    $amount_type = intval($_POST["amount_type"] ?? 0);

    $receipt_method = filter_var($_POST["receipt_method"] ?? '', FILTER_SANITIZE_STRING) ?: null;  //Újfajta
    $primary_warehouse = filter_var($_POST["primary_warehouse"] ?? '', FILTER_SANITIZE_STRING) ?: null;
    $customer_type = filter_var($_POST["customer_type"] ?? '', FILTER_SANITIZE_STRING) ?: null;
    $note = empty(htmlspecialchars($_POST["note"])) ? null : htmlspecialchars($_POST["note"]);

    if ($reason == "") {
      echo json_encode(["result" => "Kötelező megadni egy megrendelőt vagy indoklásts!"]);
      exit();
    }

    if (!filter_var($amount, FILTER_VALIDATE_INT) || intval($amount) <= 0) {
      echo json_encode(["result" => "A mennyiség csak pozitív egész szám lehet!"]);
      exit();
    }

    $sql = mysqli_query($conn,"SELECT item_id FROM pr_parameters WHERE item_id = '$item_id'");
    $item_id_sql = mysqli_fetch_array($sql);
    if ($item_id_sql != null) {
      $item_id = $item_id_sql['item_id'];
    } else {
      echo json_encode(["result" => "Nem létező cikkszám lett megadva!"]);
      exit();
    }

    if (substr($item_id, 0, 2) !== "CL") {
      $sql = mysqli_query($conn,"SELECT size, foil_product_place 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] != "" || $pr_warehouse_parameters[1] != ""))) {
        if ($pr_warehouse_parameters == null) {
          echo json_encode(["result" => "Nem létező cikkszám lett megadva!"]);
        } else {
          echo json_encode(["result" => "A cikkszámhoz nem lett megadva doboz méret!"]);
        }
        exit();
      }
    }


    if ($order_mail != null) {
      $emails = array_map('trim', explode(',', $order_mail));
      foreach ($emails as $email) {
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
          echo json_encode(["result" => "Az e-mail cím helytelen formátumban van: " . $email]);
          exit();
        }
      }
    }


    $sql = mysqli_query($conn,"SELECT warehouse_total AS total_amount FROM statistics_daily WHERE item_id = '$item_id'");
    $total_amount_warehouse = mysqli_fetch_array($sql)[0];

    $test_space = intval($total_amount_warehouse) - $amount;

    $time = time();

    $sql = mysqli_query($conn,"SELECT reserv_id, amount FROM warehouse_reservation WHERE item_id = '$item_id' and reason = '$reason' and is_active = 1 and order_id = '$order_id' and order_name = '$order_name' and order_mail = '$order_mail' and DATE(FROM_UNIXTIME(date_create)) = CURDATE() and amount_type = $amount_type");
    $there_is_this_order = mysqli_fetch_array($sql);
    if ($there_is_this_order != null) {
      $new_amount = $amount + intval($there_is_this_order["amount"]);
      $reserv_id = $there_is_this_order['reserv_id'];
      $sql = mysqli_query($conn,"UPDATE warehouse_reservation SET amount = $new_amount, receipt_method = '$receipt_method', note = '$note', customer_type = '$customer_type', primary_warehouse = '$primary_warehouse', primary_source = $primary_source, amount_type = $amount_type WHERE reserv_id = '$reserv_id'");
    } else {
      $sql = mysqli_query($conn,"INSERT INTO warehouse_reservation(item_id, amount, reason, is_active, date_create, order_id, order_name, order_mail, receipt_method, note, primary_source, amount_type, primary_warehouse, customer_type) VALUES ('$item_id', $amount, '$reason', 1, $time, '$order_id', '$order_name', '$order_mail','$receipt_method', '$note', $primary_source, $amount_type, '$primary_warehouse', '$customer_type')");
    }

    echo json_encode(["result" => "ok", "rest" => $test_space]);

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

  } else if (htmlspecialchars($_POST["func"]) == "deleteReservation" && UserHasPerm('warehouse_reservation_order')) {
    $taken_out = null;
    if (isset($_POST["reserv_id"])) {
      $reserv_id = htmlspecialchars($_POST["reserv_id"]);
      $sql = mysqli_query($conn,"SELECT taken_out FROM warehouse_reservation WHERE reserv_id = '$reserv_id'");
      $taken_out = mysqli_fetch_array($sql)[0];

      $date_end = time();
      $sql = mysqli_query($conn,"UPDATE warehouse_reservation SET is_active = 0, date_end = $date_end, is_deleted = 1 WHERE reserv_id = '$reserv_id'");

    } else {
      $encoded = htmlspecialchars($_POST['reason'] ?? '');
      $decoded = $coderclass->decode($encoded, "SZ4TUN4");
      $parts = explode('|', $decoded);

      if (count($parts) !== 2) {
        echo json_encode(['result'=>'error','message'=>'Érvénytelen azonosító'], JSON_UNESCAPED_UNICODE);
        exit;
      }

      $reason = $parts[0];
      $order_date = $parts[1];

      $sql = mysqli_query($conn,"SELECT taken_out FROM warehouse_reservation WHERE reason = '$reason' and DATE(FROM_UNIXTIME(date_create)) = '$order_date' and is_active = 1");
      $taken_out = mysqli_fetch_array($sql)[0];

      $date_end = time();
      $sql = mysqli_query($conn,"UPDATE warehouse_reservation SET is_active = 0, date_end = $date_end, is_deleted = 1 WHERE reason = '$reason' and DATE(FROM_UNIXTIME(date_create)) = '$order_date' and is_active = 1");
    }

    echo json_encode(["result" => "ok", "taken_out" => $taken_out]);
  } else if (htmlspecialchars($_POST["func"]) == "statistics") {
    $countSql = "SELECT COUNT(DISTINCT CONCAT(reason, '|', DATE(FROM_UNIXTIME(date_create)))) as total
                 FROM warehouse_reservation WHERE is_active = 1";
    $totalRes = $conn->query($countSql);
    $totalOrders = $totalRes->fetch_assoc()['total'];

    $sql_reasons = "SELECT DISTINCT reason, DATE(FROM_UNIXTIME(date_create)) as order_date
                    FROM warehouse_reservation WHERE is_active = 1";
    $res1 = $conn->query($sql_reasons);

    $classic = ['canFulfill' => 0, 'cantFulfill' => 0];
    $sporty = ['canFulfill' => 0, 'cantFulfill' => 0];
    $injmold = ['canFulfill' => 0, 'cantFulfill' => 0];
    $climair = ['canFulfill' => 0, 'cantFulfill' => 0];

    $instock = [];

    while ($row = $res1->fetch_assoc()) {
      $reason = $row['reason'];
      $order_date = $row['order_date'];

      $itemsSql = "SELECT item_id, SUM(amount - COALESCE(taken_out, 0)) as remaining
                   FROM warehouse_reservation
                   WHERE reason = ? AND DATE(FROM_UNIXTIME(date_create)) = ? AND is_active = 1
                   GROUP BY item_id";
      $stmt = $conn->prepare($itemsSql);
      $stmt->bind_param('ss', $reason, $order_date);
      $stmt->execute();
      $itemsRes = $stmt->get_result();

      $canFulfill = true;

      while ($itemRow = $itemsRes->fetch_assoc()) {
        $item_id = $itemRow['item_id'];
        $itemRemaining = intval($itemRow['remaining']);

        if ($itemRemaining <= 0) continue;

        if (!isset($instock[$item_id])) {
          $sql = mysqli_query($conn,"SELECT warehouse_total FROM statistics_daily WHERE item_id = '$item_id'");
          $result = mysqli_fetch_array($sql);
          if ($result == null) {
            $sql = mysqli_query($conn, "SELECT SUM(amount) AS total_amount FROM warehouse WHERE item_id = '$item_id' GROUP BY item_id");
            $result = mysqli_fetch_array($sql);
          }
          $instock[$item_id] = $result ? intval($result[0]) : 0;
        }

        $available_stock = $instock[$item_id];
        $prefix = explode('+', $item_id)[0];

        if (preg_match('/^[0-9]+$/', $prefix)) {
          $classic[$available_stock < $itemRemaining ? 'cantFulfill' : 'canFulfill'] += $itemRemaining;
        } elseif (preg_match('/^CL[P|M]?[0-9]+$/', $prefix)) {
          $climair[$available_stock < $itemRemaining ? 'cantFulfill' : 'canFulfill'] += $itemRemaining;
        } elseif (preg_match('/^FR[0-9]{4}$/', $prefix)) {
          $injmold[$available_stock < $itemRemaining ? 'cantFulfill' : 'canFulfill'] += $itemRemaining;
        } elseif (preg_match('/^F[0-9]{4}$/', $prefix)) {
          $sporty[$available_stock < $itemRemaining ? 'cantFulfill' : 'canFulfill'] += $itemRemaining;
        }

      }

    }

    echo json_encode([
        'result' => 'ok',
        'classic' => $classic,
        'sporty' => $sporty,
        'injmold' => $injmold,
        'climair' => $climair
    ], JSON_UNESCAPED_UNICODE );

  }


  exit();
} else if (isset($_GET["saving"]) && $_GET["saving"] == 1 && UserHasPerm('warehouse_reservation_order')) {
  header("Content-Type: application/json");

  $input = file_get_contents('php://input');
  $tableData = json_decode($input, true);

  if (!empty($tableData)) {

    $errors = "";
    $lines = "";

  	for ($i = 0; $i < count($tableData); $i++) {
  		$row = $tableData[$i];

      $time = time();
      $item_id = $row['item_id'];
      $amount = $row['amount'];

      $note = $row['note'];
      $receipt_method = $row['receipt_method'];
      $primary_source = $row['primary_source'];
      $primary_warehouse = $row['primary_warehouse'];
      $customer_type = $row['customer_type'];

      $reason = preg_replace('/[^a-zA-Z0-9áéíóöőúüűÁÉÍÓÖŐÚÜŰ .-]/u', '', htmlspecialchars($row["reason"]));

      $order_id = empty(htmlspecialchars($row["order_id"])) ? null : htmlspecialchars($row["order_id"]);
      $order_name = empty(htmlspecialchars($row["order_name"])) ? null : htmlspecialchars($row["order_name"]);
      $order_mail = empty(htmlspecialchars($row["order_mail"])) ? null : htmlspecialchars($row["order_mail"]);

      if ($reason == "") {
        $errors .= "|#".$row['line']." - Kötelező megadni egy megrendelőt vagy indoklásts!";
        $lines .= "|reserv_table-".$row['line']."-row";
        continue;
      }

      if (!filter_var($amount, FILTER_VALIDATE_INT) || intval($amount) <= 0) {
        $errors .= "|#".$row['line']." - A mennyiség csak pozitív egész szám lehet!";
        $lines .= "|reserv_table-".$row['line']."-row";
        continue;
      }

      if ($order_mail != null) {
        $emails = array_map('trim', explode(',', $order_mail));
        foreach ($emails as $email) {
          if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $errors .= "|#".$row['line']." - Az e-mail cím helytelen formátumban van: ".$email;
            $lines .= "|reserv_table-".$row['line']."-row";
            continue 2;
          }
        }
      }

      $sql = mysqli_query($conn,"SELECT item_id FROM pr_parameters WHERE item_id = '$item_id'");
      $item_id_sql = mysqli_fetch_array($sql);
      if ($item_id_sql != null) {
        $item_id = $item_id_sql['item_id'];
      } else {
        $errors .= "|#".$row['line']." - Nem létező cikkszám lett megadva!";
        $lines .= "|reserv_table-".$row['line']."-row";
        continue;
      }

      if (substr($item_id, 0, 2) !== "CL") {
        $sql = mysqli_query($conn,"SELECT size, foil_product_place 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] != "" || $pr_warehouse_parameters[1] != ""))) {
          if ($pr_warehouse_parameters == null) {
            $errors .= "|#".$row['line']." - Nem létező cikkszám!";
          } else {
            $errors .= "|#".$row['line']." - A cikkszámhoz nem lett megadva doboz méret!";
          }
          $lines .= "|reserv_table-".$row['line']."-row";
          continue;
        }
      }

      $sql = mysqli_query($conn,"SELECT reserv_id, amount FROM warehouse_reservation WHERE item_id = '$item_id' and reason = '$reason' and is_active = 1 and order_id = '$order_id' and order_name = '$order_name' and order_mail = '$order_mail' and DATE(FROM_UNIXTIME(date_create)) = CURDATE()");
      $there_is_this_order = mysqli_fetch_array($sql);
      if ($there_is_this_order != null) {
        $new_amount = $amount + intval($there_is_this_order["amount"]);
        $reserv_id = $there_is_this_order['reserv_id'];
        $sql = mysqli_query($conn,"UPDATE warehouse_reservation SET amount = $new_amount, receipt_method = '$receipt_method', note = '$note', customer_type = '$customer_type', primary_warehouse = '$primary_warehouse', primary_source = $primary_source WHERE reserv_id = '$reserv_id'");
      } else {
        $sql = mysqli_query($conn,"INSERT INTO warehouse_reservation(item_id, amount, reason, is_active, date_create, order_id, order_name, order_mail, receipt_method, note, primary_source, primary_warehouse, customer_type) VALUES ('$item_id', $amount, '$reason', 1, $time, '$order_id', '$order_name', '$order_mail', '$receipt_method', '$note', $primary_source, '$primary_warehouse', '$customer_type')");
      }

  	}

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

    if ($errors == "") {
      echo json_encode(["status" => "done"]);
    } else {
      echo json_encode(["status" => "error", "message" => substr($errors, 1), "line" => substr($lines, 1)]);
    }
  } else {
  	echo json_encode(["status" => "error", "message" => "Hibás adat", "line" => ""]);
  }

  exit();
}

$customer_type_selector = '';
$query = "SELECT DISTINCT type_name FROM customer_types ORDER BY type_name ASC";
if ($result = $conn->query($query)) {
  while ($customer_type_sql = $result->fetch_assoc()) {
    $customer_type_selector .= '<option value="'.$customer_type_sql['type_name'].'">'.$customer_type_sql['type_name'].'</option>';
  }
}
$customer_type_selector = str_replace('value="Magyar web"', 'value="Magyar web" SELECTED', $customer_type_selector);

?>

<!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>
    .group-row {
      cursor:pointer;
      background: color-mix(in srgb, var(--panelcolor) 55%, transparent 45%) !important;
      transition: background 0.2s;
      color: var(--toppanel);
    }
    .group-row:hover {
      background: #d0e8ff !important;
    }
    .group-row .arrow {
      margin-right: 8px;
      display:inline-block;
      width:11px;
      transition:transform 0.3s;
      transform:rotate(90deg);
    }
    .group-row.expanded .arrow {
      transform:rotate(180deg);
    }

    .detail-row {
      background:#fafafa;
      transition: max-height 0.3s, opacity 0.2s, line-height 0.3s;
      overflow:hidden;
    }
    .detail-row td {
      transition: padding 0.3s;
    }

    .detail-row.open {
      max-height:50px;
      opacity:1;
      line-height: normal;
    }
    .detail-row.close {
      max-height:0;
      opacity:0;
      line-height: 0px;
    }

    .detail-row.close td {
      padding: 0px;
    }

    .slide-col {
      color: var(--panelcolor);
      transition: color 0.3s, border 0.3s;
    }

    .slides-in .slide-col {
      color: white;
    }

    .tables th {
      border: none;
    }
    .tables table {
      border-collapse: separate;
      border-spacing: 0 8px;
    }
    .icon {
      position: absolute;
      color: #FF4D00;
      margin-left: 15px;
      cursor: help;
    }
    .icon svg {
      filter: drop-shadow(0px 0px 2px rgb(255 255 255 / 0.8));
      width: 16px;
      height: 16px;
    }

    #reserv_table tr {
      background-color: #fff;
    }
    #reserv_table tr:nth-child(even) {
      background-color: #f2f2f2;
    }
    .delicon {
      color: #c0392b;
      position:absolute;
      right: 57px;
      cursor: pointer;
      opacity: 0.6;
    }
    .delicon:hover {
      opacity: 1;
      transition: 0.3s;
    }
    .delicon svg {
      width: 20px;
      height: 20px;
    }
    .checkbox-wrapper-34 {
      --blue: #0D7EFF;
      --g08: #E1E5EB;
      --g04: #848ea1;
    }

    .checkbox-wrapper-34 .tgl {
      display: none;
    }
    .checkbox-wrapper-34 .tgl,
    .checkbox-wrapper-34 .tgl:after,
    .checkbox-wrapper-34 .tgl:before,
    .checkbox-wrapper-34 .tgl *,
    .checkbox-wrapper-34 .tgl *:after,
    .checkbox-wrapper-34 .tgl *:before,
    .checkbox-wrapper-34 .tgl + .tgl-btn {
      box-sizing: border-box;
    }
    .checkbox-wrapper-34 .tgl::selection,
    .checkbox-wrapper-34 .tgl:after::selection,
    .checkbox-wrapper-34 .tgl:before::selection,
    .checkbox-wrapper-34 .tgl *::selection,
    .checkbox-wrapper-34 .tgl *:after::selection,
    .checkbox-wrapper-34 .tgl *:before::selection,
    .checkbox-wrapper-34 .tgl + .tgl-btn::selection {
      background: none;
    }
    .checkbox-wrapper-34 .tgl + .tgl-btn {
      outline: 0;
      display: block;
      width: 57px;
      height: 27px;
      position: relative;
      cursor: pointer;
      user-select: none;
      font-size: 12px;
      font-weight: 400;
      color: #fff;
    }
    .checkbox-wrapper-34 .tgl + .tgl-btn:after,
    .checkbox-wrapper-34 .tgl + .tgl-btn:before {
      position: relative;
      display: block;
      content: "";
      width: 44%;
      height: 100%;
    }
    .checkbox-wrapper-34 .tgl + .tgl-btn:after {
      left: 0;
    }
    .checkbox-wrapper-34 .tgl + .tgl-btn:before {
      display: inline;
      position: absolute;
      top: 7px;
    }
    .checkbox-wrapper-34 .tgl:checked + .tgl-btn:after {
      left: 56.5%;
    }

    .checkbox-wrapper-34 .tgl-ios + .tgl-btn {
      background: var(--g08);
      border-radius: 20rem;
      padding: 2px;
      transition: all 0.4s ease;
      box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.1);
    }
    .checkbox-wrapper-34 .tgl-ios + .tgl-btn:after {
      border-radius: 2em;
      background: #fff;
      transition: left 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275), padding 0.3s ease, margin 0.3s ease;
      box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.2);
    }
    .checkbox-wrapper-34 .tgl-ios + .tgl-btn:before {
      content: "Nem";
      left: 28px;
      color: var(--g04);
      transition: left 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
    }
    .checkbox-wrapper-34 .tgl-ios + .tgl-btn:active {
      box-shadow: inset 0 0 0 30px rgba(0, 0, 0, 0.1);
    }
    .checkbox-wrapper-34 .tgl-ios + .tgl-btn:active:after {
      padding-right: 0.4em;
    }
    .checkbox-wrapper-34 .tgl-ios:checked + .tgl-btn {
      background: var(--blue);
    }
    .checkbox-wrapper-34 .tgl-ios:checked + .tgl-btn:active {
      box-shadow: inset 0 0 0 30px rgba(0, 0, 0, 0.1);
    }
    .checkbox-wrapper-34 .tgl-ios:checked + .tgl-btn:active:after {
      margin-left: -0.4em;
    }
    .checkbox-wrapper-34 .tgl-ios:checked + .tgl-btn:before {
      content: "Igen";
      left: 4px;
      color: #fff;
    }
  </style>
  <body>
    <?php echo $menuhtml;?>
    <div class="window closed" id="win">
      <div class="topbar">
        <p id="wintitle">Title</p>
        <div class="btn fullscrn" onclick="fullscrn();" id="fullscrnbtn"></div>
        <div class="btn close" onclick="closewin();"></div>
      </div>
      <div class="wapp" id="winapp"><div id="errorDIV"></div></div>
      <div class="loading" id="winloading"></div>
    </div>
    <div class="loadingBG" id="loadingBG"><img src="../img/loading.gif"></div>
    <div class="content">
      <div id="errorDIV" style="z-index: 100; top: 50px; position: fixed; width: calc(100% - 260px);"></div>

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

      <h1>Rendelések</h1>

      <button class="Feedback" id="settings-recalcdailystat-button" style="position: absolute; float: right; top: 65px; right: 15px; width: 80px; height: 40px;" onclick="RecalcDailyStat();"><span class="button-text">Raktár frissítése</span><div class="loader"></div><div class="checkmark">✔</div><div class="crossmark">✖</div></button>

      <a title="Statisztika" style="position: absolute; float: right; top: 65px; right: 100px;" 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>


      <div style="width: 100%; min-height: 85px;">
        <div style="display: inline; float: left;">
          <p>Rendelés neve / Indoklás: </p>
          <input type="text" id="filter-reason" placeholder="Rendelés neve / Indoklás..." onkeydown="if (event.keyCode == 13) {SendFilter();}" autocomplete="off" style="width: 147px; height: 17px;">
        </div><div style="display: inline; float: left; padding-left: 15px;">
          <p>Rendezési szempont: </p>
          <select id="filter-orderby" onchange="SendFilter();">
            <option value="LAST">Legújabb elől</option>
            <option value="FIRST">Legrégebbi elől</option>
            <option value="ABC">Név szerint - ABC</option>
            <option value="CBA">Név szerint - CBA</option>
          </select>
        </div><div style="display: inline; float: left; padding-left: 15px;">
          <p>Dátum kiválasztása: </p>
          <input type="date" id="filter-date" style="height: 17px" onchange="SendFilter();">
        </div><div style="display: inline; float: left; padding-left: 15px;">
          <p>Rendelés állapota: </p>
          <select id="filter-is_active" onchange="SendFilter();">
            <option value="1">Aktív rendelések</option>
            <option value="0">Lezárt rendelések</option>
          </select>
        </div><div style="display: inline; float: left; padding-left: 15px;">
          <p>Kiszedhetőség: </p>
          <select id="filter-fulfill" onchange="SendFilter();">
            <option value="ALL">Minden megjelenítése</option>
            <option value="CANFULFILL">Csak kiszedhetőek megjelenítése</option>
            <option value="PARTFULFILL">Csak részben kiszedhetőek megjelenítése</option>
            <option value="NOFULFILL">Nem kiszedhetőek megjelenítése</option>
          </select>
        </div><div style="display: inline; float: left; padding-left: 15px;">
          <p>Oldalanként: </p>
          <select id="filter-perpage" onchange="SendFilter();"><option value="25">25 db / oldal</option></select>
        </div><div style="display: inline; float: left; padding-left: 15px;">
          <p style="color: #f5f5f5;">: </p>
          <button onclick="SendFilter();">Szűrés</button>
        </div>

        <?php
        if (UserHasPerm('warehouse_reservation_order')) {
          echo '<div style="display: inline; float: right; padding-right: calc(3% - 8px);"><p style="color: #f5f5f5;">: </p><button onclick="UploadTable();">Táblázat feltöltése</button><input type="file" id="hiddenFileInput" accept=".csv,.xlsx,.xls" style="display: none;"></div><div style="display: inline; float: right; padding-right: 15px;"><p style="color: #f5f5f5;">: </p><button onclick="CreateReserv();">Új rendelés</button></div>';
        }
        ?>
      </div>

      <br clear="all">
        <div style="border-top: solid 1px rgb(211,220,228); width: calc(100% - 15px); height: 0px; margin-top: 15px;"></div>
      <br clear="all">

      <div style="width: calc(100% - 6px); margin-left: 11px; margin-top: 2px; display: inline; float: left;">
        <div class="tables" style="width: 100%">
          <table id="table">
            <thead>
              <tr style="top: 0px; position: sticky; z-index: 1;">
                <th>Rendelés neve / Indoklás</th>
          			<th class="slide-col">Cikkszám</th>
          			<th class="slide-col">Mennyiség <small><small style="opacity: 0.6;">(Kiszedve / Igény)</small></small></th>
                <th style="width: 150px;" class="slide-col">Műveletek</th>
              </tr>
            </thead>

            <tbody id="ordersTbody"></tbody>
          </table>
        </div>
      </div>

      <br clear="all">
      <div>
        <p id="hidden_element_counter" style="text-align: center; opacity: 0.8;"></p>
        <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 style="display: none; visibility: hidden">
        <table id="ExcelExportTable"></table>
      </div>

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

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

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

      /* Remove */

      var data = [];
      var is_active_link = true;

      function LoadFilter() {
        const body = 'func=filter';
        get_POST_information("wh_orders.php", body, function(text) {
          let response = JSON.parse(text);
          if (response.result == "ok") {
            document.getElementById('filter-perpage').innerHTML = response.perpage;
            LoadTable();
          } else {
            GenerateAlerts("error", response.result);
          }
        }, function() {
          GenerateAlerts("error", "Hálózati hiba!");
        });
      }
      function SendFilter() {
        document.getElementById('cpage').innerHTML = '1';
        LoadTable();
      }
      function left() {
        var cpage = document.getElementById("cpage").innerHTML;
        if ((parseInt(cpage) - 1) >= 1) {
          document.getElementById("cpage").innerHTML = parseInt(cpage) - 1;
          LoadTable();
        }
      }
      function right() {
        var cpage = document.getElementById("cpage").innerHTML;
        var maxpage = document.getElementById("maxpage").innerHTML;
        if ((parseInt(cpage) + 1) <= parseInt(maxpage)) {
          document.getElementById("cpage").innerHTML = parseInt(cpage) + 1;
          LoadTable();
        }
      }
      function LoadTable() {
        Loading();
        var reason = document.getElementById('filter-reason').value;
        var perpage = document.getElementById("filter-perpage").value;
        var orderby = document.getElementById("filter-orderby").value;
        var is_active = document.getElementById("filter-is_active").value;
        var fulfill = document.getElementById("filter-fulfill").value;
        var date = document.getElementById("filter-date").value;
        var cpage = document.getElementById("cpage").innerHTML;

        const body = 'func=table&perpage=' + perpage + '&cpage=' + cpage + '&reason=' + encodeURIComponent(reason).replace(/%20/g, '+') + '&orderby=' + orderby + '&is_active=' + is_active + '&date=' + date + '&fulfill=' + fulfill;

        get_POST_information("wh_orders.php", body, function(text) {
          Loading(false);
          let response = JSON.parse(text);
          if (response.result == "ok") {
            document.getElementById("cpage").innerHTML = response.cpage;
            document.getElementById("maxpage").innerHTML = response.maxpage;

            data = response.data;

            if (response.is_active == 1) {
              is_active_link = true;
            } else {
              is_active_link = false;
            }

            renderOrdersTable();
            updateHeaderVisibility();

            if (parseInt(response.hidden) > 0) {
              document.getElementById('hidden_element_counter').style.display = 'block';
              document.getElementById('hidden_element_counter').innerHTML = `Szűrési feltételek miatt ${response.hidden} db rendelés elrejtve!`;
            } else {
              document.getElementById('hidden_element_counter').style.display = 'none';
            }

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

      function renderOrdersTable() {
      	const tbody = document.getElementById('ordersTbody');
      	tbody.innerHTML = '';
      	data.forEach((group, idx) => {
      		const tr = document.createElement('tr');
      		tr.className = 'group-row collapsed';
      		tr.tabIndex = 0;
      		tr.onclick = () => toggleGroup(idx);
      		tr.onkeydown = e => { if (e.key === "Enter" || e.key === " ") toggleGroup(idx); };
      		tr.innerHTML = `<td colspan="4" class="group-cell"><span class="arrow"><svg role="graphics-symbol" viewBox="0 0 100 100" class=""><polygon points="5.9,88.2 50,11.8 94.1,88.2" fill="var(--toppanel)"></polygon></svg></span>${group.megrendelo}</td>`;
      		tbody.appendChild(tr);
      	});
      }
      function updateHeaderVisibility() {
        const table = document.getElementById('table');
        const anyOpen = document.querySelectorAll('.detail-row').length > 0;
        table.classList.toggle('slides-in', anyOpen);
        table.classList.toggle('slides-out', !anyOpen);
        feather.replace();
      }
      function toggleGroup(idx) {
        const tbody = document.getElementById('ordersTbody');
        const groupRow = tbody.querySelectorAll('.group-row')[idx];
        const orders = data[idx].rendelesek;
        const isOpen = groupRow.classList.contains('expanded');

        if (isOpen) {
          let next = groupRow.nextElementSibling;
          while (next && next.classList.contains('detail-row')) {
            const toRemove = next;
            next = next.nextElementSibling;
            toRemove.classList.replace('open','close');
            setTimeout(() => toRemove.remove(), 300);
          }
          groupRow.classList.replace('expanded','collapsed');
        } else {
          let insertAfter = groupRow;
          orders.forEach(r => {
            const tr = document.createElement('tr');
            tr.className = 'detail-row close';
            if (is_active_link) {
              tr.innerHTML = `
                <td></td><td>${r.cikkszam}</td><td>${r.total_taken} / ${r.mennyiseg}</td>
                <?php
                if (UserHasPerm('warehouse_reservation_order')) {
                  echo '<td><span style="color: var(--panelcolor); cursor: pointer;" onclick="Generatepicking_list(\'${r.levetel}\')">Kiszedési lista</span> / <span style="color: var(--panelcolor); cursor: pointer;" onclick="OpenReport(\'${r.levetel}\')">Kezelés</span></td>';
                } else {
                  echo '<td><span style="color: var(--panelcolor); cursor: pointer;" onclick="Generatepicking_list(\'${r.levetel}\')">Kiszedési lista</span></td>';
                }

                ?>
                `;
            } else {
              tr.innerHTML = `
                <td></td><td>${r.cikkszam}</td><td>${r.total_taken} / ${r.mennyiseg}</td>
                <td><span style="color: var(--panelcolor); cursor: pointer;" onclick="Summarizepicking_list('${r.levetel}')">Össszegzés</span></td>`;
            }
            insertAfter.after(tr);
            insertAfter = tr;
            setTimeout(() => tr.classList.replace('close','open'), 5);
          });

          const tr = document.createElement('tr');
          tr.className = 'detail-row close';
          tr.innerHTML = `<td colspan="4" style="visibility: hidden;"></td>`;
          insertAfter.after(tr);
          insertAfter = tr;
          setTimeout(() => tr.classList.replace('close','open'), 5);

          groupRow.classList.replace('collapsed','expanded');
        }

        updateHeaderVisibility();
        setTimeout(() => updateHeaderVisibility(), 310);
      }

      LoadFilter();

      function Generatepicking_list(reason) {
        Loading(true);
        openwin();
        wintitle.innerHTML = "Rendelés kiszedési listája";
        winapp.innerHTML = '<div id="errorDIV"></div>';

        const body = 'func=Generatepicking_list&reason=' + reason;
        get_POST_information("wh_orders.php", body, function(text) {
          let response = JSON.parse(text);
          Loading(false);
          if (response.result == "ok") {
            winapp.innerHTML += '<p style="color: #333333; margin-bottom: 0px; margin-left: 0px; font-size: 23px; font-weight: bold;">'+response.reason+'</p><p style="opacity: 0.8; margin-top: 0px;">'+ (response.date).replaceAll('-', '. ') +'.</p><br><p style="font-weight: bold; font-size: 18px; margin-bottom: 0px;">Kiszedési lista:</p><p style="width: calc(100% - 35px); border-bottom: 1px solid #bdc3c7; margin-top: 5px;">';

            winapp.innerHTML += '<div style="width: 100%; margin-left: 10px; margin-top: 10px; display: inline; float: left;"><div class="tables" style="width: 100%"><table id="reserv_table"><thead><tr style="top: 0px; position: sticky; z-index: 1;"><th>Cikkszám</th><th>Mennyiség</th><th>Helye</th><th style="width: 100px;">Levétel</th><th style="width: 100px;">Korrigálás</th></tr></thead><tbody></tbody></table></div></div>';

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

            response.all_picking_lists.forEach(function(group) {
              var headerTr = document.createElement('tr');
              headerTr.style.background = "transparent";
              var headerTd = document.createElement('td');
              headerTd.colSpan = 6;
              headerTd.innerHTML = (group.overal_order_id).replaceAll("!&maradek&! ", response.reason);
              headerTd.setAttribute('style', 'font-weight: bold; border: none; border-bottom: 1px solid #bdc3c7;');
              if (group.receipt_method != "") { headerTd.innerHTML += `<span onclick="CreateAlertBox('Átvételi mód', '<br><b>A rendelés átvételi módja:</b><br><br>${group.receipt_method}');" style="cursor: pointer; opacity: 0.8; margin-left: 15px; font-size: 12px;"><i class="icon" title="Átvételi mód" style="position: unset; margin-left: 0px; margin-right: 10px; color: var(--panelcolor);"><i data-feather="truck"></i></i>${group.receipt_method}</span>`; }
              if (group.order_note != "") { headerTd.innerHTML += `<span onclick="CreateAlertBox('Megjegyzés', '<br><b>A rendelés megjegyzése:</b><br><br>${group.order_note}');" style="cursor: pointer; opacity: 0.8; margin-left: 15px; font-size: 12px;"><i class="icon" title="Megjegyzés" style="position: unset; margin-left: 0px; margin-right: 10px; color: #059142;"><i data-feather="message-circle"></i></i>${group.order_note}</span>`; }
              headerTr.appendChild(headerTd);
              tableBody.appendChild(headerTr);

              group.picking_list.forEach(function(item) {
                var tr = document.createElement('tr');
                var ItemPos = String(item.pos);
                var RowID = "RowID:" + item.item_id + "-" + item.amount + "-" + MD5(item.location) + "-" + ItemPos.toString().replace(/\n/g, '') + "-" + MD5(group.overal_order_id);
                tr.id = RowID;

                if (!(group.overal_order_id).includes('alert-octagon')) {
                  tr.setAttribute("ismandatory", "true");
                }

                var tdCikkszam = document.createElement('td');
                tdCikkszam.textContent = item.item_id;
                tr.appendChild(tdCikkszam);

                var tdMennyiseg = document.createElement('td');
                tdMennyiseg.textContent = item.amount;

                var leveteloldal = "";
                if (item.amount_type == 1) {
                  tdMennyiseg.innerHTML += ` - <span style="color: var(--panelcolor); font-style: italic; font-size: 14px;">Jobb</span>`;
                  leveteloldal = "J";
                } else if (item.amount_type == 2) {
                  tdMennyiseg.innerHTML += ` - <span style="color: var(--panelcolor); font-style: italic; font-size: 14px;">Bal</span>`;
                  leveteloldal = "B";
                }

                tr.appendChild(tdMennyiseg);

                if (item.wid === 0 || item.wid === -1) {
                  var tdMerged = document.createElement('td');
                  tdMerged.colSpan = 3;
                  tdMerged.textContent = item.wid === 0
                    ? "Sikeresen levéve"
                    : "Hiányzó cikkszám";
                  tr.appendChild(tdMerged);

                  tr.style.backgroundColor = item.wid === 0
                    ? "#05914230"
                    : "#ff4d0030";
                } else {
                  var CanBeCorrigated = true;

                  var tdHelye = document.createElement('td');
                  if (ItemPos.includes(":")) {
                    if (item.code != "") {
                      tdHelye.textContent = (item.code) + NumberToABC(ItemPos.split(":")[0]) + padWithZero(ItemPos.split(":")[1]) || "";
                    } else {
                      tdHelye.textContent =  NumberToABC(ItemPos.split(":")[0]) + ":" + padWithZero(ItemPos.split(":")[1]) || "";
                    }
                  } else {
                    tdHelye.innerHTML = ItemPos.replaceAll("\n", "<br>");
                    if (tdHelye.innerHTML.includes("<br>")) {
                      CanBeCorrigated = false;
                    }
                  }
                  if (item.location != "" && ItemPos.includes(":")) {
                    tdHelye.title = item.location + " / " + NumberToABC(ItemPos.split(":")[0]) + ":" + padWithZero(ItemPos.split(":")[1]);
                  } else if (item.location != "") {
                    tdHelye.title = item.location.replaceAll("<br>", " + ");
                  }

                  tdHelye.setAttribute('ondblclick', 'CreateAlertBox("Raktár hely", "<p>"+ this.title +"</p>");');
                  tdHelye.style.cursor = "pointer";
                  tr.appendChild(tdHelye);

                  var overal_order_id = group.overal_order_id.split('<i class=')[0];

                  const safeOrderId = overal_order_id.replace("&#039;", "\\'");

                  var levetel = document.createElement('td');
                  levetel.innerHTML = `<span style="color: var(--panelcolor); cursor: pointer;" onclick="RemoveFromWarehouse('${item.wid}', '${leveteloldal+item.amount}', '${item.item_id}', '${reason}', '${safeOrderId}', '${RowID}')">Levettem</span>`;
                  tr.appendChild(levetel);

                  var corrigate = document.createElement('td');
                  if (CanBeCorrigated) {
                    corrigate.innerHTML = `<span style="color: var(--panelcolor); cursor: pointer;" onclick="CorrigateWarehouse('${item.wid}', '${leveteloldal+item.amount}', '${item.item_id}', '${reason}', '${safeOrderId}', '${RowID}')">Korrigálok</span>`;
                  } else {
                    corrigate.innerHTML = '<span style="color: #333333; opacity: 0.4; cursor: help;" title="Csak manuális raktár korrekció lehetséges!">-</span>';
                  }
                  tr.appendChild(corrigate);
                }

                tableBody.appendChild(tr);
              });

              var footerTr = document.createElement('tr');
              var footerTd = document.createElement('td');
              footerTd.colSpan = 6;
              footerTd.style.visibility = 'hidden';
              footerTr.appendChild(footerTd);
              tableBody.appendChild(footerTr);
            });

            feather.replace();

            winapp.innerHTML += '<br clear="all"><br><button id="Summarizepicking_listButton" onclick="Summarizepicking_list(\'' + reason + '\');" style="margin-top: 10px;">Rendelés véglegesítése</button>';
            winapp.innerHTML += '<br clear="all"><br>';
            SumPLBtnStatus();
          } else {
            GenerateAlerts("error", response.result);
          }
        }, function() {
          Loading(false);
          GenerateAlerts("error", "Hálózati hiba!");
        });
      }
      function SumPLBtnStatus() {
        const btn = document.getElementById("Summarizepicking_listButton");
        btn.disabled = false;

        const rows = document.querySelectorAll('#reserv_table tr[id][ismandatory]');
        for (const row of rows) {
          const hasColspan = row.querySelector('td[colspan]') !== null;
          const hasStrikeRow = row.classList.contains('strike-row');

          if (!hasColspan && !hasStrikeRow) {
            btn.disabled = true;
            return;
          }
        }
      }

      function CorrigateWarehouse(wid, amount, item_id, reason, overal_order_id, RowID, input = 'DefaultText') {
        var RealAmount = (amount[0] === 'J' || amount[0] === 'B') ? amount.slice(1) : amount;
        var FirstChar = (amount[0] === 'J' || amount[0] === 'B') ? amount[0] : '';

        console.log(RealAmount);
        console.log(FirstChar);

        const num = Number(input);
        if (Number.isInteger(num) && num >= 0 && num <= RealAmount) {
          RemoveFromWarehouse(wid, FirstChar + String(num), item_id, reason, overal_order_id, RowID, true);
        } else {
          var html = `
          <p><b>Ha nem talált annyi terméket a polcon amennyi a rendszer szerint megtalálható, kérjük írja be hogy mennyit talált a polcon!</b><br><br>A megadott értéket frissítjük a raktár nyílvántartásban!</p><br>
          <input type="number" id="AlertTextInput" placeholder="Mennyiség..." autocomplete="off" min="0" max=${RealAmount}>
          <br clear="all"><br>
          <button id="AlertBtnNo" style="float: right; margin-left: 15px; width: 80;">Mégsem</button>
          <button id="AlertBtnYes" style="float: right; width: 60px; background: var(--panelcolor); color: #f5f5f5; border: unset;">Mentés</button>
          `;
          const overlay = CreateAlertBox('Korrigálás!', html, false);
          document.getElementById('AlertBtnYes').onclick = function () { CorrigateWarehouse(wid, amount, item_id, reason, overal_order_id, RowID, (document.getElementById("AlertTextInput").value).toLowerCase()); CloseAlertBox(overlay); };
          document.getElementById('AlertBtnNo').onclick = function () { CloseAlertBox(overlay); };
          return;
        }
      }
      function RemoveFromWarehouse(wid, amount, item_id, reason, overal_order_id, RowID = "", corrigate = false) {
        var tcHely = "";
        if (RowID != "") {
          var TempRow = document.getElementById(RowID);
          var thirdTd = TempRow.querySelectorAll('td')[2];
          tcHely = thirdTd.textContent;
        }
        const body = 'func=RemoveFromWarehouse&wid=' + encodeURIComponent(wid).replace(/%20/g, '+') + '&amount=' + amount + '&item_id=' + encodeURIComponent(item_id).replace(/%20/g, '+') + '&reason=' + encodeURIComponent(reason).replace(/%20/g, '+') + '&corrigate=' + corrigate + '&overal_order_id=' + encodeURIComponent(overal_order_id).replace(/%20/g, '+') + '&tcHely=' + encodeURIComponent(tcHely).replace(/%20/g, '+');
        get_POST_information("wh_orders.php", body, function(text) {
          let response = JSON.parse(text);
          if (response.result == "ok") {
            if (response.message != '') {
              GenerateAlerts("info", response.message);
            }
            if (RowID != "") {
              document.getElementById(RowID).classList.add('strike-row');
              SumPLBtnStatus();
            }
          } else {
            GenerateAlerts("error", response.message);
          }
          if (response.reset == "true") {
            Generatepicking_list(reason);
            GenerateAlerts("info", "Kiszedési lista újragenerálva!");
          }
        }, function() {
          GenerateAlerts("error", "Hálózati hiba!");
        });
      }

      function Summarizepicking_list(reason) {
        Loading(true);
        openwin();
        wintitle.innerHTML = "Rendelés összegző";
        winapp.innerHTML = '<div id="errorDIV"></div>';

        const body = 'func=Summarizepicking_list&reason=' + reason + '&is_active=' + document.getElementById("filter-is_active").value;
        get_POST_information("wh_orders.php", body, function(text) {
          let response = JSON.parse(text);
          Loading(false);
          if (response.result == "ok") {
            winapp.innerHTML += '<p style="color: #333333; margin-bottom: 0px; margin-left: 0px; font-size: 23px; font-weight: bold;">'+response.reason+' - összegzés</p><p style="opacity: 0.8; margin-top: 0px;">'+ (response.date).replaceAll('-', '. ') +'.</p><br><p style="font-weight: bold; font-size: 18px; margin-bottom: 0px;">Összesítés:</p><p style="width: calc(100% - 35px); border-bottom: 1px solid #bdc3c7; margin-top: 5px;">';

            winapp.innerHTML += '<div style="width: 100%; margin-left: 10px; margin-top: 10px; display: inline; float: left;"><div class="tables" style="width: 100%"><table id="reserv_table"><thead><tr style="top: 0px; position: sticky; z-index: 1;"><th>Cikkszám</th><th>Mennyiség</th><th></th></tr></thead><tbody></tbody></table></div></div>';

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

            var IsWebOrder = false;

            response.all_picking_lists.forEach(function(group) {
              var headerTr = document.createElement('tr');
              headerTr.style.background = "transparent";
              var headerTd = document.createElement('td');
              headerTd.colSpan = 6;
              headerTd.innerHTML = (group.overal_order_id).replaceAll("!&maradek&!", response.reason);
              headerTd.setAttribute('style', 'font-weight: bold; border: none; border-bottom: 1px solid #bdc3c7;');
              headerTr.appendChild(headerTd);
              tableBody.appendChild(headerTr);

              if (!(group.overal_order_id).includes("!&maradek&!")) {
                IsWebOrder = true;
              }

              group.picking_list.forEach(function(item) {
                var tr = document.createElement('tr');

                var tdCikkszam = document.createElement('td');
                tdCikkszam.textContent = item.item_id;
                tr.appendChild(tdCikkszam);

                var tdMennyiseg = document.createElement('td');
                tdMennyiseg.textContent = item.amount;
                tr.appendChild(tdMennyiseg);

                if (item.wid === 0 || item.wid === -1) {
                  var tdMerged = document.createElement('td');
                  tdMerged.colSpan = 4;
                  tdMerged.textContent = item.wid === 0
                    ? "Sikeresen levéve"
                    : "Hiányzó cikkszám";
                  tr.appendChild(tdMerged);

                  tr.style.backgroundColor = item.wid === 0
                    ? "#05914230"
                    : "#ff4d0030";
                }

                tableBody.appendChild(tr);
              });

              var footerTr = document.createElement('tr');
              var footerTd = document.createElement('td');
              footerTd.colSpan = 6;
              footerTd.style.visibility = 'hidden';
              footerTr.appendChild(footerTd);
              tableBody.appendChild(footerTr);
            });

            if (response.is_active == 1 && !IsWebOrder) {
              winapp.innerHTML += '<br clear="all"><br><button onclick="Closepicking_list(\'' + reason + '\', \'' + response.reason + '\', 0);" style="margin-top: 10px;">Rendelés lezárása</button>';
            } else if (response.is_active == 1 && IsWebOrder) {
              winapp.innerHTML += '<button onclick="Closepicking_list(\'' + reason + '\', \'' + response.reason + '\', 2);" style="margin-top: 10px;">Rendelés lezárása</button>';
            } else if (response.is_active == 0) {
              winapp.innerHTML += '<button onclick="CopyExcel(\'' + reason + '\');" style="margin-top: 10px;">Excel másolása a vágólapra</button>';
            }
            winapp.innerHTML += '<br clear="all"><br>';

            feather.replace();

          } else {
            GenerateAlerts("error", response.message);
          }
        }, function() {
          Loading(false);
          GenerateAlerts("error", "Hálózati hiba!");
        });
      }
      function Closepicking_list(reason, order_name, mode, Confirmed = false) {
        if (Confirmed) {
          Loading();

          const body = 'func=Closepicking_list&reason=' + reason + '&mode=' + mode;
          get_POST_information("wh_orders.php", body, function(text) {
            Loading(false);
            let response = JSON.parse(text);
            if (response.result == "ok") {
              closewin();
              LoadTable();
              GenerateAlerts("info", response.message);
            } else {
              GenerateAlerts("error", response.message);
            }
          }, function() {
            Loading(false);
            GenerateAlerts("error", "Hálózati hiba!");
          });
        } else {
          var TheText = '';
          if (mode == 1) {
            TheText = "Biztos benne, hogy a(z) '" + order_name + "' nevű rendelést lezárja, és a ki nem szedett termékeket újrarendeli?";
          } else if (mode == 2) {
            TheText = "Biztos benne, hogy a(z) '" + order_name + "' nevű rendelést lezárja,  és a ki nem szedett termékeket újrarendeli a megrendelő e-mailes kiértesítésével (ahol lehetséges)?";
          } else {
            TheText = "Biztos benne, hogy a(z) '" + order_name + "' nevű rendelést lezárja?";
          }

          var html = `
          <p><b>${TheText}</b></p>
          <button id="AlertBtnNo" style="float: right; margin-left: 15px; width: 60px;">Nem</button>
          <button id="AlertBtnYes" style="float: right; width: 60px; background: var(--panelcolor); color: #f5f5f5; border: unset;">Igen</button>
          `;
          const overlay = CreateAlertBox('Rendelés lezárás', html);
          document.getElementById('AlertBtnYes').onclick = function () { Closepicking_list(reason, order_name, mode, true); CloseAlertBox(overlay); };
          document.getElementById('AlertBtnNo').onclick = function () { CloseAlertBox(overlay); };
          return;
        }
      }
      function CopyExcel(reason) {
        Loading(true);
        const body = 'func=CopyExcel&reason=' + reason;
        get_POST_information("wh_orders.php", body, function(text) {
          let response = JSON.parse(text);
          Loading(false);
          if (response.result == "ok") {
            const table = document.getElementById('ExcelExportTable');
            table.innerHTML = '';

            const tbody = document.createElement('tbody');
            response.all_picking_lists.forEach(list => {
              list.picking_list.forEach(item => {
                const tr = document.createElement('tr');
                [item.item_id, item.amount, response.reason || '', list.order_id, list.order_name, list.order_mail].forEach(val => {
                  const td = document.createElement('td');
                  td.textContent = val;
                  tr.appendChild(td);
                });
                tbody.appendChild(tr);
              });
            });
            table.appendChild(tbody);

            const rows = Array.from(document.querySelectorAll('#ExcelExportTable tr'));
        		const tsv = rows.map(row => {
        			const cells = Array.from(row.querySelectorAll('td, th'));
        			return cells.map(cell => cell.textContent).join('\t');
        		}).join('\r\n');

            if (navigator.clipboard && navigator.clipboard.writeText) {
          		navigator.clipboard.writeText(tsv).then(
                () => GenerateAlerts("success", "Sikeresen kimásolva! Illesze be egy Excel alkalmazásba a vágólapra másolt szöveget."),
          			err => console.error('Hiba másolás közben:', err)
          		);
          		return;
          	}

            const textarea = document.createElement('textarea');
            textarea.value = tsv;
            textarea.display = 'none';
            document.body.appendChild(textarea);
            textarea.select();
            try {
              document.execCommand('copy');
              GenerateAlerts("success", "Sikeresen kimásolva! Illesze be egy Excel alkalmazásba a vágólapra másolt szöveget.")
            } catch (err) {
              console.error('Hiba másolás közben (fallback):', err);
            }
            document.body.removeChild(textarea);

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

      /* Reservation */

      function OpenReport(reason) {
         Loading(true);
         openwin();
         wintitle.innerHTML = "Rendelés információi";
         winapp.innerHTML = '<div id="errorDIV"></div>';

         const body = 'func=openreport&reason=' + reason;
         get_POST_information("wh_orders.php", body, function(text) {
           let response = JSON.parse(text);
           Loading(false);
           if (response.result == "ok") {
             winapp.innerHTML += '<p style="color: #333333; margin-bottom: 0px; margin-left: 0px; font-size: 23px; font-weight: bold;">'+response.name_in_db+'</p>';
             winapp.innerHTML += '<i title="Teljes rendelés törlése" style="z-index: 2;" class="delicon" onclick="DeleteReservation(\'\', \'\', \'\', \''+response.name_in_db+'\', \''+reason+'\');"><i data-feather="trash-2"></i></i>';
             winapp.innerHTML += '<p style="opacity: 0.8; margin-top: 0px;">'+response.date+'</p>';
             winapp.innerHTML += '<br clear="all">';

             var tableresponse = response.data;
             if (tableresponse != "") {
               if (tableresponse.includes("|%|")) {
                 var tablearr = tableresponse.split("|%|");
               } else {
                 var tablearr = [tableresponse];
               }

               winapp.innerHTML += '<p style="font-weight: bold; font-size: 18px; margin-bottom: 0px;">Rendelések:</p>';
               for (var i = 0; i < tablearr.length; i++) {
                 var datas = tablearr[i].split("/!/");
                 if (i == 0) {winapp.innerHTML += '<p style="width: calc(100% - 35px); border-bottom: 1px solid #bdc3c7; margin-top: 5px;">';
                 } else {winapp.innerHTML += '<p style="width: calc(100% - 35px); border-bottom: 1px solid #bdc3c7;">';}
                 winapp.innerHTML += '<i title="Tétel törlése" class="delicon" onclick="DeleteReservation(\''+datas[3]+'\', \''+datas[7]+'\', \''+datas[1]+'\', \''+datas[0]+'\', \''+reason+'\');"><i data-feather="trash-2"></i></i>';
                 winapp.innerHTML += '<div class="productbox"><p>Rendelés azonosító</p><p>'+datas[4]+'</p></div>';
                 winapp.innerHTML += '<div class="productbox"><p>Rendelő neve</p><p>'+datas[5]+'</p></div>';
                 winapp.innerHTML += '<div class="productbox"><p>Rendelő e-mail címe</p><p>'+datas[6]+'</p></div>';
                 winapp.innerHTML += '<div class="productbox"><p>Cikkszám</p><p>'+datas[7]+'</p></div>';
                 winapp.innerHTML += '<div class="productbox"><p>Mennyiség</p><p>'+datas[1]+' db</p></div>';
                 winapp.innerHTML += '<div class="productbox"><p>Átvételi mód</p><p>'+datas[8]+'</p></div>';
                 winapp.innerHTML += '<div class="productbox"><p>Megjegyzés</p><p>'+datas[9]+'</p></div>';
                 winapp.innerHTML += '<div class="productbox"><p>Elsődleges forrás</p><p>' + ((datas[10] == 1) ? 'Fóliás' : 'Dobozos') + '</p></div>';
                 winapp.innerHTML += '<div class="productbox"><p>Elsődleges raktár</p><p>'+datas[11]+'</p></div>';
               }
               feather.replace();
               winapp.innerHTML += '<p style="width: calc(100% - 35px); border-bottom: 1px solid #bdc3c7;">';
             } else {
               closewin();
             }
           } else {
             GenerateAlerts("error", response.message);
           }
         }, function() {
           Loading(false);
           GenerateAlerts("error", "Hálózati hiba!");
         });
      }

      function CreateReserv() {
        openwin();
        wintitle.innerHTML = "Új rendelés létrehozása";
        winapp.innerHTML = '<div id="errorDIV"></div>';
        winapp.innerHTML += '<p style="color: #333333; margin-bottom: 0px; margin-left: 0px; font-size: 23px; font-weight: bold;">Új rendelés létrehozása</p><br><p style="font-weight: bold; font-size: 18px; margin-bottom: 0px;">Töltse ki az alábbiakat:</p><p style="width: calc(100% - 35px); border-bottom: 1px solid #bdc3c7; margin-top: 5px;">';

        const container = document.createElement('div');
        container.style.display = 'flex';
        container.style.flexWrap = 'wrap';
        container.style.width = "calc(100% - 35px)";
        container.style.gap = '15px';

        const itemStyle = 'flex: 1 1 calc(33.333% - 10px); min-width: 250px; box-sizing: border-box;';

        container.innerHTML += `
        	<div style="${itemStyle}">
        		<p class="label" style="margin-bottom: 5px;">Cikkszám: <span style="color: red;">*</span></p>
        		<input id="winapp_item_id" type="text" autocomplete="off" spellcheck="false" placeholder="Cikkszám...">
        	</div>
        	<div style="${itemStyle} display: flex; flexWrap: wrap; gap: 15px;">
            <div style="flex: 1 1 calc(70% - 10px); min-width: 180px; max-width: 250px; box-sizing: border-box;">
        		  <p class="label" style="margin-bottom: 5px;">Mennyiség: <span style="color: red;">*</span></p>
        		  <input id="winapp_amount" style="width: 160px;" type="number" min="1" autocomplete="off" spellcheck="false" placeholder="Mennyiség...">
            </div>
            <div style="flex: 1 1 calc(30% - 10px); min-width: 30px; box-sizing: border-box;">
              <p class="label" style="margin-bottom: 10px; cursor: help;" title="Elsődlegesen fóliás raktárból szedje-e ki a rendelést">Fóliásból:</p>
              <div class="checkbox-wrapper-34">
                <input class='tgl tgl-ios' id='winapp_primary_source' type='checkbox'>
                <label class='tgl-btn' for='winapp_primary_source'></label>
              </div>
            </div>
        	</div>
        	<div style="${itemStyle}">
        		<p class="label" style="margin-bottom: 5px;">Rendelés neve / Indoklás: <span style="color: red;">*</span></p>
        		<input id="winapp_reason" type="text" autocomplete="off" spellcheck="false" placeholder="Rendelés neve / Indoklás...">
        	</div>
        `;

        container.innerHTML += `
        	<div style="${itemStyle}">
        		<p class="label" style="margin-bottom: 5px;">Rendelés azonosító:</p>
        		<input id="winapp_order_id" type="text" autocomplete="off" spellcheck="false" placeholder="Rendelés azonosító...">
        	</div>
        	<div style="${itemStyle}">
        		<p class="label" style="margin-bottom: 5px;">Rendelő neve:</p>
        		<input id="winapp_order_name" type="text" autocomplete="off" spellcheck="false" placeholder="Rendelő neve...">
        	</div>
        	<div style="${itemStyle}">
        		<p class="label" style="margin-bottom: 5px;">Rendelő e-mail címe:</p>
        		<input id="winapp_order_mail" type="email" autocomplete="off" spellcheck="false" placeholder="Rendelő e-mail címe...">
        	</div>
        `;

        container.innerHTML += `
          <div style="${itemStyle}">
            <p class="label" style="margin-bottom: 5px;">Vevőtípus:</p>
            <select id="winapp_customer_type" style="max-width: unset; width: 218px;">
              <?php echo $customer_type_selector;?>
            </select>
          </div>
          <div style="${itemStyle}">
            <p class="label" style="margin-bottom: 5px;">Átvételi mód:</p>
            <input id="winapp_receipt_method" type="text" autocomplete="off" spellcheck="false" placeholder="Átvételi mód...">
          </div>
          <div style="${itemStyle}">
            <p class="label" style="margin-bottom: 5px;">Elsődleges raktár:</p>
            <select id="winapp_primary_warehouse" style="max-width: unset; width: 218px;">
              <option value="FŐ">FŐ raktár</option>
              <option value="PLEX">PLEX raktár</option>
            </select>
          </div>
        `;

        container.innerHTML += `
          <div style="${itemStyle}">
            <p class="label" style="margin-bottom: 5px;">Megjegyzés:</p>
            <textarea style="resize: vertical; min-height: 80px; width: 200px;" id="winapp_order_note" placeholder="Megjegyzés a rendeléshez..." autocomplete="off"></textarea>
          </div>
        `;

        container.innerHTML += `
        	<div style="flex: 1 1 100%; margin: 20px 0px;">
        		<button onclick="ReservItem();" style="width: 100%;">Termék megrendelése</button>
        	</div>
        `;

        winapp.appendChild(container);


      }
      function ReservItem(item_id = document.getElementById("winapp_item_id").value, amount = document.getElementById("winapp_amount").value, reason = document.getElementById("winapp_reason").value) {
        var order_id = document.getElementById("winapp_order_id").value;
        var order_name = document.getElementById("winapp_order_name").value;
        var order_mail = document.getElementById("winapp_order_mail").value;

        var receipt_method = document.getElementById("winapp_receipt_method").value;
        var note = document.getElementById("winapp_order_note").value;
        var primary_warehouse = document.getElementById("winapp_primary_warehouse").value;
        var customer_type = document.getElementById("winapp_customer_type").value;

        var order_primary_source = 0;
        if (document.getElementById("winapp_primary_source").checked) {
          var order_primary_source = 1;
        }



        Loading();
        const body = 'func=reservitem&item_id=' + encodeURIComponent(item_id).replace(/%20/g, '+') + '&primary_source=' + order_primary_source + '&reason=' + encodeURIComponent(reason).replace(/%20/g, '+') + '&amount=' + amount + '&order_id=' + encodeURIComponent(order_id).replace(/%20/g, '+') + '&order_name=' + encodeURIComponent(order_name).replace(/%20/g, '+') + '&order_mail=' + encodeURIComponent(order_mail).replace(/%20/g, '+') + '&receipt_method=' + encodeURIComponent(receipt_method).replace(/%20/g, '+') + '&note=' + encodeURIComponent(note).replace(/%20/g, '+') + '&primary_warehouse=' + encodeURIComponent(primary_warehouse).replace(/%20/g, '+') + '&customer_type=' + encodeURIComponent(customer_type).replace(/%20/g, '+');
        get_POST_information("wh_orders.php", body, function(text) {
          let response = JSON.parse(text);
          Loading(false);
          if (response.result == "ok") {
            GenerateAlerts("success", "Sikeresen létrehozta a rendelést!");
            if (response.rest < 0) {
              GenerateAlerts("warning", "Nincsen elegendő termék a raktárban! " + (response.rest * -1) + " db termék hiányzik!");
            }
            LoadTable();

            document.getElementById("winapp_item_id").value = "";
            document.getElementById("winapp_amount").value = "";
          } else {
            GenerateAlerts("error", response.result);
          }
        }, function() {
          Loading(false);
          GenerateAlerts("error", "Hálózati hiba!");
        });
      }

      function DeleteReservation(reserv_id, item_id, amount, reason, OpenReportReason, Confirmed = false) {
        if (Confirmed) {
          Loading(true);

          var body = ""
          if (reserv_id != "") {
            body = 'func=deleteReservation&reserv_id=' + reserv_id;
          } else {
            body = 'func=deleteReservation&reason=' + OpenReportReason;
          }

          get_POST_information("wh_orders.php", body, function(text) {
            let response = JSON.parse(text);
            Loading(false);
            if (response.result == "ok") {
              GenerateAlerts("success", "Sikeresen törölte a rendelést!");
              OpenReport(OpenReportReason);
              LoadTable();

              if (response.taken_out > 0) {
                var html = `<p>Ne feledje a már kiszedett termékeket visszavenni raktárba!</p>`;
                CreateAlertBox('Raktári bevét', html);
              }

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

        } else {
          if (reserv_id != "") {
            var html = `
            <p><b>Biztos benne, hogy a(z) "${reason}" rendelését a ${amount} db "${item_id}" cikkszámú termékre törli?</b></p>
            <button id="AlertBtnNo" style="float: right; margin-left: 15px; width: 60px;">Nem</button>
            <button id="AlertBtnYes" style="float: right; width: 60px; background: var(--panelcolor); color: #f5f5f5; border: unset;">Igen</button>
            `;
            const overlay = CreateAlertBox('Tétel törlése', html);
            document.getElementById('AlertBtnYes').onclick = function () { DeleteReservation(reserv_id, item_id, amount, reason, OpenReportReason, true); CloseAlertBox(overlay); };
            document.getElementById('AlertBtnNo').onclick = function () { CloseAlertBox(overlay); };
            return;
          } else {
            var html = `
            <p><b>Biztos benne, hogy a(z) "${reason}" rendelését törli?</b></p>
            <button id="AlertBtnNo" style="float: right; margin-left: 15px; width: 60px;">Nem</button>
            <button id="AlertBtnYes" style="float: right; width: 60px; background: var(--panelcolor); color: #f5f5f5; border: unset;">Igen</button>
            `;
            const overlay = CreateAlertBox('Rendelés törlése', html);
            document.getElementById('AlertBtnYes').onclick = function () { DeleteReservation("", "", "", reason, OpenReportReason, true); CloseAlertBox(overlay); };
            document.getElementById('AlertBtnNo').onclick = function () { CloseAlertBox(overlay); };
            return;
          }
        }
      }

      function UploadTable() {
        const fileInput = document.getElementById('hiddenFileInput');
        fileInput.click();

        fileInput.onchange = function(event) {
          const selectedFile = event.target.files[0];
          if (selectedFile) {
            handleFileSelection(selectedFile);
          }
          fileInput.value = '';
        };

      }
      function handleFileSelection(file) {
        Loading();
        const allowedTypes = ['text/csv', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];

        if (!allowedTypes.includes(file.type) && !file.name.toLowerCase().endsWith('.csv')) {
          Loading(false);
          GenerateAlerts("error", 'Csak CSV és Excel fájlok támogatottak!');
          return;
        }

        const maxSize = 10 * 1024 * 1024;
        if (file.size > maxSize) {
          Loading(false);
          GenerateAlerts("error", 'A fájl túl nagy! Maximum 10MB engedélyezett.');
          return;
        }

        if (file.type === 'text/csv') {
          processCSVFile(file);
        } else {
          convertExcelToCSV(file);
        }
      }
      function convertExcelToCSV(file) {
        const validExtensions = ['.xlsx', '.xls'];
        const fileExtension = file.name.toLowerCase().substr(file.name.lastIndexOf('.'));

        if (!validExtensions.includes(fileExtension)) {
          Loading(false);
          GenerateAlerts("error", 'Csak .xlsx és .xls fájlok konvertálhatók!');
          return;
        }
        const reader = new FileReader();

        reader.onload = function(e) {
          try {
            if (typeof XLSX === 'undefined') {
              throw new Error('XLSX könyvtár nem elérhető');
            }

            const data = e.target.result;
            const workbook = XLSX.read(data, { type: 'array' });

            if (!workbook.SheetNames.length) {
              throw new Error('Az Excel fájl nem tartalmaz munkalapokat');
            }

            const firstSheetName = workbook.SheetNames[0];
            const worksheet = workbook.Sheets[firstSheetName];

            if (!worksheet || !worksheet['!ref']) {
              throw new Error('Az első munkalap üres vagy hibás');
            }

            const csvData = XLSX.utils.sheet_to_csv(worksheet);

            if (!csvData.trim()) {
              throw new Error('A konvertált CSV fájl üres');
            }

            const csvBlob = new Blob([csvData], { type: 'text/csv;charset=utf-8;' });
            const csvFile = new File([csvBlob], file.name.replace(/\.(xlsx|xls)$/i, '.csv'), {
              type: 'text/csv',
              lastModified: Date.now()
            });

            processCSVFile(csvFile);

          } catch (error) {
            console.error('Excel konvertálási hiba:', error);
            Loading(false);
            GenerateAlerts("error", `Hiba az Excel fájl konvertálása során: ${error.message}`);
          }
        };

        reader.onerror = function(event) {
          console.error('Fájl olvasási hiba:', event);
          Loading(false);
          GenerateAlerts("error", 'Hiba az Excel fájl olvasása során');
        };

        reader.readAsArrayBuffer(file);
      }

      function processCSVFile(file) {
        const reader = new FileReader();

        reader.onload = function(e) {
          const binaryData = e.target.result;
          const detectedEncoding = detectEncoding(binaryData);

          readWithEncoding(file, detectedEncoding);
        };

        reader.readAsBinaryString(file);
      }
      function detectEncoding(binaryData) {
        const sample = binaryData.slice(0, 1000);

        const cp1250Chars = [
          0xE1, // á
          0xE9, // é
          0xED, // í
          0xF3, // ó
          0xF6, // ö
          0xF5, // õ
          0xFA, // ú
          0xFC, // ü
          0xFB  // û
        ];

        let cp1250Score = 0;
        for (let i = 0; i < sample.length; i++) {
          const byte = sample.charCodeAt(i);
          if (cp1250Chars.includes(byte)) {
            cp1250Score++;
          }
        }

        return cp1250Score > 0 ? 'windows-1250' : 'utf-8';
      }
      function readWithEncoding(file, encoding) {
        const reader = new FileReader();

        reader.onload = function(e) {
          try {
            const csvContent = e.target.result;
            const parsedData = parseCSVContent(csvContent);

            const lines = csvContent.split(/\r\n|\n/);

            if (parsedData.length > 0) {
              GenerateAlerts("info", `${parsedData.length} érvényes sor betöltve a ${lines.length} sorból.`);
              //console.log(`${parsedData.length} érvényes sor betöltve (${encoding} kódolással) a ${lines.length} sorból.`);
              startDataProcessing(parsedData);
            } else {
              Loading(false);
              GenerateAlerts("error", 'Nem található érvényes adat a fájlban.');
            }
          } catch (error) {
            Loading(false);
            GenerateAlerts("error", 'Hiba a fájl feldolgozása során: '+ error.message);
          }
        };

        reader.onerror = function() {
          Loading(false);
          GenerateAlerts("error", 'Hiba a fájl olvasása során');
        };

        reader.readAsText(file, encoding);
      }

      function parseCSVContent(csvContent) {
        csvContent = csvContent.replace(/"([^"]*)"/g, function(match) {
        	return match.replace(/\r\n|\n/g, ' ').replace(/\s+/g, ' ');
        });
        const lines = csvContent.split(/\r\n|\n/);
        const validRows = [];
        const delimiter = detectDelimiter(csvContent);
        console.log(csvContent);

        for (let i = 0; i < lines.length; i++) {
          const line = lines[i].trim();
          if (!line) continue;

          const columns = parseCSVLine(line, delimiter);

          if (columns.length >= 3) {
            const item_id = columns[0] ? columns[0].trim() : '';
            const amount = columns[1] ? columns[1].trim() : '';
            const reason = columns[2] ? columns[2].trim() : '';
            const order_id = columns[3] ? columns[3].trim() : '';
            const order_name = columns[4] ? columns[4].trim() : '';
            const order_mail = columns[5] ? columns[5].trim() : '';
            const receipt_method = columns[6] ? columns[6].trim() : '';
            const note = columns[7] ? columns[7].trim() : '';

            if (isNumericValue(amount)) {
              validRows.push({
                line: (i + 1),
                item_id: item_id,
                amount: Math.round(parseFloat(amount)),
                reason: reason,
                order_id: order_id,
                order_name: order_name,
                order_mail: order_mail,
                receipt_method: receipt_method,
                note: note
              });
            }
          }
        }

        return validRows;
      }
      function detectDelimiter(csvContent) {
        const lines = csvContent.split(/\r\n|\n/);
        const firstLine = lines[0];

        const delimiters = [';', ',', '\t', '|'];
        let maxCount = 0;
        let detectedDelimiter = ',';

        delimiters.forEach(delimiter => {
          const count = (firstLine.match(new RegExp('\\' + delimiter, 'g')) || []).length;
          if (count > maxCount) {
            maxCount = count;
            detectedDelimiter = delimiter;
          }
        });

        return detectedDelimiter;
      }
      function parseCSVLine(line, delimiter = ',') {
        const result = [];
        let current = '';
        let inQuotes = false;
        let i = 0;

        while (i < line.length) {
          const char = line[i];

          if (char === '"') {
            if (!inQuotes) {
              inQuotes = true;
            } else if (i + 1 < line.length && line[i + 1] === '"') {
              current += '"';
              i++;
            } else {
              inQuotes = false;
            }
          } else if (char === delimiter && !inQuotes) {
            result.push(current.trim());
            current = '';
          } else if (char === '\r' || char === '\n') {
            if (!inQuotes) {
              break;
            }
            current += char;
          } else {
            current += char;
          }

          i++;
        }

        result.push(current.trim());
        return result;
      }

      function isNumericValue(value) {
        if (!value || value === '' || value === null || value === undefined) {
          return false;
        }

        const trimmedValue = typeof value === 'string' ? value.trim() : value;

        if (trimmedValue === '') {
          return false;
        }
        const num = parseFloat(trimmedValue);
        return !isNaN(num) && isFinite(num);
      }

      function startDataProcessing(parsedData) {
        openwin();
        wintitle.innerHTML = "Új rendelés létrehozása";
        winapp.innerHTML = '<div id="errorDIV"></div>';
        winapp.innerHTML += '<p style="color: #333333; margin-bottom: 0px; margin-left: 0px; font-size: 23px; font-weight: bold;">Új rendelés létrehozása</p><br><p style="font-weight: bold; font-size: 18px; margin-bottom: 0px;">Ellenőrizze az adatokat: <small style="opacity: 0.8; font-weight: normal;"><small>(Szükség szerint módosítsa)</small></small></p><p style="width: calc(100% - 35px); border-bottom: 1px solid #bdc3c7; margin-top: 5px;">';

        winapp.innerHTML += '<div style="width: 100%; margin-left: 10px; margin-top: 10px; display: inline; float: left;"><div class="tables" style="width: 100%"><table id="reserv_table"><thead><tr style="top: 0px; position: sticky; z-index: 1;"><th style="background-color: #ddd; width: 25px; color: #333; border: none;">Sor</th><th>Cikkszám</th><th>Mennyiség</th><th>Rendelés neve / Indoklás</th><th class="ifisweb">Rendelés azonosító</th><th class="ifisweb">Rendelő neve</th><th class="ifisweb">Rendelő e-mail címe</th><th>Átvételi mód</th><th>Megjegyzés</th></tr></thead><tbody></tbody></table></div></div>';

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

        var ifisweb = false;

        parsedData.forEach(function(rowData) {
          var newRow = table.insertRow();
          newRow.id = 'reserv_table-' + rowData.line + '-row';

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

          newCell_0.innerHTML = rowData.line;
          newCell_1.innerHTML = rowData.item_id;
          newCell_2.innerHTML = rowData.amount;
          newCell_3.innerHTML = rowData.reason;
          newCell_4.innerHTML = rowData.order_id;
          newCell_5.innerHTML = rowData.order_name;
          newCell_6.innerHTML = rowData.order_mail;
          newCell_7.innerHTML = rowData.receipt_method;
          newCell_8.innerHTML = rowData.note;

          newCell_0.setAttribute('style', 'text-align: center; background-color: #f2f2f2; border: none; color: #818181');
          newCell_1.contentEditable = true;
          newCell_2.contentEditable = true;
          newCell_3.contentEditable = true;
          newCell_4.contentEditable = true;
          newCell_5.contentEditable = true;
          newCell_6.contentEditable = true;
          newCell_7.contentEditable = true;
          newCell_8.contentEditable = true;

          newCell_4.classList.add('ifisweb');
          newCell_5.classList.add('ifisweb');
          newCell_6.classList.add('ifisweb');

          if (rowData.order_id != '' || rowData.order_name != '' || rowData.order_mail != '') {
            ifisweb = true;
          }
        });

        if (!ifisweb) {
          setTimeout(function() {
            const elems = document.querySelectorAll('.ifisweb');
            if (elems.length > 0) {
              elems.forEach(el => el.style.display = 'none');
            }
          }, 5);
        }

        winapp.innerHTML += `<br clear="all"><br>
        <div style="display: flex; flex-wrap: wrap; width: calc(100% - 35px); gap: 15px;">

          <div style="flex: 1 1 calc(33.333% - 10px); min-width: 250px; box-sizing: border-box;">
            <p class="label" style="margin-bottom: 5px;">Elsődlegesen fóliás raktárból szedje-e ki a rendelést:</p>
            <div class="checkbox-wrapper-34">
              <input class='tgl tgl-ios' id='winapp_primary_source' type='checkbox'>
              <label class='tgl-btn' for='winapp_primary_source'></label>
            </div>
          </div>

          <div style="flex: 1 1 calc(33.333% - 10px); min-width: 250px; box-sizing: border-box;">
            <p class="label" style="margin-bottom: 5px;">Vevőtípus:</p>
            <select id="winapp_customer_type" style="max-width: unset; width: 218px;">
              <?php echo $customer_type_selector;?>
            </select>
          </div>

          <div style="flex: 1 1 calc(33.333% - 10px); min-width: 250px; box-sizing: border-box;">
            <p class="label" style="margin-bottom: 5px;">Elsődleges raktár:</p>
            <select id="winapp_primary_warehouse" style="max-width: unset; width: 218px;">
              <option value="FŐ">FŐ raktár</option>
              <option value="PLEX">PLEX raktár</option>
            </select>
          </div>

        </div>

        `;

        winapp.innerHTML += '<br clear="all"><br><button onclick="ReservTableItem();" style="margin-top: 20px;">Termékek megrendelése</button><br><br>';
        winapp.innerHTML += '<p style="opacity: 0.6; text-align: center;">A <i>\'sor\'</i> oszlop a feldolgozott dokumentumban elfoglalt sort jelöli. A rendszer csak azokat a sorokat vette figyelembe, ahol a B oszlopban szám található, amit a matematikai szabályoknak megfelelően kerekített egész számra, ha szükséges volt!</p>';


        Loading(false);
      }
      function ReservTableItem() {
        var table = document.getElementById('reserv_table');
        var rows = table.getElementsByTagName('tr');
        var tableData = [];

        var order_primary_source = 0;
        if (document.getElementById("winapp_primary_source").checked) {
          var order_primary_source = 1;
        }
        var primary_warehouse = document.getElementById("winapp_primary_warehouse").value;
        var customer_type = document.getElementById("winapp_customer_type").value;

        for (var i = 1; i < rows.length; i++) {
          if (!rows[i].classList.contains('strike-row')) {
            var cells = rows[i].getElementsByTagName('td');
            var rowData = {
              line: cells[0].textContent.trim(),
              item_id: cells[1].textContent.trim(),
              amount: cells[2].textContent.trim(),
              reason: cells[3].textContent.trim(),
              order_id: cells[4].textContent.trim(),
              order_name: cells[5].textContent.trim(),
              order_mail: cells[6].textContent.trim(),
              receipt_method: cells[7].textContent.trim(),
              note: cells[8].textContent.trim(),
              primary_source: order_primary_source,
              primary_warehouse: primary_warehouse,
              customer_type: customer_type
            };
            tableData.push(rowData);
          }
        }

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

      }
      function SaveResult(isSuccess, WhyNot = "", line = "") {
        Loading(false);
        LoadTable();
        if (isSuccess) {
          GenerateAlerts("success", "Sikeresen megrendelve!");
          closewin();
        } else {
          GenerateAlerts("error", WhyNot.replaceAll('|', '<br>'), false);
          var ErrorLines = line.split('|');

          var table = document.getElementById('reserv_table');
          var rows = table.getElementsByTagName('tr');

          for (var i = 1; i < rows.length; i++) {
            var row = rows[i];
            var rowId = row.id;

            if (!ErrorLines.includes(rowId)) {
              row.classList.add('strike-row');

              var cells = row.getElementsByTagName('td');
              for (var j = 0; j < cells.length; j++) {
                cells[j].contentEditable = false;
              }
            }
          }
        }
      }

      /* Egyéb */
      function RecalcDailyStat() {
        FeedbackButtonStatus('loading', 'settings-recalcdailystat-button');
        get_POST_information("../managers/statistics.php?type=daily", '', function(text) {
          if (text == "Napi statisztika sikeresen frissítve.") {
            FeedbackButtonStatus('complete', 'settings-recalcdailystat-button');
            location.reload();
          } else {
            FeedbackButtonStatus('failed', 'settings-recalcdailystat-button');
            GenerateAlerts("error", text);
          }
        }, function() {
          FeedbackButtonStatus('failed', 'settings-recalcdailystat-button');
          GenerateAlerts("error", "Hálózati hiba!");
        });
      }

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

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

          <div class="container"><div class="header"><h1>Rendelés statisztika</h1><p>Valós idejű rendelés monitorozás</p></div>

          <div class="sections">

            <div class="section-group"><h2 class="section-group-title">Rendelések</h2>
            <div class="section"><h3 class="section-name">Összesítő</h3><div class="section-articles" id="orders_stat_box"></div></div>
              <div class="section"><h3 class="section-name">Classic</h3><div class="section-articles" id="orders_classic_stat_box"></div></div>
              <div class="section"><h3 class="section-name">Sporty</h3><div class="section-articles" id="orders_sporty_stat_box"></div></div>
              <div class="section"><h3 class="section-name">Fröccsöntött</h3><div class="section-articles" id="orders_injmold_stat_box"></div></div>
              <div class="section"><h3 class="section-name">ClimAir</h3><div class="section-articles" id="orders_climair_stat_box"></div></div>
            </div>

          </div>

        </div>`;

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

            CreateStatElement('orders_stat_box', "Teljesíthető", (response.classic.canFulfill + response.sporty.canFulfill + response.injmold.canFulfill + response.climair.canFulfill));
            CreateStatElement('orders_stat_box', "Nem Teljesíthető", (response.classic.cantFulfill + response.sporty.cantFulfill + response.injmold.cantFulfill + response.climair.cantFulfill));
            CreateStatElement('orders_stat_box', "Összesen", (response.classic.canFulfill + response.sporty.canFulfill + response.injmold.canFulfill + response.climair.canFulfill + response.classic.cantFulfill + response.sporty.cantFulfill + response.injmold.cantFulfill + response.climair.cantFulfill));

            CreateStatElement('orders_classic_stat_box', "Teljesíthető", response.classic.canFulfill);
            CreateStatElement('orders_classic_stat_box', "Nem Teljesíthető", response.classic.cantFulfill);
            CreateStatElement('orders_classic_stat_box', "Összesen", (response.classic.canFulfill + response.classic.cantFulfill));

            CreateStatElement('orders_sporty_stat_box', "Teljesíthető", response.sporty.canFulfill);
            CreateStatElement('orders_sporty_stat_box', "Nem Teljesíthető", response.sporty.cantFulfill);
            CreateStatElement('orders_sporty_stat_box', "Összesen", (response.sporty.canFulfill + response.sporty.cantFulfill));

            CreateStatElement('orders_injmold_stat_box', "Teljesíthető", response.injmold.canFulfill);
            CreateStatElement('orders_injmold_stat_box', "Nem Teljesíthető", response.injmold.cantFulfill);
            CreateStatElement('orders_injmold_stat_box', "Összesen", (response.injmold.canFulfill + response.injmold.cantFulfill));

            CreateStatElement('orders_climair_stat_box', "Teljesíthető", response.climair.canFulfill);
            CreateStatElement('orders_climair_stat_box', "Nem Teljesíthető", response.climair.cantFulfill);
            CreateStatElement('orders_climair_stat_box', "Összesen", (response.climair.canFulfill + response.climair.cantFulfill));

          } 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">Bal:</span>
                    <span class="article-card-value right">${value2}</span>
                  </div>
                  <div class="article-card-stat">
                    <span class="article-card-label">Jobb:</span>
                    <span class="article-card-value left">${value}</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">pár:</span>
                    <span class="article-card-value right">${value}</span>
                  </div>
                </div>
              </div>`;
        }
      }

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