<?php

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

if (!(UserHasPerm('production_classic') || UserHasPerm('production_injmold') || UserHasPerm("production_sporty") || UserHasPerm("production_boxing"))) {
  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'>5 db / oszlop</option>
    <option value='50'>10 db / oszlop</option>
    <option value='100'>20 db / oszlop</option>
    <option value='250'>50 db / oszlop</option>
    <option value='500'>100 db / oszlop</option>
    <option value='1000'>200 db / oszlop</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'] ?? 25));
  	$cpage = intval(htmlspecialchars($_POST['cpage'] ?? 1));
  	$stagefilter = intval(htmlspecialchars($_POST['stage'] ?? 1));

  	$item_id = htmlspecialchars( str_replace(' ', '+', $_POST['item_id']) ?? '' );
  	$category = htmlspecialchars( $_POST['category'] ?? '' );

  	if ($maxperpage < 1) $maxperpage = 25;
  	if ($cpage < 1) $cpage = 1;
  	setcookie("maxperpage", $maxperpage, time() + 86400*90, "/");
  	$maxperpage_display = $maxperpage / 5;

  	$item_filter = '';
  	if (!empty($item_id)) {
  		$item_filter = " AND item_id LIKE '%" . mysqli_real_escape_string($conn, $item_id) . "%'";
  	}

  	if ($stagefilter != null) {
  		$item_filter = " AND stage = '$stagefilter'";
  	}

  	$tables = ['classic','injmold','sporty'];
  	if (!empty($category) && in_array($category,$tables)) {
  		$tables = [$category];
  	}

  	$date_field_mapping = [
  		'classic' => [
  			1 => ['date_start', 'ordered'],
  			2 => 'date_prep',
  			3 => 'date_cut',
  			4 => 'date_press',
  			5 => 'date_process',
  			6 => 'date_clean'
  		],
  		'injmold' => [
  			1 => ['date_start', 'ordered'],
  			2 => 'date_prep',
  			3 => null,
  			4 => 'date_process',
  			5 => null,
  			6 => 'date_clean'
  		],
  		'sporty' => [
  			1 => ['date_start', 'ordered'],
  			2 => null,
  			3 => 'date_cut',
  			4 => 'date_press',
  			5 => null,
  			6 => null
  		]
  	];

  	$results_by_stage = [];

  	for ($stage=1; $stage<=7; $stage++) {
  		$stage_results = [];

  		$union_parts = [];
  		foreach ($tables as $t) {
  			$date_fields_select = [];
  			for ($s = 1; $s <= 6; $s++) {
  				$field = $date_field_mapping[$t][$s] ?? null;

  				if ($field === null) {
  					$date_fields_select[] = "NULL AS date_stage_{$s}";
  				} elseif (is_array($field)) {
  					$date_fields_select[] = "{$field[0]} AS date_stage_{$s}_0";
  					$date_fields_select[] = "{$field[1]} AS date_stage_{$s}_1";
  				} else {
  					$date_fields_select[] = "{$field} AS date_stage_{$s}";
  				}
  			}

  			$union_parts[] = "(SELECT pr_id, item_id, stage, db_start, date_start,
  								" . implode(', ', $date_fields_select) . ",
  								'$t' AS category
  								FROM production_{$t}
  								WHERE stage=$stage $item_filter)";
  		}

  		$sql = "SELECT * FROM (" . implode(" UNION ALL ", $union_parts) . ") AS u";
  		$res = mysqli_query($conn,$sql);

  		while ($res && $row = mysqli_fetch_assoc($res)) {
  			$hasCategoryPerm = UserHasPerm('production_' . $row['category']);

  			$current_stage = intval($row['stage']);
  			switch ($current_stage) {
  				case 1:
  					$hasStagePerm = UserHasPerm('production_prep');
  					break;
  				case 2:
  					$hasStagePerm = UserHasPerm('production_tools');
  					break;
  				case 3:
  					$hasStagePerm = UserHasPerm('production_cut');
  					break;
  				case 4:
  					$hasStagePerm = UserHasPerm('production_press');
  					break;
  				case 5:
  					$hasStagePerm = UserHasPerm('production_process');
  					break;
  				case 6:
  					$hasStagePerm = UserHasPerm('production_postprocess');
  					break;
  				case 7:
  					$hasStagePerm = UserHasPerm('warehouse_add');
  					break;
  				default:
  					$hasStagePerm = false;
  			}

  			$rowHasPerm = $hasCategoryPerm && $hasStagePerm;

  			$print_info = '';

  			if ($current_stage === 1) {
  				$date_start = $row["date_stage_1_0"] ?? null;
  				$ordered = $row["date_stage_1_1"] ?? null;

  				if (empty($date_start)) {
  					$print_info = 'Gyártásba kerül';
  				} elseif (!empty($ordered)) {
  					$print_info = 'ordered';
  				} else {
  					$print_info = 'Előkészítés';
  				}
  			} elseif ($current_stage === 7) {
  				$print_info = 'Raktározás';
  			} else {
  				$field = $date_field_mapping[$row['category']][$current_stage] ?? null;

  				if ($field !== null) {
  					$date_value = $row["date_stage_{$current_stage}"] ?? null;
  					$print_info = !empty($date_value) ? 'Elindult' : '';
  				}
  			}

  			$amount_in_wh = 0;
  			$item_id = $row['item_id'];
  			$sql_wh = mysqli_query($conn,"SELECT free_stock FROM statistics_daily WHERE item_id = '$item_id'");
  			$daily_stat = mysqli_fetch_array($sql_wh);
  			if ($daily_stat != null) {
  				$amount_in_wh = intval($daily_stat['free_stock']);
  			}

  			$stage_results[] = [
  				'pr_id' => $row['pr_id'],
  				'item_id' => $item_id,
  				'stage' => $row['stage'],
  				'category' => $row['category'],
  				'db_start' => $row['db_start'],
  				'hasperm' => $rowHasPerm,
  				'print_info' => $print_info,
  				'amount_in_wh' => $amount_in_wh
  			];
  		}

  		usort($stage_results, function($a, $b) {
  			$a_wh = $a['amount_in_wh'] > 0 ? 1 : $a['amount_in_wh'];
  			$b_wh = $b['amount_in_wh'] > 0 ? 1 : $b['amount_in_wh'];

  			if ($a_wh != $b_wh) {
  				return $a_wh <=> $b_wh;
  			}

  			$a_started = ($a['print_info'] === 'Elindult') ? 0 : 1;
  			$b_started = ($b['print_info'] === 'Elindult') ? 0 : 1;

  			return $a_started <=> $b_started;
  		});

  		$results_by_stage[$stage] = $stage_results;
  	}

  	$final_results = [];
  	$pages_per_stage = [];

  	foreach ($results_by_stage as $stage => $stage_data) {
  		$total_in_stage = count($stage_data);
  		$pages_per_stage[$stage] = $total_in_stage > 0 ? ceil($total_in_stage / $maxperpage_display) : 1;

  		$offset = max(0, ($cpage - 1) * $maxperpage_display);
  		$sliced = array_slice($stage_data, $offset, $maxperpage_display);
  		$final_results = array_merge($final_results, $sliced);
  	}

  	$maxpage = max($pages_per_stage);

  	$response = [
  		'result' => 'ok',
  		'data' => $final_results,
  		'cpage' => $cpage,
  		'maxpage' => $maxpage
  	];
  	echo json_encode($response);
  } else if (htmlspecialchars($_POST["func"]) == "openDetails") {
    $productionId = htmlspecialchars($_POST['productionId'] ?? '');
    $category = htmlspecialchars($_POST['category'] ?? '');

    $validCategories = [
      'classic' => 'production_classic',
      'injmold' => 'production_injmold',
      'sporty'  => 'production_sporty'
    ];

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

    $table = $validCategories[$category];

    $productionId = mysqli_real_escape_string($conn, $productionId);

    $sql = "SELECT * FROM `$table` WHERE pr_id = '$productionId'";

    $result = mysqli_query($conn, $sql);
    if (!$result) {
      echo json_encode(['result' => 'Adatbázis hiba']);
      exit;
    }

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

    echo json_encode(['result' => 'ok', 'data' => $data, 'production_editor' => UserHasPerm('production_editor')]);

  } else if (isset($_POST['func']) && $_POST['func'] === 'UpdateProdPar') {
      $productionId = $_POST['productionId'] ?? '';
      $category = $_POST['category'] ?? '';
      $rawData = $_POST['data'] ?? '';
      $allowedCategories = ['classic', 'injmold', 'sporty', 'boxing'];

      if (!in_array($category, $allowedCategories, true)) {
        echo 'Érvénytelen kategória';
        exit;
      }

      $jsonData = json_decode($rawData, true);
      if (!is_array($jsonData)) {
        echo 'Hibás adatstruktúra';
        exit;
      }

      $HasReload = false;

      foreach ($jsonData as $item) {
        if (!isset($item['name'], $item['value'])) {
          continue;
        }
        $paramName = $item['name'];
        $paramValue = $item['value'];

        /* Jogrendszer */
        $categoryPerm = 'production_' . $category;
        $hasCategoryPerm = UserHasPerm($categoryPerm);
        $isParamEditable = false;
        $ParamPermID = '';

        if ($paramName == 'stage') {
          $isParamEditable = true;
        } else {
          $permData = json_decode(file_get_contents($currentUrl."/managers/prdb.json"), true);

          if (isset($permData['ProductionPerms'])) {
            foreach ($permData['ProductionPerms'] as $permEntry) {
              if ($permEntry['PARAM'] === $paramName) {
                $isParamEditable = UserHasPerm($permEntry['PERM']);
                $ParamPermID = $permEntry['PERM'];
                break;
              }
            }
          }
        }

        if (!($hasCategoryPerm && $isParamEditable)) {
          echo 'Nincs jogosultsága az adott részhez!';
          exit;
        }
        /* Jogrendszer vége */

        if ($paramName == 'stage') {
          $HasReload = true;
        }

        /* Paraméter verifikációk */
        if (!preg_match('/^[a-z_]+$/', $paramName)) {
          continue;
        }

        if ($paramName == "item_id") {
          $sql = mysqli_query($conn,"SELECT name_in_db FROM pr_parameters WHERE item_id = '$paramValue'");
          $pr_parameters = mysqli_fetch_array($sql);
          if ($pr_parameters == null) {
            echo 'Nem létező cikkszámot adott meg!';
            exit;
          }
          $HasReload = true;
        }

        if ($paramName == 'db_start' && $category == 'boxing') {
          $sql = mysqli_query($conn,"SELECT item_id FROM production_".$category." WHERE pr_id = '$productionId'");
          $item_id_from_prod = mysqli_fetch_array($sql)[0];

          $sql = mysqli_query($conn,"SELECT warehouse_total - warehouse_box FROM statistics_daily WHERE item_id = '$item_id_from_prod'");
          $maximum_available_pair = mysqli_fetch_array($sql)[0];

          if (intval($maximum_available_pair) < intval($paramValue)) {
            echo 'Nem lehet ennyi pár terméket bedobozolni! Nincs elegendő pár a fóliás raktárban.';
            exit;
          }
        }

        if ($paramName == "db_start" && intval($paramValue) < 1) {
          echo 'Nem lehet 1 párnál kevesebb az induló mennyiség';
          exit;
        }

        if ($paramName == "db_start" && ($category == 'classic' || $category == 'sporty')) {
          $table = intval($paramValue) * 2;

          $sql = mysqli_query($conn,"SELECT item_id FROM production_".$category." WHERE pr_id = '$productionId'");
          $item_id_from_prod = mysqli_fetch_array($sql)[0];

          $sql = mysqli_query($conn,"SELECT pcs FROM pr_cutting_parameters WHERE item_id = '$item_id_from_prod'");
          $pcs = mysqli_fetch_array($sql)[0];

          if (is_numeric($pcs)) {
            $tablepcs = ceil($table / intval($pcs));
            $sql = mysqli_query($conn,"UPDATE production_$category SET db_table = '$tablepcs' WHERE pr_id = '$productionId'");
          }

        }

        if ($paramValue === '$[TIMESTAMP]') {
          $paramValue = time();
          $type = 'i';
        } else {
          $paramValue = htmlspecialchars($paramValue, ENT_QUOTES, 'UTF-8');
          $type = 's';
        }

        $table = $conn->real_escape_string("production_{$category}");
        $column = $conn->real_escape_string($paramName);
        $sql = "UPDATE `{$table}` SET `{$column}` = ? WHERE `pr_id` = ?";
        $stmt = $conn->prepare($sql);

        if (!$stmt) {
          continue;
        }

        if ($paramValue == null || trim($paramValue) == '') {
          $nullVar = NULL;
          $stmt->bind_param($type . 'i', $nullVar, $productionId);
        } else {
          $stmt->bind_param($type . 'i', $paramValue, $productionId);
        }

        $stmt->execute();
        $stmt->close();
      }

      if ($HasReload) {
        echo 'reload - ';
      }
      echo 'ok';

  } else if (htmlspecialchars($_POST["func"]) == "SearchTable") {
	$category = $_POST['category'] ?? '';
	$allowedCategories = ['classic', 'sporty', 'injmold', 'all'];

	if (!in_array($category, $allowedCategories, true)) {
		echo '{"result": "Érvénytelen kategória"}';
		exit;
	}

	$maxperpage = intval(htmlspecialchars($_POST["perpage"]));
	$cpage = intval(htmlspecialchars($_POST["cpage"]));

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

	$addquery = "";
	$isfirst = true;

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

	if ($start_datetime != "") {
		$timestamp = strtotime($start_datetime);
		$addquery = $addquery." WHERE date_revenue > '".$timestamp."'";
		$isfirst = false;
	}

	if ($end_datetime != "") {
		$timestamp = strtotime($end_datetime);
		if ($isfirst) {
			$addquery = $addquery." WHERE date_revenue < '".$timestamp."'";
			$isfirst = false;
		} else {
			$addquery = $addquery." and date_revenue < '".$timestamp."'";
		}
	}

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

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

	$categories = ($category === 'all') ? ['classic', 'sporty', 'injmold'] : [$category];
	$count = 0;

	foreach ($categories as $cat) {
		$table = $conn->real_escape_string("production_{$cat}");
		$sql = mysqli_query($conn, "SELECT COUNT(*) FROM ".$table.$addquery);
		$count += mysqli_fetch_array($sql)[0];
	}

	$addquery = $addquery." ORDER BY date_revenue DESC";

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

	$limit = ($cpage - 1) * $maxperpage;
	$responseStr = '';
	$remaining = $maxperpage;
	$offset = $limit;

	foreach ($categories as $cat) {
		if ($remaining <= 0) break;

		$table = $conn->real_escape_string("production_{$cat}");
		$cat_count_sql = mysqli_query($conn, "SELECT COUNT(*) FROM ".$table.$addquery);
		$cat_count = mysqli_fetch_array($cat_count_sql)[0];

		if ($offset >= $cat_count) {
			$offset -= $cat_count;
			continue;
		}

		$cat_limit = min($remaining, $cat_count - $offset);
		$query = "SELECT pr_id, item_id, (db_revenue * 2) + db_revenue_bulk_r + db_revenue_bulk_l AS total_revenue, date_start, date_revenue FROM $table".$addquery." LIMIT $offset, $cat_limit";

		if ($result = $conn->query($query)) {
			while ($c_prod = $result->fetch_assoc()) {
				if ($responseStr != "") {
					$responseStr .= "|%|";
				}
				$responseStr .= $c_prod['item_id'].'/!/'.date("Y. m. d.", $c_prod['date_start']).'/!/'.date("Y. m. d.", $c_prod['date_revenue']).'/!/'.$c_prod['total_revenue'].'/!/'.$c_prod['pr_id'].'/!/'.$cat;
			}
		}

		$remaining -= $cat_limit;
		$offset = 0;
	}

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

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

    $SendedParam = explode(",", $param);

    $pr_items = [];
    $wh_items = [];
    $st_items = [];

    foreach ($SendedParam as $item) {
      if (strpos($item, 'pr_') === 0) {
        $pr_items[] = $item;
      } elseif (strpos($item, 'wh_') === 0) {
        $wh_items[] = $item;
      } elseif (strpos($item, 'st_') === 0) {
        $st_items[] = $item;
      }
    }

    $result_list = [];
    $parameters = [];

    $response_arr = [];

    if ($LocalData && !empty($pr_items)) {
      foreach ($LocalData["DBList"] as $table) {
        if (UserHasPerm($table["ID"] . "_read")) {
          foreach ($pr_items as $key) {
            if (strpos($key, $table["ID"] . "_") === 0) {
              $param = substr($key, strlen($table["ID"]) + 1);
              $result_list[$table["ID"]][] = ['param' => $param, 'param_code' => $key];
            }
          }
        }
      }

      if (!empty($result_list)) {
        foreach ($result_list as $table_id => $parameters) {

          foreach ($parameters as $param) {
            $param_name = $param['param'];
            $param_code = $param['param_code'];
            $param_print_name = "N/A";
            $is_valid = false;

            foreach ($LocalData["Parameters"] as $ParamData) {
              if ($ParamData["ID"] === $param_code) {
                $is_valid = true;
                $param_print_name = $ParamData["NAME"];
              }
            }

            if ($is_valid) {
              $sql = mysqli_query($conn,"SELECT $param_name FROM $table_id WHERE item_id = '$item_id'");
              $value = mysqli_fetch_array($sql);

              if ($value != null) {
                $response_arr[] = [
                  "param" => $param_name,
                  "name" => $param_print_name,
                  "value" => $value[0]
                ];
              }
            }
          }
        }
      }
    }

    if (!empty($wh_items) && UserHasPerm("warehouse_statistic")) {
      foreach ($wh_items as $item) {
        if ($item == "wh_foil_left") {
          $sql = mysqli_query($conn,"SELECT sum(left_db) as left_db FROM warehouse_foil WHERE item_id = '$item_id'");
          $value = mysqli_fetch_array($sql);

          if ($value != null) {
            $response_arr[] = [
              "param" => 'wh_foil_left',
              "name" => 'Bal fóliás darabszám',
              "value" => $value[0].' db'
            ];
          }

        } else if ($item == "wh_foil_right") {
          $sql = mysqli_query($conn,"SELECT sum(right_db) as right_db FROM warehouse_foil WHERE item_id = '$item_id'");
          $value = mysqli_fetch_array($sql);

          if ($value != null) {
            $response_arr[] = [
              "param" => 'wh_foil_right',
              "name" => 'Jobb fóliás darabszám',
              "value" => $value[0].' db'
            ];
          }

        }
      }
    }

    if (!empty($st_items) && UserHasPerm("production_statistics")) {
      $StatPrintName = [
        "st_daily_warehouse_box" => "Raktárkészlet dobozos",
        "st_daily_warehouse_total" => "Teljes raktárkészlet",
        "st_daily_stock_endurance" => "Készlet kitartás",
        "st_daily_stock_box_endurance" => "Dobozos kitartás",
        "st_daily_priority_score" => "Sürgősségi score",
        "st_daily_boxing_score" => "Dobozolási score",
        "st_daily_under_production" => "Gyártás alatt van",
        "st_daily_under_boxing" => "Dobozolás alatt van",
        "st_daily_under_sales" => "Eladás alatt van",
        "st_annual_total_consumption" => "Éves fogyás",
        "st_annual_average_production" => "Gyártási átlagidő",
        "st_annual_produced_quantity" => "Legyártott mennyiség",
        "st_annual_went_into_production" => "Gyártásba került",
        "st_annual_average_scrap" => "Átlag selejtszám"
      ];

      foreach ($st_items as $item) {
        if (!array_key_exists($item, $StatPrintName)) {
          $response_arr[] = [
            "param" => $item,
            "name" => "HHIBÁS PARAMÉTER",
            "value" => $item
          ];
          continue;
        }

        if (str_starts_with($item, 'st_annual_')) {
          $param = substr($item, strlen('st_annual_'));
          $sql = mysqli_query($conn,"SELECT `$param` FROM statistics_annual WHERE item_id = '$item_id' ORDER BY year DESC LIMIT 1");

          if ($sql && $value = mysqli_fetch_array($sql)) {
            $response_arr[] = [
              "param" => $item,
              "name" => $StatPrintName[$item],
              "value" => $value[0] ?? 'N/A'
            ];
          }

        } else if (str_starts_with($item, 'st_daily_')) {
          $param = substr($item, strlen('st_daily_'));
          $sql = mysqli_query($conn,"SELECT `$param` FROM statistics_daily WHERE item_id = '$item_id'");

          if ($sql && $value = mysqli_fetch_array($sql)) {
            $response_arr[] = [
              "param" => $item,
              "name" => $StatPrintName[$item],
              "value" => $value[0] ?? 'N/A'
            ];
          }
        }

      }
    }

    echo json_encode(["result"=>"ok","response_arr"=>$response_arr], JSON_UNESCAPED_UNICODE|JSON_NUMERIC_CHECK);
  } else if (htmlspecialchars($_POST["func"]) == "DuplicateProduction") {
    $productionId = $_POST['productionId'] ?? '';
    $category = $_POST['category'] ?? '';
    $allowedCategories = ['classic', 'injmold', 'sporty', 'boxing'];
    $section = $_POST['section'] ?? 0;

    if (!UserHasPerm("production_editor")) {
      echo 'Jogosultság megtagadva';
      exit;
    }

    if (!in_array($category, $allowedCategories, true)) {
      echo 'Érvénytelen kategória';
      exit;
    }

    if ($section == 0) {
      echo 'Érvénytelen szekciók';
      exit;
    }

    $table = $conn->real_escape_string("production_{$category}");
    $productionId = $conn->real_escape_string($productionId);

    $sql = mysqli_query($conn,"SELECT * FROM $table WHERE pr_id = '$productionId'");
    $original = mysqli_fetch_array($sql);

    if (!$original) {
      echo 'Nincs ilyen rekord';
      exit;
    }

    $new_db_start = intval($original['db_start']) - intval($section);
    mysqli_query($conn, "UPDATE $table SET db_start = '$new_db_start' WHERE pr_id = '$productionId'");

    $fields = [];
    $values = [];
    foreach ($original as $key => $value) {
      if ($key !== 'pr_id' && is_string($key) && !empty($key) && !is_numeric($key) && $value !== null && $value !== '') {
        $fields[] = $key;
        if ($key === 'db_start') {
          $val = intval($section);
          $values[] = $val;
        } elseif (is_numeric($value) && intval($value) == $value) {
          $val = intval($value);
          $values[] = $val;
        } else {
          $values[] = "'".$conn->real_escape_string($value)."'";
        }
      }
    }
    $fields_str = implode(', ', $fields);
    $values_str = implode(', ', $values);

    mysqli_query($conn, "INSERT INTO $table ($fields_str) VALUES ($values_str)");
    echo "ok";
  }


  exit();
}

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

