<?php

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

if (!UserHasPerm('production_statistics')) {
  StopAndDie();
}

if (isset($_POST["func"])) {
  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"]) == "table") {
    $maxperpage = intval(htmlspecialchars($_POST["perpage"]));
    $cpage = intval(htmlspecialchars($_POST["cpage"]));

    $item_id = htmlspecialchars(str_replace(' ', '+', $_POST['item_id']));
    $score = htmlspecialchars($_POST["score"]);
    $under_production = htmlspecialchars($_POST["under_production"]);
    $under_boxing = htmlspecialchars($_POST["under_boxing"]);

    $addquery = "";
    $isfirst = true;

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

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

    if ($under_production == "1") {
      if ($isfirst) {
        $addquery = $addquery." WHERE under_production = '0'";
        $isfirst = false;
      } else {
        $addquery = $addquery." and under_production = '0'";
      }
    }

    if ($under_boxing == "1") {
      if ($isfirst) {
        $addquery = $addquery." WHERE under_boxing = '0'";
        $isfirst = false;
      } else {
        $addquery = $addquery." and under_boxing = '0'";
      }
    }

    if ($score != "") {
      if ($isfirst && $score == "priority_score") {
        $addquery = $addquery." WHERE priority_score IS NOT NULL";
      } else if ($score == "priority_score") {
        $addquery = $addquery." and priority_score IS NOT NULL";
      } else if ($isfirst && $score == "boxing_score") {
        $addquery = $addquery." WHERE boxing_score IS NOT NULL";
      } else if ($score == "boxing_score") {
        $addquery = $addquery." and boxing_score IS NOT NULL";
      }

      $addquery = $addquery." ORDER BY ".$score;
      $isfirst = false;
    }

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

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

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

    $sql = mysqli_query($conn,"SELECT param_value FROM system_params WHERE param_key = 'inventory_alert'");
    $inventory_alert = intval(mysqli_fetch_array($sql)[0]);

    $sql = mysqli_query($conn,"SELECT param_value FROM system_params WHERE param_key = 'box_alert'");
    $box_alert = intval(mysqli_fetch_array($sql)[0]);

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

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

        $sql = mysqli_query($conn,"SELECT total_consumption FROM statistics_annual WHERE item_id = '" . $statistics_daily['item_id'] . "' ORDER BY year DESC LIMIT 1");
        $av_prod_sql = mysqli_fetch_array($sql);
        $av_prod = "<span style='opacity: 0.7;'>N/A</span>";
        $is_new = "0";
        if ($av_prod_sql != null) {
          if ($av_prod_sql[0] != 0) {
            $av_prod = $av_prod_sql[0];
          }
        } else {
          $sql = mysqli_query($conn,"SELECT data_status FROM pr_parameters WHERE item_id = '" . $statistics_daily['item_id'] . "'");
          $data_stat = mysqli_fetch_array($sql)['data_status'];
          if ($data_stat == 1) {
            $is_new = "1";
          }
        }

        $stock_endurance = ($score === "priority_score") ? intval($statistics_daily['stock_endurance']) : intval($statistics_daily['stock_box_endurance']);
        $show_alert = ($score === "priority_score") ? $inventory_alert : $box_alert;

        if ($show_alert > $stock_endurance) {
          $stock_endurance = '<span style=\'color: #FF4D00;\'>' . $stock_endurance . '</span>';
        }

        $responseStr .= $statistics_daily['item_id'].'/!/'.$statistics_daily['warehouse_box'].'/!/'.(intval($statistics_daily['warehouse_total']) - intval($statistics_daily['warehouse_box'])).'/!/'.$stock_endurance.'/!/'.$av_prod.'/!/'.$statistics_daily['under_production'].'/!/'.$statistics_daily['under_boxing'].'/!/'.$is_new;
      }
    }

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

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

    $keys = ['default_average_production', 'default_total_consumption', 'inventory_holding', 'inventory_alert', 'box_holding', 'box_alert'];
    $placeholders = implode(',', array_fill(0, count($keys), '?'));

    $stmt = $conn->prepare("SELECT param_key, param_value FROM system_params WHERE param_key IN ($placeholders)");
    $stmt->bind_param(str_repeat('s', count($keys)), ...$keys);
    $stmt->execute();
    $result = $stmt->get_result();

    $params = [];
    while ($row = $result->fetch_assoc()) {
      $params[$row['param_key']] = $row['param_value'];
    }

    $sql = mysqli_query($conn,"SELECT day_date FROM statistics_daily ORDER BY day_date ASC LIMIT 1");
    $oldest_statistics = mysqli_fetch_array($sql)[0];
    $statistics_daily = date('Y.m.d. H:i', $oldest_statistics);

    echo json_encode([
      'default_average_production' => $params['default_average_production'],
      'default_total_consumption' => $params['default_total_consumption'],
      'inventory_holding' => $params['inventory_holding'],
      'inventory_alert' => $params['inventory_alert'],
      'box_holding' => $params['box_holding'],
      'box_alert' => $params['box_alert'],
      'statistics_daily' => $statistics_daily,
      'result' => 'ok'
    ]);
  } else if (htmlspecialchars($_POST["func"]) == "SaveSettings") {
    $params = [
      'default_total_consumption' => htmlspecialchars($_POST["default_total_consumption"]),
      'default_average_production' => htmlspecialchars($_POST["default_average_production"]),
      'inventory_holding' => htmlspecialchars($_POST["inventory_holding"]),
      'inventory_alert' => htmlspecialchars($_POST["inventory_alert"]),
      'box_holding' => htmlspecialchars($_POST["box_holding"]),
      'box_alert' => htmlspecialchars($_POST["box_alert"])
    ];

    $stmt = $conn->prepare("UPDATE system_params SET param_value = ? WHERE param_key = ?");

    foreach ($params as $key => $value) {
      $stmt->bind_param('ss', $value, $key);
      $stmt->execute();
    }
    $stmt->close();

    echo json_encode(['result' => 'ok']);
  } else if (htmlspecialchars($_POST["func"]) == "OpenInfo") {
    $item_id = htmlspecialchars(str_replace(' ', '+', $_POST['item_id']));

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

    $annual_result = mysqli_query($conn, "SELECT * FROM statistics_annual WHERE item_id = '$item_id' AND year = (SELECT MAX(year) FROM statistics_annual WHERE item_id = '$item_id') LIMIT 1");
    $statistics_annual = mysqli_fetch_assoc($annual_result);

    $sql = mysqli_query($conn,"SELECT * FROM system_params");
    $system_params = [];
    while ($row = mysqli_fetch_assoc($sql)) {
      $system_params[$row['param_key']] = $row['param_value'];
    }

    echo json_encode([
      'day_date' => date('Y.m.d. H:i', $statistics_daily['day_date']) ?? 'N/A',
      'year' => $statistics_annual['year'] ?? 'N/A',
      'warehouse_total' => $statistics_daily['warehouse_total'] ?? 'N/A',
      'stock_endurance' => $statistics_daily['stock_endurance'] ?? 'N/A',
      'under_production' => $statistics_daily['under_production'] ?? 'N/A',
      'under_boxing' => $statistics_daily['under_boxing'] ?? 'N/A',
      'under_sales' => $statistics_daily['under_sales'] ?? 'N/A',
      'total_consumption' => $statistics_annual['total_consumption'] ?? 'N/A',
      'average_production' => $statistics_annual['average_production'] ?? 'N/A',
      'average_scrap' => $statistics_annual['average_scrap'] ?? 'N/A',
      'inventory_alert' => $system_params['inventory_alert'],
      'warehouse_box' => $statistics_daily['warehouse_box'] ?? 'N/A',
      'warehouse_foil' => (intval($statistics_daily['warehouse_total']) - intval($statistics_daily['warehouse_box'])) ?? 'N/A',
      'stock_box_endurance' => $statistics_daily['stock_box_endurance'] ?? 'N/A',
      'free_stock' => $statistics_daily['free_stock'] ?? 'N/A',
      'result' => 'ok'
    ]);

  } else if (htmlspecialchars($_POST["func"]) == "CreateProduction") {
    $item_id = htmlspecialchars(str_replace(' ', '+', $_POST['item_id']) ?? '');
    $category = htmlspecialchars($_POST['type'] ?? '');

    /* Tábla validálás */
    $validCategories = [
      'classic' => 'production_classic',
      'injmold' => 'production_injmold',
      'sporty'  => 'production_sporty'
    ];

    if (!array_key_exists($category, $validCategories)) {
      echo json_encode(['result' => 'Érvénytelen típus']);
      exit;
    }

    $sql_table = $validCategories[$category];

    /* Gyártandó termék mennyisége */
    $sql = mysqli_query($conn,"SELECT * FROM statistics_daily WHERE item_id = '$item_id'");
    $statistics_daily = mysqli_fetch_array($sql);

    if ($statistics_daily['priority_score'] == null || $statistics_daily['priority_score'] == '') {
      echo json_encode(['result' => 'Ez a cikkszám nem vehető fel gyártásba!']);
      exit();
    }

    $annual_result = mysqli_query($conn, "SELECT * FROM statistics_annual WHERE item_id = '$item_id' AND year = (SELECT MAX(year) FROM statistics_annual WHERE item_id = '$item_id') LIMIT 1");
    $statistics_annual = mysqli_fetch_assoc($annual_result);

    $sql = mysqli_query($conn,"SELECT * FROM system_params");
    $system_params = [];
    while ($row = mysqli_fetch_assoc($sql)) {
      $system_params[$row['param_key']] = $row['param_value'];
    }

    $daily_consumption = ($statistics_annual["total_consumption"] ?? $system_params["default_total_consumption"]) / 365;
    $inventory_holding_amount = $daily_consumption * ($system_params["inventory_holding"] + ($statistics_annual['average_production'] ?? $system_params['default_average_production']));
    $to_invholding = $inventory_holding_amount - ($statistics_daily["warehouse_total"] ?? 0) + ($statistics_annual['average_scrap'] ?? 0);

    $db_start = ceil($to_invholding / 10) * 10;

    /* SQL */
    $sql = mysqli_query($conn,"INSERT INTO $sql_table(item_id, db_start) VALUES ('$item_id', $db_start)");
    $prid = mysqli_insert_id($conn);

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

    /* Táblázati adatok kitöltése */
    if ($category == "classic" || $category == "sporty") {
      $sql = mysqli_query($conn,"SELECT tablesize_x, tablesize_y FROM pr_cutting_parameters WHERE item_id = '$item_id'");
      $pr_cutting_parameters = mysqli_fetch_array($sql);
      if ($pr_cutting_parameters != null) {
        $tablesize_x = intval($pr_cutting_parameters['tablesize_x']) ?? 0;
        $tablesize_y = intval($pr_cutting_parameters['tablesize_y']) ?? 0;

        $sql = mysqli_query($conn,"SELECT sum(left_db) as left_db, sum(right_db) as right_db FROM warehouse_foil WHERE item_id = '$item_id'");
        $value = mysqli_fetch_array($sql);

        $difference = intval($value["left_db"]) - intval($value["right_db"]);
        $remain_l = abs($difference);
        $remain_r = abs($difference);
        if ($difference > 0) {
          $remain_r = 0;
        } else {
          $remain_l = 0;
        }

        $sql = mysqli_query($conn,"UPDATE $sql_table SET tablesize_x = $tablesize_x, tablesize_y = $tablesize_y, remain_r = $remain_r, remain_l = $remain_l WHERE pr_id = '$prid'");
      }
    }

    echo json_encode(['result' => 'ok', 'db_start' => $db_start]);

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

    $annual_result = mysqli_query($conn, "SELECT * FROM statistics_annual WHERE item_id = '$item_id' AND year = (SELECT MAX(year) FROM statistics_annual WHERE item_id = '$item_id') LIMIT 1");
    $statistics_annual = mysqli_fetch_assoc($annual_result);

    $sql = mysqli_query($conn,"SELECT warehouse_total, warehouse_box FROM statistics_daily WHERE item_id = '$item_id'");
    $statistics_daily = mysqli_fetch_array($sql);

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

    $sql = mysqli_query($conn,"SELECT * FROM system_params");
    $system_params = [];
    while ($row = mysqli_fetch_assoc($sql)) {
      $system_params[$row['param_key']] = $row['param_value'];
    }

    $in_foil_warehouse = intval($statistics_daily['warehouse_total']) - intval($statistics_daily['warehouse_box']);
    $daily_consumption = ($statistics_annual["total_consumption"] ?? $system_params["default_total_consumption"]) / 365;

    $need_to_box = intval($system_params['box_holding']) * $daily_consumption - intval($statistics_daily['warehouse_box']);
    if ($pr_parameters['front_and_rear'] == 'első') {
      $len = strlen($item_id);
      if ($len < 4) {
        $padded = str_pad($item_id, 4, '0', STR_PAD_LEFT);
      } else {
        $padded = $item_id;
      }
      $searchItem_ID = $padded.'+____';

      $need_to_box_set = 0;

      $sql = mysqli_query($conn,"SELECT item_id, warehouse_box FROM statistics_daily WHERE item_id LIKE '$searchItem_ID'");
      while ($row = mysqli_fetch_assoc($sql)) {
        $c_item_id = $row['item_id'];
        $annual_result_set = mysqli_query($conn, "SELECT * FROM statistics_annual WHERE item_id = '$c_item_id' AND year = (SELECT MAX(year) FROM statistics_annual WHERE item_id = '$c_item_id') LIMIT 1");
        $statistics_annual_set = mysqli_fetch_assoc($annual_result_set);
        $daily_consumption_set = ($statistics_annual_set["total_consumption"] ?? $system_params["default_total_consumption"]) / 365;

        $need_to_box_set += max(0, intval($system_params['box_holding']) * $daily_consumption_set - intval($row['warehouse_box']));
      }

      if ($need_to_box + $need_to_box_set > 0) {
        $ratio = $need_to_box_set / ($need_to_box + $need_to_box_set);
        $rationed = $ratio * $in_foil_warehouse;
        $need_to_box = min($need_to_box, max(0, $rationed));
      }
    }

    $min_db = min(max(5, ceil($need_to_box)), $in_foil_warehouse);

    $sql = mysqli_query($conn,"INSERT INTO production_boxing(item_id, db_start) VALUES ('$item_id', $min_db)");
    echo json_encode(['result' => 'ok', 'db_start' => $min_db]);

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

  } else if (htmlspecialchars($_POST["func"]) == "statistics") {
  	$data = [];

    // Classic adatok
    $classicQuery = "SELECT stage, COUNT(*) as item_count, SUM(db_start) as total_db_start FROM production_classic WHERE stage != 0 GROUP BY stage";
    $classicResult = $conn->query($classicQuery);
    if ($classicResult) {
    	while ($row = $classicResult->fetch_assoc()) {
    		$data[] = [
    			'stage' => $row['stage'],
    			'item_count' => $row['item_count'],
    			'is_boxing' => false,
    			'type' => 'classic',
    			'db_start' => $row['total_db_start']
        ];
    	}
    }

    // Sports adatok
    $sportyQuery = "SELECT stage, COUNT(*) as item_count, SUM(db_start) as total_db_start FROM production_sporty WHERE stage != 0 GROUP BY stage";
    $sportyResult = $conn->query($sportyQuery);
    if ($sportyResult) {
    	while ($row = $sportyResult->fetch_assoc()) {
    		$data[] = [
    			'stage' => $row['stage'],
    			'item_count' => $row['item_count'],
    			'is_boxing' => false,
    			'type' => 'sporty',
          'db_start' => $row['total_db_start']
    		];
    	}
    }

    // Injmold adatok
    $injmoldQuery = "SELECT stage, COUNT(*) as item_count, SUM(db_start) as total_db_start FROM production_injmold WHERE stage != 0 GROUP BY stage";
    $injmoldResult = $conn->query($injmoldQuery);
    if ($injmoldResult) {
    	while ($row = $injmoldResult->fetch_assoc()) {
    		$data[] = [
    			'stage' => $row['stage'],
    			'item_count' => $row['item_count'],
    			'is_boxing' => false,
    			'type' => 'injmold',
          'db_start' => $row['total_db_start']
    		];
    	}
    }

    // Boxing adatok
    $boxingQuery = "SELECT stage, COUNT(*) as item_count, SUM(db_start) as total_db_start,
        CASE
            WHEN SUBSTRING_INDEX(item_id, '+', 1) REGEXP '^[0-9]+$' THEN 'classic'
            WHEN SUBSTRING_INDEX(item_id, '+', 1) REGEXP '^CL[P|M]?[0-9]+$' THEN 'climair'
            WHEN SUBSTRING_INDEX(item_id, '+', 1) REGEXP '^FR[0-9]{4}$' THEN 'injmold'
            WHEN SUBSTRING_INDEX(item_id, '+', 1) REGEXP '^F[0-9]{4}$' THEN 'sporty'
            ELSE 'unknown'
        END AS category
    FROM production_boxing
    WHERE stage != 0
    GROUP BY stage, category";

    $boxingResult = $conn->query($boxingQuery);
    if ($boxingResult) {
    	while ($row = $boxingResult->fetch_assoc()) {
    		$data[] = [
    			'stage' => $row['stage'],
    			'item_count' => $row['item_count'],
    			'is_boxing' => true,
    			'type' => $row['category'],
    			'db_start' => $row['total_db_start']
    		];
    	}
    }


    // Összesítő: classic, sporty, injmold
    $stageTypes = [];
    $totals = [];

    foreach ($data as $item) {
    	if (in_array($item['type'], ['classic', 'sporty', 'injmold'])) {
    		$stage = $item['stage'];
    		$isBoxing = $item['is_boxing'] ? 'boxing' : 'production';

    		if (!isset($stageTypes[$stage])) {
    			$stageTypes[$stage] = [];
    		}
    		$stageTypes[$stage][] = $item['type'];

    		$key = $stage . '_' . $isBoxing;

    		if (!isset($totals[$key])) {
    			$totals[$key] = [
    				'stage' => $stage,
    				'item_count' => 0,
    				'is_boxing' => $item['is_boxing'],
    				'type' => 'total',
    				'db_start' => 0
    			];
    		}
    		$totals[$key]['item_count'] += $item['item_count'];
    		$totals[$key]['db_start'] += $item['db_start'];
    	}
    }

    foreach ($totals as $key => $total) {
    	list($stage, $isBoxing) = explode('_', $key);

    	$boxingTypes = array_filter($stageTypes[$stage], function($type) use ($data, $stage, $isBoxing) {
    		foreach ($data as $item) {
    			if ($item['stage'] == $stage && $item['type'] == $type &&
    				($item['is_boxing'] ? 'boxing' : 'production') == $isBoxing) {
    				return true;
    			}
    		}
    		return false;
    	});

    	if (count(array_unique($boxingTypes)) > 1) {
    		$data[] = $total;
    	}
    }


  	echo json_encode(['result' => 'ok', 'data' => $data]);
  }
  exit();
}

?>

<!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>
    .InfoBox .panel {
    	transition: all 0.2s ease;
    	overflow: hidden;
    }

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

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

    .InfoBox .panel-collapsed .panel-content {
    	opacity: 0;
      pointer-events: none;
	    user-select: none;
    }

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

    .InfoBox .panel-collapsed .panel-header {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100%;
      min-height: 35px;
      opacity: 0.4;
      cursor: pointer;
    }
    .InfoBox .panel-collapsed .panel-header:hover {
      opacity: 1;
    }

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

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

      <h1>Gyártástervező</h1>

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


      <div style="width: 100%; min-height: 85px;">
        <div style="display: inline; float: left;">
          <p>Cikkszám: </p>
          <input type="text" id="filter-item_id" placeholder="Cikkszám..." autocomplete="off" style="width: 147px; height: 17px;" onkeydown="if (event.keyCode == 13) {SendFilter();}">
        </div><div style="display: inline; float: left; padding-left: 15px;">
          <p>Rendezés: </p>
          <select id="filter-score" onchange="SendFilter();">
            <option value="priority_score">Gyártásterv</option>
            <option value="boxing_score">Dobozolásterv</option>
          </select>
        </div><div style="display: inline; float: left; padding-left: 15px; width: 155px;">
          <p>Gyártás alatt lévők: </p>
          <div class="checkbox-wrapper">
            <input type="checkbox" id="filter-under_production" onclick="SendFilter();">
          	<label for="filter-under_production" style="margin-left: 0px;">Elrejtés</label>
          </div>
        </div><div style="display: inline; float: left; padding-left: 15px; width: 155px;">
          <p>Dobozolás alatt lévők: </p>
          <div class="checkbox-wrapper">
            <input type="checkbox" id="filter-under_boxing" onclick="SendFilter();">
          	<label for="filter-under_boxing" style="margin-left: 0px;">Elrejtés</label>
          </div>
        </div><div style="display: inline; float: left; padding-left: 15px;">
          <p>Oldalanként: </p>
          <select id="filter-perpage" onchange="SendFilter();"><option value="25">25 db / oldal</option></select>
        </div><div style="display: inline; float: left; padding-left: 15px;">
          <p style="color: #f5f5f5;">: </p>
          <button onclick="SendFilter();">Szűrés</button>
        </div>

        <div style="display: inline; float: right; padding-right: 15px;">
          <p style="color: #f5f5f5;">: </p>
          <a title="Beállítások"><i class="icon" onclick="OpenSettings();" style="width: 35px; height: 35px; opacity: 0.6;"><i data-feather="settings"></i></i></a>
        </div>

      </div>

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

      <div style="width: 100%; margin-left: 10px; margin-top: 10px; display: inline; float: left;">
        <div class="tables" style="width: 100%">
          <table id="table">
            <thead>
              <tr style="top: 0px; position: sticky; z-index: 1;">
                <th>Cikkszám</th>
                <th>Raktáron</th>
                <th>Készletkitartás <small style='opacity: 0.8;'>nap</small></th>
                <th>Éves fogyás</th>
                <th style="width: 100px;">Info</th>
              </tr>
            </thead>

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

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

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

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

    </div>
    <script src="../js/default.js" type="text/javascript"></script>
    <script type="text/javascript">
      feather.replace();

      function LoadFilter() {
        const body = 'func=filter';
        get_POST_information("productionstat.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 item_id = document.getElementById('filter-item_id').value;
        var score = document.getElementById('filter-score').value;
        if (document.getElementById('filter-under_production').checked) { under_production = 1; } else { under_production = 0; }
        if (document.getElementById('filter-under_boxing').checked) { under_boxing = 1; } else { under_boxing = 0; }

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

        const body = 'func=table&perpage=' + perpage + '&cpage=' + cpage + '&under_production=' + under_production + '&under_boxing=' + under_boxing + '&item_id=' + encodeURIComponent(item_id).replace(/%20/g, '+') + '&score=' + score;

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

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

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

                newCell_1.innerHTML = datas[0];
                newCell_2.innerHTML = "<div style='float:left;'>" + datas[1] + " <small style='opacity: 0.8;'>doboz</small></div><div style='float:right;'>" + datas[2] + " <small style='opacity: 0.8;'> pár fóliás</small></div>";
                newCell_3.innerHTML = datas[3];
                newCell_4.innerHTML = datas[4];
                newCell_5.innerHTML = '<a style="cursor: pointer;" onclick="OpenInfo(\'' + datas[0] + '\')">Megnyitás</button>';

                var margin_left = "10px";
                if (datas[5] == "1") {
                  margin_left = "35px";
                  newCell_1.innerHTML += `<img style='margin-left: 10px; height: 20px; position: absolute;' title='Gyártás alatt' src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAYAAAAeP4ixAAAACXBIWXMAAAsTAAALEwEAmpwYAAADjElEQVR4nO2aXahUVRTH902h8gMjU0E0Rcyz1txUuBeUwI8CIa2HoqLHIATxKR8sStHWOnMxEhXRB8EXIXoobvmB1j1rzVRDYAa9WSqIRIlC+pCg4gfevCN7Prhzz5wzZ+ZOng/0D/vlsPdh/87a/7XX3jPGPIrKUXGFs/PYVJNlAesWZC0jy5+YL7xgsigkXQUsw1UQLTssm03WtHDH0AwkuVyHANK/cyTPmkyJ6Alg9eoQlUbyocmakAubxkBUQUaAdP88Kj1lsiIgPdAAcRhZ91qQmun/cPLFxSYrJsdaplpKpWfsM8ctvAqs/9Se30HSD4wp95i0C11v5Ys7fpjVlABYT4wuN/0JWddnAqhZ5R4kyTf6B0g+MVkUsHw5BoTlR5M1ARUXIel/voh8GtY/R6UpSN67wPIxkG7oHZC5Jo3RQNbrYRtljmQtsFz1Qd8DFkrUVxAUDZaBwL557UfSu037URrKHeggGsDyfRhELePd6Kfjk1IdDWMzm91rWoHYqLjySvKZiuSef5+pazWVJiLr/SgQcL3X05CpBluOYT3bemnJSI6Kz8dHYSqT2h4wmdNAXl/YGCRvY8tosB41cSvH8n7wZGQYSXcv2aWTm0eVe4D0UEg0frflTuwgq6k0EVh+bvGF/0JX1wWNdVx5u5rB5DySnETWjxLJVnU5VJgNJFciUuopu8ujq8vN4OAEk1Y55L3sN324B+SmrZRtWRK7qdsRkm5rB6QJjPSM3XcS8UboeZ5kaDwwtWz1rz3rmDQIPitOB5aL44YhvZaaKhhdb+V4QWop+IhJjfG5C5AKTOG1pDmMNW63IMB6IfHrJWT5teuIVKOyNTGIBZ8XpzXeCbdr8JCo3MKB7+YlAoKu90aHxh6xl3rAeimkz+FEQOzVaYdL6HR1nNdXiUBajA8k5zozteyrj82RvjN6/TrW+Av3DT0Za/HYcXYi763Gd/gv+DAJ4wPJe536YxGVngs4038V0Pe2Q978WECQ9Yvx+MOvOXtOPQ2kvzXD6LexgLTIPJH+CFymDb+KYb2FHNL+N/XmC9itP4Iu8sCXyR668cH1XkLWg500WylHvRdJ3vSPy5Ese2ggmZFTWbPemjQ2hwqz24Kwa7nT+inOBizDUX6rCFl/SXqyGL0nnWwjIjKY+EQ5KgPq15Eg9soGWL6xqa/yv5MUNWC9YD/0EtKZbfnksR7LdK0HngfOl1qKuVUAAAAASUVORK5CYII=' alt='construction-worker'>`;
                }

                if (datas[6] == "1") {
                  newCell_1.innerHTML += `<img style='margin-left: ${margin_left}; height: 20px; position: absolute;' title='Dobozolás alatt' src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAYAAAAeP4ixAAAACXBIWXMAAAsTAAALEwEAmpwYAAADZklEQVR4nO2aW4hNYRSAl3suT8ql3ErDrLVHQyheNA+SB+NaXpVHhZRHaq1tDDE8KIknbx4mT4w5a51hTlGUS8iLKEIhjPs1zOg/zugYZ875d7bmP/jqr3PZe5/9tdf617/22QD/+QeJOLuCxHLI+tYN97o2tuVQTZDYbhLrKTVQtBmq6Er0lBvI2gihQ2K5SiLE1gmhg6JvPERew18hIvYKQofYOivmiOgZCB1kbawoEmeWQTWAbDvLXI0mqCaQtdGFkMuZwjhTNVei6oi4dXgkuolEL+SXH2yvie08iW5o4NxQqAZm7Dw9Cdmu9Z/MeqmebTyEzDw+MYrErntMr1fdthAqJHrUo9gVqrcegxBB1o3eEoVRK7oVQgI5uxDFPiUVIbYvtXF2KYRAPdt4FHuQWOJHvljXDO6YPqASDZwb6rN2+lMDRc+lIoKsewdKggojBYnMGmLtTpAPN5HtuUeo3SbWVZV+n9IQQe6YSawv/SX0WcRaQ7EtyFd5P/HOiG3OHxOpOdA+gkRvJEjmTxRnFv04gTi7mEQ/eMp8ceELra1DUhdB1i1JYjgSXf/LMWJdQqJP/Y+j21IXcWulBHmxr7/jRNw2MUFo3kldBMXe+YWUnioVEqVOhlgPEtvHMuH5IHURd2PAU+RqfYuN9hFxr+uadAqyHSq1QkCxltRFXCeXILSOA/QM8hHpJeKOqQWhLjfboViL62/SF4kzy5IkO7FJEhFf6HdF8jKizQkStTuKs2uDFHEg6zrfxCfW97WcnQ8hijiQM3NJ7K5n8t+raW4fByGKOCLWscja7iXDehiKSJRrUnpAqjAPRlEmsa8VEv9h8W5uGf47Esh2Nl0RAJi8//xIVzvKh5c9gpCZd+TyMBI7mTS0woJ5sLsj4iFxy+UThEnPIBI74hHL96mpbZrbY1bz6QkQGii6p3INsSd1O7Lkti80VjchJIhtu0fteNHb5dXt0Nnuvfu8V2zAwTjbUKlfz1f9Qmfo2lw3YxVdpc0QAijWUSGcProusGg1e7/P920QAtj3xH4Op88Y2+qiqn+rxAz2GEIA++tJWLvdYrJ3u4hzYwqPZ5St8AMGlrqn9V1iY99tXd9eQno3hALFmZUkduX7QzF2sb+ew1V91+Xl75qwPiPWXVXzr9V/IF2+AY4NiVSfCQlXAAAAAElFTkSuQmCC' alt='manual-handling'>`;
                  if (datas[5] == "1") {
                    margin_left = "60px";
                  } else {
                    margin_left = "35px";
                  }
                }

                if (datas[7] == "1") {
                  newCell_1.innerHTML += `<span style='margin-left: ${margin_left}; height: 20px; position: absolute; color: var(--panelcolor); font-size: 14px; font-weight: bold; margin-top: 3px; cursor: default;' title='Új termék'>Új!</span>`;

                }

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

      function OpenSettings() {
        Loading();
        openwin();
        wintitle.innerHTML = "Beállítások";
        winapp.innerHTML = '<div id="errorDIV"></div>';
        const body = 'func=OpenSettings';
        get_POST_information("productionstat.php", body, function(text) {
          Loading(false);
          let response = JSON.parse(text);
          if (response.result == "ok") {
            winapp.innerHTML += '<p style="color: #333333; margin-bottom: 0px; margin-left: 0px; font-size: 23px; font-weight: bold;">Beállítások</p>';
            winapp.innerHTML += `<p style="opacity: 0.8; margin-top: 0px;">Alapértelmezett paraméterek, statisztikai beállítások</p><br>
            <button class="Feedback" id="settings-save-button" style="position: absolute; width: 70px; right: 57px; top: 80px;" onclick="SaveSettings();"><span class="button-text">Mentés</span><div class="loader"></div><div class="checkmark">✔</div><div class="crossmark">✖</div></button>
            <p style="width: calc(100% - 35px); border-bottom: 1px solid #bdc3c7; margin-top: 5px;"></p>`;

            winapp.innerHTML += `<div style="margin-bottom: 15px; height: 87px;">
              <div style="display: inline; float: left;">
                <p style="font-weight: bold;">Éves fogyás: </p>
                <input value="${response.default_total_consumption}" defaultValue="${response.default_total_consumption}" onblur="if(this.value !== this.defaultValue) { SaveSettings(); this.defaultValue = this.value; }" type="number" id="default_total_consumption" min="0" placeholder="Éves fogyás..." autocomplete="off" style="width: 147px; height: 17px;">
              </div><div style="display: inline; float: left; margin-left: 15px; padding-left: 15px; height: 87px; width: calc(100% - 230px); border-left: 1px solid #bdc3c7;">
                <p style="text-align: justify;">Az éves fogyást határozza meg, hogyha az adott cikkszámnak nincsen erre vonatkozó paramétere.</p>
              </div>
            </div>`;

            winapp.innerHTML += `<div style="margin-bottom: 15px; height: 87px;">
              <div style="display: inline; float: left;">
                <p style="font-weight: bold;">Gyártási átlagidő: </p>
                <input value="${response.default_average_production}" defaultValue="${response.default_average_production}" onblur="if(this.value !== this.defaultValue) { SaveSettings(); this.defaultValue = this.value; }" type="number" id="default_average_production" min="0" placeholder="Gyártási átlagidő..." autocomplete="off" style="width: 147px; height: 17px;">
              </div><div style="display: inline; float: left; margin-left: 15px; padding-left: 15px; height: 87px; width: calc(100% - 230px); border-left: 1px solid #bdc3c7;">
                <p style="text-align: justify;">Átlagos gyártási időt határozza meg napokban, hogyha az adott cikkszámnak nincsen erre vonatkozó paramétere.</p>
              </div>
            </div>`;

            winapp.innerHTML += `<div style="margin-bottom: 15px; height: 87px;">
              <div style="display: inline; float: left;">
                <p style="font-weight: bold;">Készletkitartás: </p>
                <input value="${response.inventory_holding}" defaultValue="${response.inventory_holding}" onblur="if(this.value !== this.defaultValue) { SaveSettings(); this.defaultValue = this.value; }" type="number" id="inventory_holding" min="0" placeholder="Készletkitartás..." autocomplete="off" style="width: 147px; height: 17px;">
              </div><div style="display: inline; float: left; margin-left: 15px; padding-left: 15px; height: 87px; width: calc(100% - 230px); border-left: 1px solid #bdc3c7;">
                <p style="text-align: justify;">Napokban kifejezi azt hogy hány napos készletre tervezzen a gyártásnál.</p>
              </div>
            </div>`;

            winapp.innerHTML += `<div style="margin-bottom: 15px; height: 87px;">
              <div style="display: inline; float: left;">
                <p style="font-weight: bold;">Kritikus készlet: </p>
                <input value="${response.inventory_alert}" defaultValue="${response.inventory_alert}" onblur="if(this.value !== this.defaultValue) { SaveSettings(); this.defaultValue = this.value; }" type="number" id="inventory_alert" min="0" placeholder="Kritikus készlet..." autocomplete="off" style="width: 147px; height: 17px;">
              </div><div style="display: inline; float: left; margin-left: 15px; padding-left: 15px; height: 87px; width: calc(100% - 230px); border-left: 1px solid #bdc3c7;">
                <p style="text-align: justify;">Napokban kifejezi azt, mikortól jelezze a rendszer, hogy egy terméket fel kell venni gyártásba.</p>
              </div>
            </div>`;

            winapp.innerHTML += `<div style="margin-bottom: 15px; height: 87px;">
              <div style="display: inline; float: left;">
                <p style="font-weight: bold;">Dobozos készlet: </p>
                <input value="${response.box_holding}" defaultValue="${response.box_holding}" onblur="if(this.value !== this.defaultValue) { SaveSettings(); this.defaultValue = this.value; }" type="number" id="box_holding" min="0" placeholder="Dobozos készlet..." autocomplete="off" style="width: 147px; height: 17px;">
              </div><div style="display: inline; float: left; margin-left: 15px; padding-left: 15px; height: 87px; width: calc(100% - 230px); border-left: 1px solid #bdc3c7;">
                <p style="text-align: justify;">Napokban kifejezi azt hogy hány napos készletre tervezzen a dobozolásnál.</p>
              </div>
            </div>`;

            winapp.innerHTML += `<div style="margin-bottom: 15px; height: 87px;">
              <div style="display: inline; float: left;">
                <p style="font-weight: bold;">Krit. dobozos készlet: </p>
                <input value="${response.box_alert}" defaultValue="${response.box_alert}" onblur="if(this.value !== this.defaultValue) { SaveSettings(); this.defaultValue = this.value; }" type="number" id="box_alert" min="0" placeholder="Kritikus dobozos készlet..." autocomplete="off" style="width: 147px; height: 17px;">
              </div><div style="display: inline; float: left; margin-left: 15px; padding-left: 15px; height: 87px; width: calc(100% - 230px); border-left: 1px solid #bdc3c7;">
                <p style="text-align: justify;">Napokban kifejezi azt, mikortól jelezze a rendszer, hogy egy terméket fel kell venni dobozolásra.</p>
              </div>
            </div>`;

            winapp.innerHTML += `<div style="margin-bottom: 15px; height: 87px;">
              <div style="display: inline; float: left;">
                <p style="font-weight: bold;">Napi statisztika: </p>
                <button class="Feedback" id="settings-recalcdailystat-button" style="width: 165px;" onclick="RecalcDailyStat();"><span class="button-text">Újraszámolás</span><div class="loader"></div><div class="checkmark">✔</div><div class="crossmark">✖</div></button>
              </div><div style="display: inline; float: left; margin-left: 15px; padding-left: 15px; height: 87px; width: calc(100% - 230px); border-left: 1px solid #bdc3c7;">
                <p style="text-align: justify;">A gombra rányomva újraszámolja a napi statisztikát a mostani időpillanatban aktuális raktárkészlettel.</p>
                <p style="text-align: justify;">Legutóbbi statisztika: <span style="color: var(--panelcolor);">${response.statistics_daily}</span></p>
              </div>
            </div>`;

          } else {
            GenerateAlerts("error", response.result);
          }
        }, function() {
          Loading(false);
          GenerateAlerts("error", "Hálózati hiba!");
        });
      }
      var isSaving = false;
      function SaveSettings() {
        if (isSaving) {return;}
        FeedbackButtonStatus('loading', 'settings-save-button');

        var default_total_consumption = document.getElementById("default_total_consumption").value;
        var default_average_production = document.getElementById("default_average_production").value;
        var inventory_holding = document.getElementById("inventory_holding").value;
        var inventory_alert = document.getElementById("inventory_alert").value;
        var box_holding = document.getElementById("box_holding").value;
        var box_alert = document.getElementById("box_alert").value;

        const body = 'func=SaveSettings&default_total_consumption=' + encodeURIComponent(default_total_consumption).replace(/%20/g, '+')
                      + '&default_average_production=' + encodeURIComponent(default_average_production).replace(/%20/g, '+')
                      + '&inventory_holding=' + encodeURIComponent(inventory_holding).replace(/%20/g, '+')
                      + '&inventory_alert=' + encodeURIComponent(inventory_alert).replace(/%20/g, '+')
                      + '&box_holding=' + encodeURIComponent(box_holding).replace(/%20/g, '+')
                      + '&box_alert=' + encodeURIComponent(box_alert).replace(/%20/g, '+');

        get_POST_information("productionstat.php", body, function(text) {
          isSaving = false;
          let response = JSON.parse(text);
          if (response.result == "ok") {
            FeedbackButtonStatus('complete', 'settings-save-button');
          } else {
            FeedbackButtonStatus('failed', 'settings-save-button');
            GenerateAlerts("error", response.result);
          }
        }, function() {
          isSaving = false;
          FeedbackButtonStatus('failed', 'settings-save-button');
          GenerateAlerts("error", "Hálózati hiba!");
        });


      }
      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 OpenInfo(item_id) {
        Loading();
        openwin();
        wintitle.innerHTML = "Adatlap - " + item_id;
        winapp.innerHTML = '<div id="errorDIV"></div>';
        const body = 'func=OpenInfo&item_id=' + encodeURIComponent(item_id).replace(/%20/g, '+');
        get_POST_information("productionstat.php", body, function(text) {
          Loading(false);
          let response = JSON.parse(text);
          if (response.result == "ok") {

            var stock_endurance_color = 'var(--panelcolor)';
            if (response.stock_endurance != 'N/A' && parseInt(response.stock_endurance) < parseInt(response.inventory_alert)) {
              stock_endurance_color = '#FF4D00';
            }

            var boxingbutton = 'disabled';
            if (response.warehouse_foil != 'N/A' && parseInt(response.warehouse_foil) > 0) {
              boxingbutton = '';
            }

            winapp.innerHTML += `<p style="color: #333333; margin-bottom: 0px; margin-left: 0px; font-size: 23px; font-weight: bold;">Adatlap - <span style="color: var(--panelcolor);">${item_id}</span></p>
            <p style="opacity: 0.8; margin-top: 0px;">A cikkszámra vonatkozó gyártási és dobozolási paraméterek</p><br>
            <p style="width: calc(100% - 35px); border-bottom: 1px solid #bdc3c7; margin-top: 5px;"></p>
            <div style="display: flex; align-items: stretch;" class="InfoBox">

              <div id="productionPanel" class="panel panel-collapsed" style="flex: 1; position: relative; padding-bottom: 35px;">
                <p class="panel-header" onclick="toggleInfoPanel('productionPanel')">Gyártási paraméterek</p>
                <div class="panel-content">
                  <p title="${response.day_date}" style="cursor: help;"><b>Raktárkészlet:</b><span style="color: var(--panelcolor); margin-left: 5px;">${response.warehouse_total}</span> <small style="opacity: 0.8;">pár</small></p>
                  <p title="${response.day_date}" style="cursor: help;"><b>Szabad raktárkészlet:</b><span style="color: var(--panelcolor); margin-left: 5px;">${response.free_stock}</span> <small style="opacity: 0.8;">pár</small></p>
                  <p title="${response.day_date}" style="cursor: help;"><b>Rendelés alatt:</b><span style="color: var(--panelcolor); margin-left: 5px;">${response.under_sales}</span> <small style="opacity: 0.8;">pár</small></p>
                  <p title="${response.day_date}" style="cursor: help;"><b>Készlet kitartás:</b><span style="color: ${stock_endurance_color}; margin-left: 5px;">${response.stock_endurance}</span> <small style="opacity: 0.8;">nap</small></p>
                  <p title="${response.year}" style="cursor: help;"><b>Éves fogyás:</b><span style="color: var(--panelcolor); margin-left: 5px;">${response.total_consumption}</span> <small style="opacity: 0.8;">pár</small></p>
                  <p title="${response.year}" style="cursor: help;"><b>Gyártási átlagidő:</b><span style="color: var(--panelcolor); margin-left: 5px;">${response.average_production}</span> <small style="opacity: 0.8;">nap</small></p>
                  <p title="${response.year}" style="cursor: help;"><b>Átlag selejtszám:</b><span style="color: var(--panelcolor); margin-left: 5px;">${response.average_scrap}</span> <small style="opacity: 0.8;">pár</small></p>

                  <button onclick="StartProduction('${item_id}', '${response.under_production}');" style="position: absolute; bottom: 0px; right: 0px;">Felvétel gyártásba</button>
                </div>
              </div>

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

              <div id="boxingPanel" class="panel panel-collapsed" style="flex: 1; position: relative; padding-bottom: 35px;">
                <p class="panel-header" onclick="toggleInfoPanel('boxingPanel')">Dobozolási paraméterek</p>
                <div class="panel-content">
                  <p title="${response.day_date}" style="cursor: help;"><b>Dobozos raktárkészlet:</b><span style="color: var(--panelcolor); margin-left: 5px;">${response.warehouse_box}</span> <small style="opacity: 0.8;">doboz</small></p>
                  <p title="${response.day_date}" style="cursor: help;"><b>Rendelés alatt:</b><span style="color: var(--panelcolor); margin-left: 5px;">${response.under_sales}</span> <small style="opacity: 0.8;">pár</small></p>
                  <p title="${response.day_date}" style="cursor: help;"><b>Fóliás raktárkészlet:</b><span style="color: var(--panelcolor); margin-left: 5px;">${response.warehouse_foil}</span> <small style="opacity: 0.8;">pár</small></p>
                  <p title="${response.day_date}" style="cursor: help;"><b>Dobozos készlet kitartás:</b><span style="color: var(--panelcolor); margin-left: 5px;">${response.stock_box_endurance}</span> <small style="opacity: 0.8;">nap</small></p>

                  <button onclick="StartBoxing('${item_id}', '${response.under_boxing}');" style="position: absolute; bottom: 0px; right: 0px;" ${boxingbutton}>Dobozolási feladat létrehozása</button>
                </div>
              </div>

            </div>`;

            var score = document.getElementById('filter-score').value;
            if (score == "boxing_score") {
              toggleInfoPanel('boxingPanel');
            } else {
              toggleInfoPanel('productionPanel');
            }

          } else {
            GenerateAlerts("error", response.result);
          }

        }, function() {
          Loading(false);
          GenerateAlerts("error", "Hálózati hiba!");
        });
      }
      function toggleInfoPanel(panelId) {
      	const panel = document.getElementById(panelId);
      	if (panel.classList.contains('panel-collapsed')) {
      		panel.classList.remove('panel-collapsed');
      		panel.classList.add('panel-expanded');
      	} else {
      		panel.classList.remove('panel-expanded');
      		panel.classList.add('panel-collapsed');
      	}
      }

      function StartProduction(item_id, under_production) {
        if (under_production == "1") {
          var html = `
          <p><b>Ez a termék már gyártás alatt van! Biztos szeretné felvenni gyártásba?</b></p>
          <button id="startProductionAlertBtnYes" style="float: right; margin-left: 15px; width: 60px;">Igen</button>
          <button id="startProductionAlertBtnNo" style="float: right; background: var(--panelcolor); color: #f5f5f5; width: 60px; border: unset;">Nem</button>
          `;
          const overlay = CreateAlertBox('Figyelem!', html);
          document.getElementById('startProductionAlertBtnYes').onclick = function () { StartProduction(item_id, "0"); CloseAlertBox(overlay); };
          document.getElementById('startProductionAlertBtnNo').onclick = function () { CloseAlertBox(overlay); };
        } else {
          var classic_selected = '';
          var sporty_selected = '';
          var injmold_selected = '';

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

          var html = `
          <p><b>Válassza ki a gyártás típusát</b></p>
          <select id="StartProductionType">
            <option value="">-- Válasszon --</option>
            <option value="classic" ${classic_selected}>Classic gyártás</option>
            <option value="sporty" ${sporty_selected}>Sporty gyártás</option>
            <option value="injmold" ${injmold_selected}>Fröccsöntött gyártás</option>
          </select>
          <button id="startProductionAlertBtn" style="float: right;">Indítás</button>
          `;

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

          document.getElementById('startProductionAlertBtn').onclick = function () {
            CreateProduction(item_id, overlay);
          };
        }
      }
      function CreateProduction(item_id, overlay) {
        var type = document.getElementById('StartProductionType').value;
        CloseAlertBox(overlay);
        if (type == null || type == "") {
          GenerateAlerts('warning', 'Kérjük, válasszon ki egy típust!');
          return;
        }

        Loading();
        const body = 'func=CreateProduction&item_id=' + encodeURIComponent(item_id).replace(/%20/g, '+') + '&type=' + type;
        get_POST_information("productionstat.php", body, function(text) {
          Loading(false);
          let response = JSON.parse(text);
          if (response.result == "ok") {
            GenerateAlerts("info", response.db_start + " pár cikkszám az ajánlott gyártási mennyiség.");
            GenerateAlerts("success", "Sikeresen felvette gyártásba! Továbbiakat a <a href='./production' style='text-decoration: underline; color: white;'>termékgyártás</a> menuponton érheti el.");
            LoadTable();
          } else {
            GenerateAlerts("error", response.result);
          }
        }, function() {
          Loading(false);
          GenerateAlerts("error", "Hálózati hiba!");
        });
      }

      function StartBoxing(item_id, under_boxing) {
        if (under_boxing == "1") {
          var html = `
          <p><b>Ez a termék már dobozolás alatt van! Biztos szeretné felvenni dobozolási feladatnak?</b></p>
          <button id="startBoxingAlertBtnYes" style="float: right; margin-left: 15px; width: 60px;">Igen</button>
          <button id="startBoxingAlertBtnNo" style="float: right; background: var(--panelcolor); color: #f5f5f5; width: 60px; border: unset;">Nem</button>
          `;
          const overlay = CreateAlertBox('Figyelem!', html);
          document.getElementById('startBoxingAlertBtnYes').onclick = function () { StartBoxing(item_id, "0"); CloseAlertBox(overlay); };
          document.getElementById('startBoxingAlertBtnNo').onclick = function () { CloseAlertBox(overlay); };
        } else {
          Loading();
          const body = 'func=CreateBoxing&item_id=' + encodeURIComponent(item_id).replace(/%20/g, '+');
          get_POST_information("productionstat.php", body, function(text) {
            Loading(false);
            let response = JSON.parse(text);
            if (response.result == "ok") {
              GenerateAlerts("info", response.db_start + " pár cikkszám az ajánlott dobozolási mennyiség.");
              GenerateAlerts("success", "Sikeresen felvette dobozolási feladatnak! Továbbiakat a <a href='./boxing' style='text-decoration: underline; color: white;'>termékdobozolás</a> menuponton érheti el.");
              LoadTable();
            } else {
              GenerateAlerts("error", response.result);
            }
          }, function() {
            Loading(false);
            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>Gyártási és Dobozolási statisztika</h1><p>Valós idejű termelés és dobozolás monitorozás</p></div>

          <div class="sections">
            <div class="section-group"><h2 class="section-group-title">Gyártás</h2>
              <div class="section"><h3 class="section-name">Előkészítés</h3><div class="section-articles" id="prodstat_prep"></div></div>
              <div class="section"><h3 class="section-name">Szerszám előkészítése</h3><div class="section-articles" id="prodstat_tools"></div></div>
              <div class="section"><h3 class="section-name">Terítékfelvágás</h3><div class="section-articles" id="prodstat_cut"></div></div>
              <div class="section"><h3 class="section-name">Préselés</h3><div class="section-articles" id="prodstat_press"></div></div>
              <div class="section"><h3 class="section-name">Feldolgozás</h3><div class="section-articles" id="prodstat_process"></div></div>
              <div class="section"><h3 class="section-name">Utómunka</h3><div class="section-articles" id="prodstat_postprocess"></div></div>
              <div class="section"><h3 class="section-name">Raktározás</h3><div class="section-articles" id="prodstat_warehouse"></div></div>
            </div>

            <div class="section-group"><h2 class="section-group-title">Dobozolás</h2>
              <div class="section"><h3 class="section-name">Előkészítés</h3><div class="section-articles" id="boxstat_prep"></div></div>
              <div class="section"><h3 class="section-name">Raktározás</h3><div class="section-articles" id="boxstat_warehouse"></div></div>
            </div>
          </div>

        </div>`;

        const body = 'func=statistics';
        get_POST_information("productionstat.php", body, function(text) {
          let response = JSON.parse(text);
          if (response.result == "ok") {
          	const sectionMap = {
          		boxing: {
          			1: 'boxstat_prep',
          			2: 'boxstat_warehouse'
          		},
          		production: {
          			1: 'prodstat_prep',
          			2: 'prodstat_tools',
          			3: 'prodstat_cut',
          			4: 'prodstat_press',
          			5: 'prodstat_process',
          			6: 'prodstat_postprocess',
          			7: 'prodstat_warehouse'
          		},
              type: {
          			'classic': 'Classic',
          			'injmold': 'Fröccsöntött',
          			'sporty': 'Sporty',
                'total': 'Összesen',
          			'boxing': 'Dobozolás'
          		}
          	};

          	response.data.forEach(item => {
          		let section_id;
          		/*let type = item.is_boxing ? 'boxing' : 'prod';*/

          		if (item.is_boxing) {
          			section_id = sectionMap.boxing[item.stage];
          		} else {
          			section_id = sectionMap.production[item.stage];
          		}

          		if (section_id) {
          			CreateStatElement(section_id, 'prod', sectionMap.type[item.type], item.item_count, item.db_start);
          		}
          	});

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

      }
      function CreateStatElement(section_id, type, item_id, left, right) {
        const section = document.getElementById(section_id);
        if (type == "prod") {
          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">${right}</span>
          			</div>
          		  <div class="article-card-stat">
          			   <span class="article-card-label">Cikkszám:</span>
          				 <span class="article-card-value left">${left}</span>
          			</div>
          		</div>
          	</div>`;

        } else {
          var percent = (parseInt(left) / parseInt(right) * 100).toFixed();

          section.innerHTML += `
          <div class="boxing-row">
            <div class="boxing-header">
              <div class="article-code">${item_id}</div>
              <span class="boxing-label">${left}/${right}</span>
            </div>
            <div class="boxing-progress">
              <div class="progress-bar">
                <div class="progress-fill" style="width: ${percent}%;"></div>
              </div>
              <span class="progress-text">${percent}%</span>
            </div>
          </div>
          `;

        }
      }

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