<!DOCTYPE html>
<html lang="hu" dir="ltr">
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="../css/panel.css">
    <script src="../js/feather-icons.js"></script>
    <title>Kezelőfelület</title>
  </head>
  <style>
    .accordion { border: 1px solid #ccc; border-radius: 4px; overflow: hidden; margin-bottom: 30px; }
    .accordion .AppSection { border-bottom: 1px solid #ccc; }
    .accordion .AppSection:last-child { border-bottom: none; }
    .accordion .AppSection .header {
      background: #f7f7f7;
      padding: 12px;
      cursor: pointer;
      user-select: none;
    }
    .accordion .AppSection .header.active { background: #e2e2e2; }
    .accordion .AppSection .information {
      max-height: 0;
      overflow: hidden;
      transition: max-height .3s ease;
      padding: 0 12px;
    }

    button[title]:not([title=""]):disabled {
      cursor: url(../img/CheckCircle.cur),not-allowed;
    }
    .plusbtn {
      width: calc(92% / 5);
      border-radius: 12px;
      font-weight: bold;
      background: #3bb143 !important;
      color: var(--toppanel);
    }
    .minusbtn {
      width: calc(92% / 5);
      border-radius: 12px;
      font-weight: bold;
      background: #e3242b !important;
      color: var(--toppanel);
    }
    .icon {
      position: relative;
      color: var(--panelcolor);
      margin-left: 15px;
      cursor: pointer;
      float: right;
    }
    .icon svg {
      transition: 0.2s;
      filter: drop-shadow(0px 0px 2px #8c8c8c4d);
      width: 24px;
      height: 24px;
    }
    .icon.info svg {
      width: 16px;
      height: 16px;
    }
    .icon:hover svg {
      filter: drop-shadow(0px 0px 5px #8c8c8ce6);
    }
    .icon:active svg {
      filter: drop-shadow(0px 0px 3px #8c8c8ce6);
      opacity: 0.8;
    }

    .kanban-card.highlight {
      background-color: color-mix(in srgb, #FF4D00 5%, #ffffff 95%);
      border: 1px solid;
      border-left: 4px solid;
      border-color: #FF4D00;
    }

  </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>Termékgyártás</h1>

      <div style="width: 100%; min-height: 85px;">
        <div style="display: inline; float: left;">
          <p>Cikkszám: </p>
          <input type="text" id="filter-item_id" placeholder="Cikkszám..." value="" onkeydown="if (event.keyCode == 13) {SendFilter();}" autocomplete="off" style="width: 147px; height: 17px;">
        </div><div style="display: inline; float: left; padding-left: 15px;">
          <p>Gyártási típus: </p>
          <select id="filter-category" onchange="SendFilter();">
            <option value="">-- Összes --</option>
            <option value="classic" style="color: #895129">Classic gyártás</option>
            <option value="sporty" style="color: #C0392B">Sporty gyártás</option>
            <option value="injmold" style="color: #ED944D">Fröccsöntött gyártás</option>
          </select>
        </div><div style="display: inline; float: left; padding-left: 15px;">
          <p>Gyártás stádiuma: </p>
          <select id="filter-stage" onchange="SendFilter();">
            <option value="">-- Összes --</option>
            <option value="1">Előkészítés</option>
            <option value="2">Szerszám előkészítése</option>
            <option value="3">Terítékfelvágás</option>
            <option value="4">Préselés</option>
            <option value="5">Feldolgozás</option>
            <option value="6">Utómunka</option>
            <option value="7">Raktározás</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">5 db / oszlop</option></select>
        </div><div style="display: inline; float: left; padding-left: 15px;">
          <p style="color: #f5f5f5;">: </p>
          <button onclick="SendFilter();">Szűrés</button>
        </div>
      </div>

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

      <div class="kanban-board">

        <div class="kanban-column" id="production_prep"><div class="column-header">Előkészítés</div></div>
        <div class="kanban-column" id="production_tool"><div class="column-header">Szerszám előkészítése</div></div>
        <div class="kanban-column" id="production_cut"><div class="column-header">Terítékfelvágás</div></div>
        <div class="kanban-column" id="production_press"><div class="column-header">Préselés</div></div>
        <div class="kanban-column" id="production_process"><div class="column-header">Feldolgozás</div></div>
        <div class="kanban-column" id="production_postprocess"><div class="column-header">Utómunka</div></div>
        <div class="kanban-column" id="warehouse_add"><div class="column-header">Raktározás</div></div>

      </div>

      <br clear="all">
      <div>
        <p style="text-align: center; padding-bottom: 30px; 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: <?php echo (UserHasPerm('production_statistics')) ? 'unset' : 'none'?>">

        <br clear="all">
        <div style="border-top: solid 1px rgb(211,220,228); width: 100%; height: 0px; margin-top: 15px;"></div>
        <p style="color: rgb(211,220,228);">Lezárt gyártási folyamatok áttekintése</p>
        <br clear="all">

        <div style="width: 100%; min-height: 85px;">
          <div style="display: inline; float: left;">
            <p>Cikkszám: </p>
            <input type="text" id="search_filter-item_id" placeholder="Cikkszám..." onkeydown="if (event.keyCode == 13) {SearchSendFilter();}" autocomplete="off" style="width: 147px; height: 17px;">
          </div><div style="display: inline; float: left; padding-left: 15px;">
            <p>Gyártási típus: </p>
            <select id="search_filter-category" onchange="SearchSendFilter();">
              <option value="all" >-- Összes --</option>
              <option value="classic" style="color: #895129">Classic gyártás</option>
              <option value="sporty" style="color: #C0392B">Sporty gyártás</option>
              <option value="injmold" style="color: #ED944D">Fröccsöntött gyártás</option>
            </select>
          </div><div style="display: inline; float: left; padding-left: 15px;">
            <p>Bevét időtartam kezdet: </p>
            <input type="datetime-local" id="search_filter-start_datetime" onchange="SearchSendFilter();" >
          </div><div style="display: inline; float: left; padding-left: 15px;">
            <p>Bevét időtartam vége: </p>
            <input type="datetime-local" id="search_filter-end_datetime" onchange="SearchSendFilter();">
          </div><div style="display: inline; float: left; padding-left: 15px;">
            <p>Oldalanként: </p>
            <select id="search_filter-perpage" onchange="SearchSendFilter();"><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="SearchSendFilter();">Szűrés</button>
          </div>
        </div>

        <br clear="all">
        <div style="border-top: solid 1px rgb(211,220,228); width: 100%; 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="search_table">
              <thead>
                <tr style="top: 0px; position: sticky; z-index: 1;">
                  <th>Cikkszám</th>
                  <th>Kezdési dátum</th>
                  <th>Bevételezési dátum</th>
                  <th>Legyártott darabszám <small style="opacity: 0.8;"><small>Jobb + Bal</small></small></th>
                  <th style="width: 100px;">Adatlap</th>
                </tr>
              </thead>
            <tbody>
            </tbody>
          </table>
          </div>
        </div>

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

      </div>

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

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

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

      function LoadFilter() {
        const body = 'func=filter';
        get_POST_information("production.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 category = document.getElementById('filter-category').value;
        var stage = document.getElementById('filter-stage').value;

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

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

        get_POST_information("production.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;

            const categoryColors = {
              'classic': '#895129',
          		'sporty': '#C0392B',
          		'injmold': '#ED944D'
          	};
            const stageHeaders = {
              1: 'Előkészítés',
              2: 'Szerszám előkészítése',
              3: 'Terítékfelvágás',
              4: 'Préselés',
              5: 'Feldolgozás',
              6: 'Utómunka',
              7: 'Raktározás'
            };
            const stageContainers = {
              1: 'production_prep',
              2: 'production_tool',
              3: 'production_cut',
              4: 'production_press',
              5: 'production_process',
              6: 'production_postprocess',
              7: 'warehouse_add'
            };

            for (let i = 1; i <= 7; i++) {
              const container = document.getElementById(stageContainers[i]);
          		if (container) {
          			container.innerHTML = '';
          			const headerEl = document.createElement('div');
          			headerEl.className = 'column-header';
                container.style.display = "flex";
          			headerEl.textContent = stageHeaders[i];
          			container.appendChild(headerEl);
          		}
          	}

            if (stageContainers[parseInt(stage)] != null) {
              for (let i = 1; i <= 7; i++) {
                const container = document.getElementById(stageContainers[i]);
                if (container && i != parseInt(stage)) {
                  container.style.display = "none";
                }
              }
            }

            response.data.forEach(item => {
              const stage = parseInt(item.stage);
              const containerId = stageContainers[stage];
              const container = document.getElementById(containerId);

              if (container) {
                const cardElement = document.createElement('div');
                cardElement.className = 'kanban-card';
                cardElement.style.borderLeftColor = categoryColors[item.category] || '#2980b9';
                if (item.hasperm == false) {
                  cardElement.style.opacity = '0.5';
                  cardElement.style.boxShadow = 'unset';
                }

                var icon = '';
                if (item.amount_in_wh < 1) {
                  icon = `<i class="icon info" title='Nincs szabad raktáron a cikkszámból!' style="color: #FF4D00;"><i data-feather='alert-octagon'></i></i>`;
                }
                if (item.amount_in_wh < 0) {
                  cardElement.className += ' highlight';
                }

                cardElement.innerHTML = `
                  <div class="card-title">Cikkszám: ${item.item_id} ${icon}</div>
                  <div class="card-subtitle">
                    <span class="subtitle-left" style="color: ${categoryColors[item.category] || '#2980b9'}">${item.print_info}</span>
                    <span class="subtitle-right"><span style="color: ${categoryColors[item.category] || '#2980b9'}">${item.db_start}</span> <span style="opacity: 0.8; font-size: 12px;">pár</span></span>
                  </div>
                  <button class="card-button" onclick="openDetails('${item.pr_id}', '${item.category}')">Részletek</button>
                `;

                container.appendChild(cardElement);
              }

              feather.replace();
            });

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

      }
      LoadFilter();

      var CurrentProductionId = '';
      var CurrentCategory = '';
      var CurrentItemID = '';
      function openDetails(productionId, category, IsEditorMode = false) {
        CurrentProductionId = productionId;
        CurrentCategory = category;
        openwin();
        wintitle.innerHTML = "Gyártási folyamat";
        if (IsEditorMode) wintitle.innerHTML += " - Szerkesztő mód";
        winapp.innerHTML = '<div id="errorDIV"></div>';

        const fileNameMap = {
          classic: '../managers/template/classic_prod.html',
          injmold: '../managers/template/injmold_prod.html',
          sporty: '../managers/template/sporty_prod.html'
        };
        const filePath = fileNameMap[category];
        if (!filePath) {
          GenerateAlerts("error", 'Nem létező gyártási kategória.');
          return;
        }
        //Loading();

        const body = 'func=openDetails&productionId=' + productionId + '&category=' + category;

        get_POST_information("production.php", body, function(text) {
          let response = JSON.parse(text);
          if (response.result == "ok") {
            fetch(filePath, { cache: 'no-store' })
              .then(response => {
                if (!response.ok) throw new Error('Nem sikerült betölteni a template-et.');
                return response.text();
              })
              .then(templateHtml => {
                //Loading(false);
              	const tempDiv = document.createElement('div');
                var EditedHTML = templateHtml;

                Object.keys(response.data[0]).forEach(key => {
                  const val = response.data[0][key];
                  if (val != null) {
                    if (/^\d{10}$/.test(val)) {
                      const d = new Date(+val * 1000);
                      EditedHTML = EditedHTML.replaceAll('$[' + key + ']', `${d.getFullYear()}.${('0'+(d.getMonth()+1)).slice(-2)}.${('0'+d.getDate()).slice(-2)}. ${('0'+d.getHours()).slice(-2)}:${('0'+d.getMinutes()).slice(-2)}:${('0'+d.getSeconds()).slice(-2)}`);
                    } else EditedHTML = EditedHTML.replaceAll('$[' + key + ']', val);
                  } else EditedHTML = EditedHTML.replaceAll('$[' + key + ']', '');
                });

                EditedHTML = EditedHTML.replaceAll('$[filter-location]', `<?php echo $WarehouseLocSelect;?>`);

                tempDiv.innerHTML = EditedHTML;
                var IsNoWarehouse = false;
              	Object.keys(response.data[0]).forEach(key => {
              		const els = tempDiv.querySelectorAll('#' + key);
                  const val = response.data[0][key];
              		els.forEach(el => {

              			if (['INPUT','TEXTAREA','SELECT'].includes(el.tagName)) {
              				el.value = val;
              			} else {
              				if (/^\d{10}$/.test(val)) {
              					const d = new Date(+val * 1000);
              					el.textContent = `${d.getFullYear()}.${('0'+(d.getMonth()+1)).slice(-2)}.${('0'+d.getDate()).slice(-2)}. ${('0'+d.getHours()).slice(-2)}:${('0'+d.getMinutes()).slice(-2)}:${('0'+d.getSeconds()).slice(-2)}`;
              				} else el.textContent = val;
              			}

                    if (key == "date_warehouseend" && !(val == null || val.length < 1)) {
                      IsNoWarehouse = true;
                    }
                    if (key == "item_id") {
                      CurrentItemID = val;
                    }
              		});
              	});

              	while (tempDiv.firstChild) winapp.appendChild(tempDiv.firstChild);

                if (IsNoWarehouse) {
                  document.getElementById("WarehouseAdd").style.display = 'none';
                } else {
                  CreateWarehouseIframe();
                }

                if (response.production_editor == true) {
                  document.getElementById("EditorMode_icon").style.display = '';
                  document.getElementById("EditorMode_icon").setAttribute("onclick", 'EditorMode(' + !IsEditorMode + ')');
                } else {
                  document.getElementById("EditorMode_icon").style.display = 'none';
                  document.getElementById("EditorMode_icon").setAttribute("onclick", '');
                }

                if (IsEditorMode) {
                  document.getElementById("EditorMode_icon").style.color = 'green';
                  document.getElementById("DuplicateProduction_icon").style.display = '';
                } else {
                  document.getElementById("DuplicateProduction_icon").style.display = 'none';
                }

              	const allFilled = inputs => inputs.every(i => i.value.trim() !== '');

                function updateVisibility() {
                	const sections = Array.from(document.querySelectorAll('.AppSection'));
                	const first = sections[0];
                	const startHidden = first.querySelector('input#date_start[type="hidden"]');
                	if (!startHidden || !startHidden.value.trim()) {
                		sections.forEach((s, i) => {
                			s.style.display = i === 0 ? '' : 'none';
                		});
                		return;
                	}
                	let allow = true;
                	sections.forEach((section, idx) => {
                		if (idx === 0) {
                			section.style.display = '';
                			return;
                		}
                		if (!allow) {
                			section.style.display = 'none';
                			return;
                		}

                		const endHidden = section.querySelector('input[type="hidden"][id^="date_"][id$="end"]');
                		const orderedHidden = section.querySelector('input[type="hidden"][id="ordered"]');

                		section.style.display = '';

                		if ((endHidden && !endHidden.value.trim()) || (orderedHidden && !orderedHidden.value.trim())) {
                			allow = false;
                		}
                	});

                  if (IsEditorMode) {
                    const visibleSections = sections.filter(s => s.style.display !== 'none');
                    const lastVisible = visibleSections[visibleSections.length - 1];
                    if (lastVisible) lastVisible.style.display = 'none';
                  }

                }

                function openFirstEmptySpan() {
                	const sections = Array.from(document.querySelectorAll('.AppSection'));
                	let first = null;
                	for (const section of sections) {
                		const span = section.querySelector('.header span');
                		if (span && span.textContent.trim() === '') {
                			first = section;
                			break;
                		}
                	}
                	if (first) {
                		const hdr = first.querySelector('.header');
                		const cnt = first.querySelector('.information');
                		document.querySelectorAll('.AppSection').forEach(s => {
                			s.querySelector('.header').classList.remove('active');
                			if (s.querySelector('.information')) {
                				s.querySelector('.information').style.maxHeight = null;
                				s.querySelector('.information').style.padding = null;
                			}
                		});
                		hdr.classList.add('active');
                		if (cnt) {
                			cnt.style.maxHeight = cnt.scrollHeight + 'px';
                			cnt.style.padding = '12px';
                		}
                	}
                }

              	document.querySelectorAll('.AppSection').forEach(section => {
              		const inputs = Array.from(section.querySelectorAll('input:not([type="hidden"]), textarea, select')).filter(el => !el.closest('#WarehouseAdd'));
              		const hiddens = Array.from(section.querySelectorAll('input[type="hidden"]')).filter(el => !el.closest('#WarehouseAdd'));
              		const startHidds = hiddens.filter(h => h.id.includes('date_') && !h.id.endsWith('end'));
              		const stopHidds = hiddens.filter(h => h.id.includes('date_') && h.id.endsWith('end'));
              		const specialIDs = ['date_start','ordered','date_warehouseend','date_revenue'];

              		function setLocked(lock) {
              			inputs.forEach(i => {
                      if (!IsEditorMode) {
                				i.disabled = lock;
                				i.readOnly = lock;
                      }
              			});
              		}

              		function update() {
              			const filled = allFilled(inputs);
              			const specialHidden = specialIDs
              				.map(id => section.querySelector(`input#${id}[type="hidden"]`))
              				.find(h => h && !h.closest('#WarehouseAdd'));
              			if (specialHidden) {
              				const btn = section.querySelector(`#${specialHidden.id}_btn`);
              				if (specialHidden.value.trim() !== '') {
              					setLocked(true);
              					if (btn) btn.disabled = true;
              				} else {
              					setLocked(false);
              					if (btn) btn.disabled = !filled;
              				}
              				updateVisibility();
              				return;
              			}

              			const started = startHidds.some(h => h.value.trim() !== '');

              			startHidds.forEach(h => {
              				const btn = section.querySelector(`#${h.id}_btn`);
              				if (btn) btn.disabled = started;
              			});
              			setLocked(!started);

                    stopHidds.forEach(h => {
                      const btn = section.querySelector(`#${h.id}_btn`);

                      if (h.value.trim() != '') {
                        if (btn) btn.disabled = true;
                        setLocked(true);
                      } else if (!inputs.length) {
                        if (btn) btn.disabled = !started;
                      } else {
                        if (btn) btn.disabled = !started || !filled;
                      }
                    });

                    updateVisibility();
              		}

              		inputs.forEach(i => {
              			i.readOnly = false;
              			i.oninput = update;
              			i.onkeydown = update;
              		});

              		const hdr = section.querySelector('.header');
              		const cnt = section.querySelector('.information');
              		hdr.addEventListener('click', () => {
              			document.querySelectorAll('.AppSection').forEach(s => {
              				s.querySelector('.header').classList.remove('active');
              				s.querySelector('.information').style.maxHeight = null;
              				s.querySelector('.information').style.padding = null;
              			});
              			hdr.classList.add('active');
              			cnt.style.maxHeight = cnt.scrollHeight + 'px';
              			cnt.style.padding = '12px';
              		});

              		update();
              	});

              	updateVisibility();
              	openFirstEmptySpan();
                CheckCanEndWarehouse();
                feather.replace();
                AlertStart();
              })
              .catch(err => {
                //Loading(false);
                GenerateAlerts("error", 'Hiba a betöltéskor: ' + err.message);
              });

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

      }

      var BlockNextAlert = false;
      function AlertStart() {
        if (BlockNextAlert) {
          BlockNextAlert = false;
          return;
        }
        var btnid = '';
        var headerText = '';
        var CreateAlert = false;

        const sections = Array.from(document.querySelectorAll('.AppSection'));
        const visibleSections = sections.filter(s => s.style.display !== 'none');
        const lastVisibleSection = visibleSections[visibleSections.length - 1];

        if (lastVisibleSection) {
          const startHidds = Array.from(lastVisibleSection.querySelectorAll('button'))
            .filter(h => h.id.includes('date_') && !h.id.endsWith('end_btn') && h.id.endsWith('_btn') && !h.disabled);

          if (startHidds.length > 0) {
            const enabledBtn = startHidds[0];
            btnid = enabledBtn.id;
            const headerSpan = lastVisibleSection.querySelector('.header span');
            headerText = headerSpan ? headerSpan.previousSibling?.textContent.trim() || '' : '';
            CreateAlert = true;
          }

        }

        if (CreateAlert) {
          var html = `
          <p><b>El szeretné indítani a(z) '${headerText}' gyártási lépést?</b><br><br>
          Könnyedén megteheti az alábbi '<b>Start</b>' gombra kattintva, vagy az ablak bezárását követően az ott megjelenő 'Start' gombbal.</p>
          <br clear="all"><br>
          <button id="AlertBtnNo" style="float: right; margin-left: 15px; width: 80px; background: #bdc3c7; color: #333;">Nem</button>
          <button id="AlertBtnYes" style="float: right; width: 80px; background: var(--panelcolor); color: #f5f5f5; border: unset;">Start</button>
          `;
          const overlay = CreateAlertBox(headerText + ' - Start', html);
          document.getElementById('AlertBtnYes').onclick = function () { CloseAlertBox(overlay); document.getElementById(btnid).click(); };
          document.getElementById('AlertBtnNo').onclick = function () { CloseAlertBox(overlay); };
        }

      }

      function EditorMode(IsEditorMode) {
        openDetails(CurrentProductionId, CurrentCategory, IsEditorMode)
      }
      function DuplicateProduction(section = 0) {
        if (section != 0) {
          Loading(true);
          const body = 'func=DuplicateProduction&productionId=' + CurrentProductionId + '&category=' + CurrentCategory + '&section=' + section;
          get_POST_information("production.php", body, function(text) {
            Loading(false);
            if (text == "ok") {
              LoadTable();
              openDetails(CurrentProductionId, CurrentCategory);
            } else {
              GenerateAlerts("error", text);
            }
          }, function() {
            GenerateAlerts("error", "Hálózati hiba!");
          });
        } else {
          var max = document.getElementById("db_start").value;
          var html = `
              <p><strong>Válassza ki, hogy mekkora részletekre szeretné a gyártást szétszedni:</strong></p>
              <div>
                <p style="color: var(--panelcolor);"><span style="float: left;"><span id="DuplicateProduction_first" style="float: left;"></span><span style="opacity: 0.8; font-size: 12px; color: #333; margin-left: 5px;">pár</span></span><span style="float: right;"><span id="DuplicateProduction_second"></span><span style="opacity: 0.8; font-size: 12px; color: #333; margin-left: 5px;">pár</span></span></p><br>
                <input style="width: calc(100% - 20px);" type="range" id="DuplicateProduction_slider" min="1" max="${max - 1}" value="${Math.ceil(max / 2)}" step="1" oninput="RefreshProdDuplicationSlider(${max}, this.value)">
              </div>
              <br clear="all">
              <button id="AlertBtnNo" style="float: right; margin-left: 15px; width: 80px;">Mégsem</button>
              <button id="AlertBtnYes" style="float: right; width: 95px; background: var(--panelcolor); color: #f5f5f5; border: unset;">Szétszedés</button>
          `;

          const overlay = CreateAlertBox('Duplikálás', html);
          document.getElementById('AlertBtnYes').onclick = function () {
            DuplicateProduction(document.getElementById("DuplicateProduction_slider").value);
            CloseAlertBox(overlay);
          };
          document.getElementById('AlertBtnNo').onclick = function () {
            CloseAlertBox(overlay);
          };

          RefreshProdDuplicationSlider(max, Math.ceil(max / 2));
        }
      }
      function RefreshProdDuplicationSlider(max, current) {
        document.getElementById("DuplicateProduction_second").innerHTML = parseInt(max) - parseInt(current);
        document.getElementById("DuplicateProduction_first").innerHTML = current;
      }

      async function SendUpdateProductionParameter(productionId, category, json) {
      	try {
      		const formData = new FormData();
      		formData.append('func', 'UpdateProdPar');
      		formData.append('productionId', productionId);
      		formData.append('category', category);
      		formData.append('data', JSON.stringify(json));

      		const response = await fetch('production.php', {
      			method: 'POST',
      			body: formData
      		});

      		const result = await response.text();
          return result;
      	} catch (error) {
      		console.error('Hiba:', error);
      		return null;
      	}
      }
      function UpdateProductionParameter(dataArray, silent = false) {
        if (!silent) { Loading(); }
        SendUpdateProductionParameter(CurrentProductionId, CurrentCategory, dataArray).then(result => {
          if (result == "ok" || result == "reload - ok") {
            if (!silent) {
              BlockNextAlert = true;
              openDetails(CurrentProductionId, CurrentCategory);
              Loading(false);
              if (result == "reload - ok" && !silent) {
                SendFilter();
              }
            }
          } else {
            GenerateAlerts("error", result);
            if (!silent) { Loading(false); }
          }
        });
      }

      /* Azonos Gyártás funkciók */
      function ProdStart() {
        const dataArray = [
        	{name: "item_id", value: document.querySelector('input[id="item_id"]').value },
        	{name: "db_start", value: document.querySelector('input[id="db_start"]').value },
        	{name: "date_start", value: "$[TIMESTAMP]"}
        ];
        UpdateProductionParameter(dataArray);
      }
      function ToolPrepStart() {
        const dataArray = [{name: "date_prep", value: "$[TIMESTAMP]"}];
        UpdateProductionParameter(dataArray);
      }

      function CutStart() {
        const dataArray = [{name: "date_cut", value: "$[TIMESTAMP]"}];
        UpdateProductionParameter(dataArray);
      }
      function CutEnd() {
        const dataArray = [
          {name: "db_cut_r", value: document.querySelector('input[id="db_cut_r"]').value },
          {name: "db_cut_l", value: document.querySelector('input[id="db_cut_l"]').value },
          {name: "date_cutend", value: "$[TIMESTAMP]"},
          {name: "stage", value: '4' }
        ];
        UpdateProductionParameter(dataArray);
      }

      function PressStart() {
        const dataArray = [{name: "date_press", value: "$[TIMESTAMP]"}];
        UpdateProductionParameter(dataArray);
      }

      function ProcessStart() {
        const dataArray = [{name: "date_process", value: "$[TIMESTAMP]"}];
        UpdateProductionParameter(dataArray);
      }

      function PostprocessStart() {
        const dataArray = [{name: "date_clean", value: "$[TIMESTAMP]"}];
        UpdateProductionParameter(dataArray);
      }
      function PostprocessEnd() {
        const dataArray = [
          {name: "db_clean_r", value: document.querySelector('input[id="db_clean_r"]').value },
          {name: "db_clean_l", value: document.querySelector('input[id="db_clean_l"]').value },
          {name: "date_cleanend", value: "$[TIMESTAMP]"},
          {name: "stage", value: '7' }
        ];
        UpdateProductionParameter(dataArray);
      }

      function WarehouseEnd(validated = false) {
        if (validated) {
          const dataArray = [
            {name: "date_warehouseend", value: "$[TIMESTAMP]"},
            {name: "date_revenue", value: "$[TIMESTAMP]"},
            {name: "stage", value: '0' }
          ];
          UpdateProductionParameter(dataArray);

          RefreshDailyStat();
        } else {
          var html = `
              <p><strong>Biztos benne, hogy le akarja menteni a raktározást és ezzel a gyártást lezárni?</strong></p>
              <br clear="all"><br>
              <button id="AlertBtnNo" style="float: right; margin-left: 15px; width: 80px;">Mégsem</button>
              <button id="AlertBtnYes" style="float: right; width: 95px; background: var(--panelcolor); color: #f5f5f5; border: unset;">Bevételezés</button>
          `;


          const overlay = CreateAlertBox('Lezárás', html);
          document.getElementById('AlertBtnYes').onclick = function () {
            WarehouseEnd(true);
            CloseAlertBox(overlay);
          };
          document.getElementById('AlertBtnNo').onclick = function () {
            CloseAlertBox(overlay);
          };
        }

      }
      function RevenueProd() {
        const dataArray = [
          {name: "date_revenue", value: "$[TIMESTAMP]"},
          {name: "stage", value: '0' }
        ];
        UpdateProductionParameter(dataArray);
      }

      /* Classic gyártás funkciók */
      function ClassicPrepEnd() {
        const dataArray = [
          {name: "remain_r", value: document.querySelector('input[id="remain_r"]').value },
          {name: "remain_l", value: document.querySelector('input[id="remain_l"]').value },
          {name: "tablesize_x", value: document.querySelector('input[id="tablesize_x"]').value },
          {name: "tablesize_y", value: document.querySelector('input[id="tablesize_y"]').value },
          {name: "db_table", value: document.querySelector('input[id="db_table"]').value },
          {name: "ordered", value: "$[TIMESTAMP]"},
          {name: "stage", value: '2' }
        ];
        UpdateProductionParameter(dataArray);
      }
      function ClassicToolPrepEnd() {
        const dataArray = [
          {
          name: "date_prepend", value: "$[TIMESTAMP]"},
          {name: "stage", value: '3' },
        ];
        UpdateProductionParameter(dataArray);
      }
      function ClassicPressEnd() {
        const dataArray = [
          {name: "db_press_r", value: document.querySelector('input[id="db_press_r"]').value },
          {name: "db_press_l", value: document.querySelector('input[id="db_press_l"]').value },
          {name: "press_machine", value: document.querySelector('select[id="press_machine"]').value },
          {name: "date_pressend", value: "$[TIMESTAMP]"},
          {name: "stage", value: '5' }
        ];
        UpdateProductionParameter(dataArray);
      }
      function ClassicProcessEnd() {
        const dataArray = [
          {name: "db_process_r", value: document.querySelector('input[id="db_process_r"]').value },
          {name: "db_process_l", value: document.querySelector('input[id="db_process_l"]').value },
          {name: "process_mode", value: document.querySelector('select[id="process_mode"]').value },
          {name: "date_processend", value: "$[TIMESTAMP]"},
          {name: "stage", value: '6' }
        ];
        UpdateProductionParameter(dataArray);
      }

      /* Sporty gyártás funkciók */
      function SportyPrepEnd() {
        const dataArray = [
          {name: "remain_r", value: document.querySelector('input[id="remain_r"]').value },
          {name: "remain_l", value: document.querySelector('input[id="remain_l"]').value },
          {name: "tablesize_x", value: document.querySelector('input[id="tablesize_x"]').value },
          {name: "tablesize_y", value: document.querySelector('input[id="tablesize_y"]').value },
          {name: "db_table", value: document.querySelector('input[id="db_table"]').value },
          {name: "ordered", value: "$[TIMESTAMP]"},
          {name: "stage", value: '3' }
        ];
        UpdateProductionParameter(dataArray);
      }
      function SportyPressEnd() {
        const dataArray = [
          {name: "db_press_r", value: document.querySelector('input[id="db_press_r"]').value },
          {name: "db_press_l", value: document.querySelector('input[id="db_press_l"]').value },
          {name: "date_pressend", value: "$[TIMESTAMP]"},
          {name: "stage", value: '7' }
        ];
        UpdateProductionParameter(dataArray);
      }

      /* Fröccsöntött gyártás funkciók */
      function InjmoldPrepEnd() {
        const dataArray = [
          {name: "db_granules", value: document.querySelector('input[id="db_granules"]').value },
          {name: "ordered", value: "$[TIMESTAMP]"},
          {name: "stage", value: '2' }
        ];
        UpdateProductionParameter(dataArray);
      }
      function InjmoldToolPrepEnd() {
        const dataArray = [
          {
          name: "date_prepend", value: "$[TIMESTAMP]"},
          {name: "stage", value: '4' }
        ];
        UpdateProductionParameter(dataArray);
      }
      function InjmoldProcessEnd() {
        const dataArray = [
          {name: "db_process_r", value: document.querySelector('input[id="db_process_r"]').value },
          {name: "db_process_l", value: document.querySelector('input[id="db_process_l"]').value },
          {name: "db_granules_used", value: document.querySelector('input[id="db_granules_used"]').value },
          {name: "kwh_start", value: document.querySelector('input[id="kwh_start"]').value },
          {name: "kwh_stop", value: document.querySelector('input[id="kwh_stop"]').value },
          {name: "date_processend", value: "$[TIMESTAMP]"},
          {name: "stage", value: '6' }
        ];
        UpdateProductionParameter(dataArray);
      }

      /* Katalógus lekérő */
      function OpenCatalogue(title, parameters) {
        const body = 'func=OpenCatalogue&param=' + encodeURIComponent(parameters).replace(/%20/g, '+') + '&item_id=' + encodeURIComponent(CurrentItemID).replace(/%20/g, '+');
        get_POST_information("production.php", body, function(text) {
          let response = JSON.parse(text);
          if (response.result == "ok") {

            var html = ``;
            response.response_arr.forEach(function(item) {
              html += `<p><b>${item.name}</b>:<br> <span style="color: var(--panelcolor);">${item.value}</span></p>`;
            });

            CreateAlertBox(title, html);

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

      /* Raktározás */
      function CreateWarehouseIframe() {

        var reason = encodeURIComponent("Production#" + CurrentCategory + "#" + CurrentProductionId).replace(/%20/g, '+');

        const container = document.getElementById('WarehouseAdd');
        container.innerHTML = "";

        const iframe = document.createElement('iframe');
        iframe.src = './wh_add?iframe=1&item_id=' + CurrentItemID + '&reason=' + reason + '&functions=foil';
        iframe.style.width = "100%";
        iframe.style.height = "500px";
        iframe.style.border = "0px";
        iframe.id = "WarehouseIframe";
        container.appendChild(iframe);

        iframe.onload = function() {
          iframe.style.height = iframe.contentWindow.document.body.scrollHeight + 'px';
        };

      }
      window.addEventListener('message', function(event) {
        if (event.origin === 'https://szaturnusz.szatuna.hu') {
          if (event.data.iframeHeight) {
            setTimeout(() => {
              const iframe = document.getElementById("WarehouseIframe");
              iframe.style.height = event.data.iframeHeight + 'px';
              console.log(event.data.iframeHeight);
              //document.getElementById('WarehouseSection').style.maxHeight = document.getElementById('WarehouseSection').scrollHeight + 'px';
            }, 50);
          }
          if (event.data.iframeLeft) {
            document.getElementById('db_revenue_bulk_l').innerHTML = (parseInt(document.getElementById('db_revenue_bulk_l').innerHTML) || 0) + parseInt(event.data.iframeLeft);
          }
          if (event.data.iframeRight) {
            document.getElementById('db_revenue_bulk_r').innerHTML = (parseInt(document.getElementById('db_revenue_bulk_r').innerHTML) || 0) + parseInt(event.data.iframeRight);
          }
          if (event.data.iframeBox) {
            document.getElementById('db_revenue').innerHTML = (parseInt(document.getElementById('db_revenue').innerHTML) || 0) + parseInt(event.data.iframeBox);
          }
          CheckCanEndWarehouse();
        }
      });
      function CheckCanEndWarehouse() {
        var db_revenue_bulk_l = parseInt(document.getElementById('db_revenue_bulk_l').innerHTML) || 0;
        var db_revenue_bulk_r = parseInt(document.getElementById('db_revenue_bulk_r').innerHTML) || 0;

        const date_warehouseend_btn = document.getElementById('date_warehouseend_btn');
        if (date_warehouseend_btn == null) {
          return;
        }

        if (db_revenue_bulk_l > 0 && db_revenue_bulk_r > 0) {
          date_warehouseend_btn.disabled = false;
        } else {
          date_warehouseend_btn.disabled = true;
        }
      }

      /* Folyamatos mentés */
      function SaveSingleParam(name, id) {
        const dataArray = [ {name: name, value: document.querySelector('input#' + id + ', select#' + id).value } ];
        UpdateProductionParameter(dataArray, true);
      }

      function RefreshDailyStat() {
        get_POST_information("../managers/statistics.php?type=daily&item_id=" + encodeURIComponent(CurrentItemID).replace(/%20/g, '+'), '', function(text) {

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

      /* Lezártak keresője */
      function SearchLoadFilter() {
        const body = 'func=filter';
        get_POST_information("wh_remove.php", body, function(text) {
          let response = JSON.parse(text);
          if (response.result == "ok") {
            document.getElementById('search_filter-perpage').innerHTML = response.perpage;
            SearchLoadTable();
          } else {
            GenerateAlerts("error", response.result);
          }
        }, function() {
          GenerateAlerts("error", "Hálózati hiba!");
        });
      }
      function SearchSendFilter() {
        document.getElementById('search_cpage').innerHTML = '1';
        SearchLoadTable();
      }
      function SearchLeft() {
        var cpage = document.getElementById("search_cpage").innerHTML;
        if ((parseInt(cpage) - 1) >= 1) {
          document.getElementById("search_cpage").innerHTML = parseInt(cpage) - 1;
          SearchLoadTable();
        }
      }
      function SearchRight() {
        var cpage = document.getElementById("search_cpage").innerHTML;
        var maxpage = document.getElementById("search_maxpage").innerHTML;
        if ((parseInt(cpage) + 1) <= parseInt(maxpage)) {
          document.getElementById("search_cpage").innerHTML = parseInt(cpage) + 1;
          SearchLoadTable();
        }
      }

      function SearchLoadTable() {
        Loading();
        var item_id = document.getElementById("search_filter-item_id").value;
        var category = document.getElementById("search_filter-category").value;
        var start_datetime = document.getElementById("search_filter-start_datetime").value;
        var end_datetime = document.getElementById("search_filter-end_datetime").value;

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

        const body = 'func=SearchTable&perpage=' + perpage + '&cpage=' + cpage + '&item_id=' + encodeURIComponent(item_id).replace(/%20/g, '+') + '&start_datetime=' + encodeURIComponent(start_datetime).replace(/%20/g, '+') +'&end_datetime=' + encodeURIComponent(end_datetime).replace(/%20/g, '+') + '&category=' + category;
        get_POST_information("production.php", body, function(text) {
          Loading(false);
          let response = JSON.parse(text);
          if (response.result == "ok") {
            var table = document.getElementById('search_table').getElementsByTagName('tbody')[0];
            table.innerHTML = "";
            document.getElementById("search_cpage").innerHTML = response.cpage;
            document.getElementById("search_maxpage").innerHTML = response.maxpage;

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

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

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

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