<?php

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

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

if (isset($_POST["func"])) {
  if (htmlspecialchars($_POST["func"]) == "classicProduction") {
    $from_date = htmlspecialchars($_POST["from_date"]);
    $to_date = htmlspecialchars($_POST["to_date"]);
    $get_item_id = htmlspecialchars(str_replace(' ', '+', $_POST['item_id']));

    $query_item_id = '';
    if ($get_item_id != '') { $query_item_id = 'AND item_id LIKE "%'.$get_item_id.'%"'; }

    $sql = mysqli_query($conn,"SELECT
          SUM(db_start) AS db_start,
          SUM(db_cut_r) AS db_cut_r,
          SUM(db_cut_l) AS db_cut_l,
          SUM(db_press_r) AS db_press_r,
          SUM(db_press_l) AS db_press_l,
          SUM(db_process_r) AS db_process_r,
          SUM(db_process_l) AS db_process_l,
          SUM(db_clean_r) AS db_clean_r,
          SUM(db_clean_l) AS db_clean_l,
          SUM(db_revenue_bulk_r) AS db_revenue_bulk_r,
          SUM(db_revenue_bulk_l) AS db_revenue_bulk_l,
          SUM(db_table) AS db_table,
          (SUM(db_cut_r) + SUM(db_cut_l)) - (SUM(db_revenue_bulk_r) + SUM(db_revenue_bulk_l)) AS db_scrap,
          ((SUM(db_cut_r) + SUM(db_cut_l)) - (SUM(db_revenue_bulk_r) + SUM(db_revenue_bulk_l))) / (SUM(db_cut_r) + SUM(db_cut_l)) * 100 AS percent_scrap,
          AVG(date_prepend - date_prep) AS prep_time,
          AVG(date_cutend - date_cut) AS cut_time,
          AVG(date_pressend - date_press) AS press_time,
          AVG(date_processend - date_process) AS process_time,
          AVG(date_cleanend - date_clean) AS clean_time,
          AVG(date_revenue - date_start) AS product_time,
          SUM(date_prepend - date_prep) AS prep_time_sum,
          SUM(date_cutend - date_cut) AS cut_time_sum,
          SUM(date_pressend - date_press) AS press_time_sum,
          SUM(date_processend - date_process) AS process_time_sum,
          SUM(date_cleanend - date_clean) AS clean_time_sum,
          SUM(date_revenue - date_start) AS product_time_sum,
          SUM((tablesize_x * tablesize_y) / 1000000 * db_table) AS tablesize
      FROM
          production_classic
      WHERE
          stage = 0 $query_item_id
          AND FROM_UNIXTIME(date_revenue) >= '$from_date 00:00:00' AND FROM_UNIXTIME(date_revenue) <= '$to_date 23:59:59'");

    $parameters = mysqli_fetch_array($sql);

    echo json_encode(["result" => "ok", "data" => $parameters]);
  } else if (htmlspecialchars($_POST["func"]) == "sportyProduction") {
    $from_date = htmlspecialchars($_POST["from_date"]);
    $to_date = htmlspecialchars($_POST["to_date"]);
    $get_item_id = htmlspecialchars(str_replace(' ', '+', $_POST['item_id']));

    $query_item_id = '';
    if ($get_item_id != '') { $query_item_id = 'AND item_id LIKE "%'.$get_item_id.'%"'; }

    $sql = mysqli_query($conn,"SELECT
          SUM(db_start) AS db_start,
          SUM(db_cut_r) AS db_cut_r,
          SUM(db_cut_l) AS db_cut_l,
          SUM(db_press_r) AS db_press_r,
          SUM(db_press_l) AS db_press_l,
          SUM(db_revenue_bulk_r) AS db_revenue_bulk_r,
          SUM(db_revenue_bulk_l) AS db_revenue_bulk_l,
          SUM(db_table) AS db_table,
          (SUM(db_cut_r) + SUM(db_cut_l)) - (SUM(db_revenue_bulk_r) + SUM(db_revenue_bulk_l)) AS db_scrap,
          ((SUM(db_cut_r) + SUM(db_cut_l)) - (SUM(db_revenue_bulk_r) + SUM(db_revenue_bulk_l))) / (SUM(db_cut_r) + SUM(db_cut_l)) * 100 AS percent_scrap,
          AVG(date_cutend - date_cut) AS cut_time,
          AVG(date_pressend - date_press) AS press_time,
          AVG(date_revenue - date_start) AS product_time,
          SUM(date_cutend - date_cut) AS cut_time_sum,
          SUM(date_pressend - date_press) AS press_time_sum,
          SUM(date_revenue - date_start) AS product_time_sum,
          SUM((tablesize_x * tablesize_y) / 1000000 * db_table) AS tablesize
      FROM
          production_sporty
      WHERE
          stage = 0 $query_item_id
          AND FROM_UNIXTIME(date_revenue) >= '$from_date 00:00:00' AND FROM_UNIXTIME(date_revenue) <= '$to_date 23:59:59'");

    $parameters = mysqli_fetch_array($sql);

    echo json_encode(["result" => "ok", "data" => $parameters]);
  } else if (htmlspecialchars($_POST["func"]) == "injmoldProduction") {
    $from_date = htmlspecialchars($_POST["from_date"]);
    $to_date = htmlspecialchars($_POST["to_date"]);
    $get_item_id = htmlspecialchars(str_replace(' ', '+', $_POST['item_id']));

    $query_item_id = '';
    if ($get_item_id != '') { $query_item_id = 'AND item_id LIKE "%'.$get_item_id.'%"'; }

    $sql = mysqli_query($conn,"SELECT
          SUM(db_start) AS db_start,
          SUM(db_process_r) AS db_process_r,
          SUM(db_process_l) AS db_process_l,
          SUM(db_clean_r) AS db_clean_r,
          SUM(db_clean_l) AS db_clean_l,
          SUM(db_revenue_bulk_r) AS db_revenue_bulk_r,
          SUM(db_revenue_bulk_l) AS db_revenue_bulk_l,
          SUM(db_granules_used) AS db_granules_used,
          SUM(kwh_stop - kwh_start) AS kwh,
          (SUM(db_process_r) + SUM(db_process_l)) - (SUM(db_revenue_bulk_r) + SUM(db_revenue_bulk_l)) AS db_scrap,
          ((SUM(db_process_r) + SUM(db_process_l)) - (SUM(db_revenue_bulk_r) + SUM(db_revenue_bulk_l))) / (SUM(db_start) * 2) * 100 AS percent_scrap,
          AVG(date_prepend - date_prep) AS prep_time,
          AVG(date_processend - date_process) AS process_time,
          AVG(date_cleanend - date_clean) AS clean_time,
          AVG(date_revenue - date_start) AS product_time,
          SUM(date_prepend - date_prep) AS prep_time_sum,
          SUM(date_processend - date_process) AS process_time_sum,
          SUM(date_cleanend - date_clean) AS clean_time_sum,
          SUM(date_revenue - date_start) AS product_time_sum
      FROM
          production_injmold
      WHERE
          stage = 0 $query_item_id
          AND FROM_UNIXTIME(date_revenue) >= '$from_date 00:00:00' AND FROM_UNIXTIME(date_revenue) <= '$to_date 23:59:59'");

    $parameters = mysqli_fetch_array($sql);

    echo json_encode(["result" => "ok", "data" => $parameters]);
  } else if (htmlspecialchars($_POST["func"]) == "boxingProduction") {
    $from_date = htmlspecialchars($_POST["from_date"]);
    $to_date = htmlspecialchars($_POST["to_date"]);
    $get_item_id = htmlspecialchars(str_replace(' ', '+', $_POST['item_id']));

    $query_item_id = '';
    if ($get_item_id != '') { $query_item_id = 'AND item_id LIKE "%'.$get_item_id.'%"'; }

    $sql = mysqli_query($conn,"SELECT
            SUM(CASE
                WHEN SUBSTRING_INDEX(item_id, '+', 1) REGEXP '^[0-9]+$' THEN db_revenue
                ELSE 0
            END) AS db_revenue_classic,
            SUM(CASE
                WHEN SUBSTRING_INDEX(item_id, '+', 1) REGEXP '^F[0-9]{4}$' THEN db_revenue
                ELSE 0
            END) AS db_revenue_sporty,
            SUM(CASE
                WHEN SUBSTRING_INDEX(item_id, '+', 1) REGEXP '^FR[0-9]{4}$' THEN db_revenue
                ELSE 0
            END) AS db_revenue_injmold,
            AVG(CASE
                WHEN SUBSTRING_INDEX(item_id, '+', 1) REGEXP '^[0-9]+$' THEN (date_warehouseend - date_start)
                ELSE 0
            END) AS product_time_classic,
            AVG(CASE
                WHEN SUBSTRING_INDEX(item_id, '+', 1) REGEXP '^F[0-9]{4}$' THEN (date_warehouseend - date_start)
                ELSE 0
            END) AS product_time_sporty,
            AVG(CASE
                WHEN SUBSTRING_INDEX(item_id, '+', 1) REGEXP '^FR[0-9]{4}$' THEN (date_warehouseend - date_start)
                ELSE 0
            END) AS product_time_injmold,
            SUM(CASE
                WHEN SUBSTRING_INDEX(item_id, '+', 1) REGEXP '^[0-9]+$' THEN (date_warehouseend - date_start)
                ELSE 0
            END) AS product_time_classic_sum,
            SUM(CASE
                WHEN SUBSTRING_INDEX(item_id, '+', 1) REGEXP '^F[0-9]{4}$' THEN (date_warehouseend - date_start)
                ELSE 0
            END) AS product_time_sporty_sum,
            SUM(CASE
                WHEN SUBSTRING_INDEX(item_id, '+', 1) REGEXP '^FR[0-9]{4}$' THEN (date_warehouseend - date_start)
                ELSE 0
            END) AS product_time_injmold_sum
        FROM
            production_boxing
        WHERE
            stage = 0 $query_item_id
            AND FROM_UNIXTIME(date_warehouseend) >= '$from_date 00:00:00' AND FROM_UNIXTIME(date_warehouseend) <= '$to_date 23:59:59'");

    $parameters = mysqli_fetch_array($sql);

    echo json_encode(["result" => "ok", "data" => $parameters]);
  } if (htmlspecialchars($_POST["func"]) == "classicDetails") {
    $from_date = htmlspecialchars($_POST["from_date"]);
    $to_date = htmlspecialchars($_POST["to_date"]);
    $get_item_id = htmlspecialchars(str_replace(' ', '+', $_POST['item_id']));

    $query_item_id = '';
    if ($get_item_id != '') { $query_item_id = 'AND item_id LIKE "%'.$get_item_id.'%"'; }

    $sql = mysqli_query($conn,"SELECT
          COALESCE(SUM(CASE WHEN date_cutend IS NOT NULL AND FROM_UNIXTIME(date_cutend) >= '$from_date 00:00:00' AND FROM_UNIXTIME(date_cutend) <= '$to_date 23:59:59' THEN db_cut_r ELSE 0 END), 0) AS db_cut_r,
          COALESCE(SUM(CASE WHEN date_cutend IS NOT NULL AND FROM_UNIXTIME(date_cutend) >= '$from_date 00:00:00' AND FROM_UNIXTIME(date_cutend) <= '$to_date 23:59:59' THEN db_cut_l ELSE 0 END), 0) AS db_cut_l,

          COALESCE(SUM(CASE WHEN date_pressend IS NOT NULL AND FROM_UNIXTIME(date_pressend) >= '$from_date 00:00:00' AND FROM_UNIXTIME(date_pressend) <= '$to_date 23:59:59' THEN db_press_r ELSE 0 END), 0) AS db_press_r,
          COALESCE(SUM(CASE WHEN date_pressend IS NOT NULL AND FROM_UNIXTIME(date_pressend) >= '$from_date 00:00:00' AND FROM_UNIXTIME(date_pressend) <= '$to_date 23:59:59' THEN db_press_l ELSE 0 END), 0) AS db_press_l,

          COALESCE(SUM(CASE WHEN date_processend IS NOT NULL AND FROM_UNIXTIME(date_processend) >= '$from_date 00:00:00' AND FROM_UNIXTIME(date_processend) <= '$to_date 23:59:59' THEN db_process_r ELSE 0 END), 0) AS db_process_r,
          COALESCE(SUM(CASE WHEN date_processend IS NOT NULL AND FROM_UNIXTIME(date_processend) >= '$from_date 00:00:00' AND FROM_UNIXTIME(date_processend) <= '$to_date 23:59:59' THEN db_process_l ELSE 0 END), 0) AS db_process_l,

          COALESCE(SUM(CASE WHEN date_cleanend IS NOT NULL AND FROM_UNIXTIME(date_cleanend) >= '$from_date 00:00:00' AND FROM_UNIXTIME(date_cleanend) <= '$to_date 23:59:59' THEN db_clean_r ELSE 0 END), 0) AS db_clean_r,
          COALESCE(SUM(CASE WHEN date_cleanend IS NOT NULL AND FROM_UNIXTIME(date_cleanend) >= '$from_date 00:00:00' AND FROM_UNIXTIME(date_cleanend) <= '$to_date 23:59:59' THEN db_clean_l ELSE 0 END), 0) AS db_clean_l
      FROM production_classic;
      ");

    $parameters = mysqli_fetch_array($sql);

    echo json_encode(["result" => "ok", "data" => $parameters]);
  } else if (htmlspecialchars($_POST["func"]) == "ordersStat") {
    $from_date = htmlspecialchars($_POST["from_date"]);
    $to_date = htmlspecialchars($_POST["to_date"]);
    $get_item_id = htmlspecialchars(str_replace(' ', '+', $_POST['item_id']));

    $query_item_id = '';
    if ($get_item_id != '') { $query_item_id = 'AND item_id LIKE "%'.$get_item_id.'%"'; }

    $sql = mysqli_query($conn,"SELECT
            SUM(CASE
                WHEN SUBSTRING_INDEX(item_id, '+', 1) REGEXP '^[0-9]+$' THEN
                    CASE WHEN amount_type != 0 THEN amount / 2 ELSE amount END
                ELSE 0
            END) AS amount_classic,
            SUM(CASE
                WHEN SUBSTRING_INDEX(item_id, '+', 1) REGEXP '^CL[P|M]?[0-9]+$' THEN
                    CASE WHEN amount_type != 0 THEN amount / 2 ELSE amount END
                ELSE 0
            END) AS amount_climair,
            SUM(CASE
                WHEN SUBSTRING_INDEX(item_id, '+', 1) REGEXP '^F[0-9]{4}$' THEN
                    CASE WHEN amount_type != 0 THEN amount / 2 ELSE amount END
                ELSE 0
            END) AS amount_sporty,
            SUM(CASE
                WHEN SUBSTRING_INDEX(item_id, '+', 1) REGEXP '^FR[0-9]{4}$' THEN
                    CASE WHEN amount_type != 0 THEN amount / 2 ELSE amount END
                ELSE 0
            END) AS amount_injmold,
            SUM(CASE
                WHEN SUBSTRING_INDEX(item_id, '+', 1) REGEXP '^[0-9]+$' THEN
                    CASE WHEN amount_type != 0 THEN taken_out / 2 ELSE taken_out END
                ELSE 0
            END) AS taken_out_classic,
            SUM(CASE
                WHEN SUBSTRING_INDEX(item_id, '+', 1) REGEXP '^CL[P|M]?[0-9]+$' THEN
                    CASE WHEN amount_type != 0 THEN taken_out / 2 ELSE taken_out END
                ELSE 0
            END) AS taken_out_climair,
            SUM(CASE
                WHEN SUBSTRING_INDEX(item_id, '+', 1) REGEXP '^F[0-9]{4}$' THEN
                    CASE WHEN amount_type != 0 THEN taken_out / 2 ELSE taken_out END
                ELSE 0
            END) AS taken_out_sporty,
            SUM(CASE
                WHEN SUBSTRING_INDEX(item_id, '+', 1) REGEXP '^FR[0-9]{4}$' THEN
                    CASE WHEN amount_type != 0 THEN taken_out / 2 ELSE taken_out END
                ELSE 0
            END) AS taken_out_injmold
        FROM
            warehouse_reservation
        WHERE
            is_active = 0 AND is_deleted = 0 $query_item_id
            AND FROM_UNIXTIME(date_end) >= '$from_date 00:00:00' AND FROM_UNIXTIME(date_end) <= '$to_date 23:59:59'");

    $parameters = mysqli_fetch_array($sql);

    echo json_encode(["result" => "ok", "data" => $parameters]);
  } else if (htmlspecialchars($_POST["func"]) == "scrapTable") {
    $from_date = htmlspecialchars($_POST["from_date"]);
    $to_date = htmlspecialchars($_POST["to_date"]);
    $get_item_id = htmlspecialchars(str_replace(' ', '+', $_POST['item_id']));

    $query_item_id = '';
    if ($get_item_id != '') { $query_item_id = 'AND item_id LIKE "%'.$get_item_id.'%"'; }

    $parameters = array();

    $query = "SELECT * FROM scrap_removal WHERE FROM_UNIXTIME(date_create) >= '$from_date 00:00:00' AND FROM_UNIXTIME(date_create) <= '$to_date 23:59:59' $query_item_id";
    if ($result = $conn->query($query)) {
      while ($c_scrap = $result->fetch_assoc()) {

        $parameters[] = [
          "date_create" => date('Y. m. d. H:i:s', $c_scrap['date_create']),
          "wh_id" => $c_scrap['wh_id'],
          "item_id" => $c_scrap['item_id'],
          "right_db" => $c_scrap['right_db'],
          "left_db" => $c_scrap['left_db'],
          "reason" => $c_scrap['reason']
        ];

      }
    }

    echo json_encode(["result" => "ok", "data" => $parameters]);
  } else if (htmlspecialchars($_POST["func"]) == "returnGoodsTable") {
    $from_date = htmlspecialchars($_POST["from_date"]);
    $to_date = htmlspecialchars($_POST["to_date"]);
    $get_item_id = htmlspecialchars(str_replace(' ', '+', $_POST['item_id']));

    $query_item_id = '';
    if ($get_item_id != '') { $query_item_id = 'AND item_id LIKE "%'.$get_item_id.'%"'; }

    $parameters = array();

    $query = "SELECT * FROM return_goods WHERE FROM_UNIXTIME(return_date) >= '$from_date 00:00:00' AND FROM_UNIXTIME(return_date) <= '$to_date 23:59:59' $query_item_id";
    if ($result = $conn->query($query)) {
      while ($c_scrap = $result->fetch_assoc()) {

        $parameters[] = [
          "date_create" => date('Y. m. d.', $c_scrap['return_date']),
          "name" => $c_scrap['name'],
          "item_id" => $c_scrap['item_id'],
          "pack_id" => $c_scrap['pack_id'],
          "order_id" => $c_scrap['order_id'],
          "return_reason" => $c_scrap['return_reason'],
          "is_withdraw" => $c_scrap['is_withdraw'],
          "cancellation_invoice" => $c_scrap['cancellation_invoice'],
          "is_scrap" => $c_scrap['is_scrap'],
          "is_warehoused" => $c_scrap['is_warehoused'],
          "reason" => $c_scrap['reason'],
          "note" => $c_scrap['note'],
          "is_saved" => $c_scrap['is_saved'] == 1 ? 'igen' : 'nem'
        ];

      }
    }

    echo json_encode(["result" => "ok", "data" => $parameters]);
  } else if (htmlspecialchars($_POST["func"]) == "warrantyTable") {
    $from_date = htmlspecialchars($_POST["from_date"]);
    $to_date = htmlspecialchars($_POST["to_date"]);
    $get_item_id = htmlspecialchars(str_replace(' ', '+', $_POST['item_id']));

    $query_item_id = '';
    if ($get_item_id != '') { $query_item_id = 'AND item_id LIKE "%'.$get_item_id.'%"'; }

    $parameters = array();

    $query = "SELECT * FROM warranty_removal WHERE FROM_UNIXTIME(date_create) >= '$from_date 00:00:00' AND FROM_UNIXTIME(date_create) <= '$to_date 23:59:59' $query_item_id";
    if ($result = $conn->query($query)) {
      while ($c_scrap = $result->fetch_assoc()) {

        $parameters[] = [
          "date_create" => date('Y. m. d. H:i:s', $c_scrap['date_create']),
          "name" => $c_scrap['name'],
          "mail" => $c_scrap['mail'],
          "order_id" => $c_scrap['order_id'],
          "item_id" => $c_scrap['item_id'],
          "right_db" => $c_scrap['right_db'],
          "left_db" => $c_scrap['left_db'],
          "reason" => $c_scrap['reason'],
          "note" => $c_scrap['note']
        ];

      }
    }

    echo json_encode(["result" => "ok", "data" => $parameters]);
  } else if (htmlspecialchars($_POST["func"]) == "OpenSettings") {

    $keys = ['plexi_price', 'granules_price', 'kwh_price'];
    $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'];
    }

    echo json_encode([
      'plexi_price' => $params['plexi_price'],
      'granules_price' => $params['granules_price'],
      'kwh_price' => $params['kwh_price'],
      'result' => 'ok'
    ]);
  } else if (htmlspecialchars($_POST["func"]) == "SaveSettings") {
    $params = [
      'plexi_price' => htmlspecialchars($_POST["plexi_price"]),
      'granules_price' => htmlspecialchars($_POST["granules_price"]),
      'kwh_price' => htmlspecialchars($_POST["kwh_price"])
    ];

    $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"]) == "ExportGenerator") {
    $from_date = htmlspecialchars($_POST["from_date"]);
    $to_date = htmlspecialchars($_POST["to_date"]);
    $type = htmlspecialchars($_POST["type"]);

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

    $query_item_id = '';
    if ($get_item_id != '') { $query_item_id = 'AND item_id LIKE "%'.$get_item_id.'%"'; }

    $parameters = array();

    if ($type == 'classic') {
      $parameters[] = [
        "item_id" => "Cikkszám", "db_start" => "Mennyiség", "date_start" => "Gyártásba került", "date_prep" => "Szerszám elők.",
        "date_prepend" => "Szerszám elők. STOP", "remain_r" => "Maradék j", "remain_l" => "Maradék b", "ordered" => "Megrendelve",
        "tablesize_x" => "Táblaméret x", "tablesize_y" => "Táblaméret y", "date_cut" => "Terítékfelvágás", "date_cutend" => "Terítékfelvágás STOP",
        "db_cut_r" => "Felvágott j", "db_cut_l" => "Felvágott b", "date_press" => "Préslégformázás", "date_pressend" => "Préslégformázás STOP",
        "db_press_r" => "Préslégformázott j", "db_press_l" => "Préslégformázott b", "press_machine" => "Présgép", "date_process" => "Feldolgozás",
        "date_processend" => "Feldolgozás STOP", "db_process_r" => "Feldolgozott j", "db_process_l" => "Feldolgozott b", "process_mode" => "Feldolgozás módja",
        "date_clean" => "Tisztítás", "date_cleanend" => "Tisztítás STOP", "db_clean_r" => "Tisztított j", "db_clean_l" => "Tisztított b",
        "date_warehouseend" => "Raktározás / Gyártás lezárva", "db_revenue_bulk_r" => "Raktározva j", "db_revenue_bulk_l" => "Raktározva b", "db_table" => "Táblamennyiség"
      ];

      $query = "SELECT * FROM production_classic WHERE FROM_UNIXTIME(date_revenue) >= '$from_date 00:00:00' AND FROM_UNIXTIME(date_revenue) <= '$to_date 23:59:59' AND stage = 0 $query_item_id";
      if ($result = $conn->query($query)) {
        while ($c_export = $result->fetch_assoc()) {

          $parameters[] = [
            "item_id" => $c_export['item_id'],
            "db_start" => $c_export['db_start'],
            "date_start" => date('Y. m. d. H:i:s', $c_export['date_start']),
            "date_prep" => date('Y. m. d. H:i:s', $c_export['date_prep']),
            "date_prepend" => date('Y. m. d. H:i:s', $c_export['date_prepend']),
            "remain_r" => $c_export['remain_r'],
            "remain_l" => $c_export['remain_l'],
            "ordered" => date('Y. m. d. H:i:s', $c_export['ordered']),
            "tablesize_x" => $c_export['tablesize_x'],
            "tablesize_y" => $c_export['tablesize_y'],
            "db_table" => $c_export['db_table'],
            "date_cut" => date('Y. m. d. H:i:s', $c_export['date_cut']),
            "date_cutend" => date('Y. m. d. H:i:s', $c_export['date_cutend']),
            "db_cut_r" => $c_export['db_cut_r'],
            "db_cut_l" => $c_export['db_cut_l'],
            "date_press" => date('Y. m. d. H:i:s', $c_export['date_press']),
            "date_pressend" => date('Y. m. d. H:i:s', $c_export['date_pressend']),
            "db_press_r" => $c_export['db_press_r'],
            "db_press_l" => $c_export['db_press_l'],
            "press_machine" => $c_export['press_machine'],
            "date_process" => date('Y. m. d. H:i:s', $c_export['date_process']),
            "date_processend" => date('Y. m. d. H:i:s', $c_export['date_processend']),
            "db_process_r" => $c_export['db_process_r'],
            "db_process_l" => $c_export['db_process_l'],
            "process_mode" => $c_export['process_mode'],
            "date_clean" => date('Y. m. d. H:i:s', $c_export['date_clean']),
            "date_cleanend" => date('Y. m. d. H:i:s', $c_export['date_cleanend']),
            "db_clean_r" => $c_export['db_clean_r'],
            "db_clean_l" => $c_export['db_clean_l'],
            "date_warehouseend" => date('Y. m. d. H:i:s', $c_export['date_warehouseend']),
            "db_revenue_bulk_r" => $c_export['db_revenue_bulk_r'],
            "db_revenue_bulk_l" => $c_export['db_revenue_bulk_l']
          ];

        }
      }
    } else if ($type == 'sporty') {
      $parameters[] = [
        "item_id" => "Cikkszám", "db_start" => "Mennyiség", "date_start" => "Gyártásba került", "remain_r" => "Maradék j",
        "remain_l" => "Maradék b", "ordered" => "Megrendelve", "tablesize_x" => "Táblaméret x", "tablesize_y" => "Táblaméret y",
        "db_table" => "Táblamennyiség", "date_cut" => "Terítékfelvágás", "date_cutend" => "Terítékfelvágás STOP", "db_cut_r" => "Felvágott j",
        "db_cut_l" => "Felvágott b", "date_press" => "Préselés", "date_pressend" => "Préselés STOP", "db_press_r" => "Préselt j",
        "db_press_l" => "Préselt b", "date_warehouseend" => "Raktározás / Gyártás lezárva", "db_revenue_bulk_r" => "Raktározva j", "db_revenue_bulk_l" => "Raktározva b"
      ];

      $query = "SELECT * FROM production_sporty WHERE FROM_UNIXTIME(date_revenue) >= '$from_date 00:00:00' AND FROM_UNIXTIME(date_revenue) <= '$to_date 23:59:59' AND stage = 0 $query_item_id";
      if ($result = $conn->query($query)) {
        while ($c_export = $result->fetch_assoc()) {

          $parameters[] = [
            "item_id" => $c_export['item_id'],
            "db_start" => $c_export['db_start'],
            "date_start" => date('Y. m. d. H:i:s', $c_export['date_start']),
            "remain_r" => $c_export['remain_r'],
            "remain_l" => $c_export['remain_l'],
            "ordered" => date('Y. m. d. H:i:s', $c_export['ordered']),
            "tablesize_x" => $c_export['tablesize_x'],
            "tablesize_y" => $c_export['tablesize_y'],
            "db_table" => $c_export['db_table'],
            "date_cut" => date('Y. m. d. H:i:s', $c_export['date_cut']),
            "date_cutend" => date('Y. m. d. H:i:s', $c_export['date_cutend']),
            "db_cut_r" => $c_export['db_cut_r'],
            "db_cut_l" => $c_export['db_cut_l'],
            "date_press" => date('Y. m. d. H:i:s', $c_export['date_press']),
            "date_pressend" => date('Y. m. d. H:i:s', $c_export['date_pressend']),
            "db_press_r" => $c_export['db_press_r'],
            "db_press_l" => $c_export['db_press_l'],
            "date_warehouseend" => date('Y. m. d. H:i:s', $c_export['date_warehouseend']),
            "db_revenue_bulk_r" => $c_export['db_revenue_bulk_r'],
            "db_revenue_bulk_l" => $c_export['db_revenue_bulk_l']
          ];

        }
      }
    } else if ($type == 'injmold') {
      $parameters[] = [
        "item_id" => "Cikkszám", "db_start" => "Mennyiség", "date_start" => "Gyártásba került", "date_prep" => "Szerszám elők.",
        "date_prepend" => "Szerszám elők. STOP", "ordered" => "Megrendelve", "db_granules" => "Rendelt granulátum", "date_process" => "Fröccsöntés",
        "date_processend" => "Fröccsöntés STOP", "db_process_r" => "Fröccsöntött j", "db_process_l" => "Fröccsöntött b", "db_granules_used" => "Használt anyag",
        "kwh_start" => "Villanyóra start", "kwh_stop" => "Villanyóra stop", "date_clean" => "Utómunka", "date_cleanend" => "Utómunka STOP",
        "db_clean_r" => "Utómunka j", "db_clean_l" => "Utómunka b", "date_warehouseend" => "Raktározás / Gyártás lezárva", "db_revenue_bulk_r" => "Raktározva j",
        "db_revenue_bulk_l" => "Raktározva b"
      ];

      $query = "SELECT * FROM production_injmold WHERE FROM_UNIXTIME(date_revenue) >= '$from_date 00:00:00' AND FROM_UNIXTIME(date_revenue) <= '$to_date 23:59:59' AND stage = 0 $query_item_id";
      if ($result = $conn->query($query)) {
        while ($c_export = $result->fetch_assoc()) {

          $parameters[] = [
            "item_id" => $c_export['item_id'],
            "db_start" => $c_export['db_start'],
            "date_start" => date('Y. m. d. H:i:s', $c_export['date_start']),
            "date_prep" => date('Y. m. d. H:i:s', $c_export['date_prep']),
            "date_prepend" => date('Y. m. d. H:i:s', $c_export['date_prepend']),
            "ordered" => date('Y. m. d. H:i:s', $c_export['ordered']),
            "db_granules" => $c_export['db_granules'],
            "date_process" => date('Y. m. d. H:i:s', $c_export['date_process']),
            "date_processend" => date('Y. m. d. H:i:s', $c_export['date_processend']),
            "db_process_r" => $c_export['db_process_r'],
            "db_process_l" => $c_export['db_process_l'],
            "db_granules_used" => $c_export['db_granules_used'],
            "kwh_start" => $c_export['kwh_start'],
            "kwh_stop" => $c_export['kwh_stop'],
            "date_clean" => date('Y. m. d. H:i:s', $c_export['date_clean']),
            "date_cleanend" => date('Y. m. d. H:i:s', $c_export['date_cleanend']),
            "db_clean_r" => $c_export['db_clean_r'],
            "db_clean_l" => $c_export['db_clean_l'],
            "date_warehouseend" => date('Y. m. d. H:i:s', $c_export['date_warehouseend']),
            "db_revenue_bulk_r" => $c_export['db_revenue_bulk_r'],
            "db_revenue_bulk_l" => $c_export['db_revenue_bulk_l']
          ];

        }
      }
    } else if ($type == 'boxing') {
      $parameters[] = [
        "item_id" => 'Cikkszám', "db_start" => 'Mennyiség', "date_start" => 'Dobozolásra került',
        "date_warehouseend" => 'Raktározás / Dobozolás lezárva', "db_revenue" => 'Raktározva'
      ];

      $query = "SELECT * FROM production_boxing WHERE FROM_UNIXTIME(date_warehouseend) >= '$from_date 00:00:00' AND FROM_UNIXTIME(date_warehouseend) <= '$to_date 23:59:59' AND stage = 0 $query_item_id";
      if ($result = $conn->query($query)) {
        while ($c_export = $result->fetch_assoc()) {

          $parameters[] = [
            "item_id" => $c_export['item_id'],
            "db_start" => $c_export['db_start'],
            "date_start" => date('Y. m. d. H:i:s', $c_export['date_start']),
            "date_warehouseend" => date('Y. m. d. H:i:s', $c_export['date_warehouseend']),
            "db_revenue" => $c_export['db_revenue']
          ];

        }
      }
    } else if ($type == 'orders') {
      $parameters[] = [
        "item_id" => "Cikkszám", "amount" => "Mennyiség db", "reason" => "Rendelés neve / indoklás", "date_create" => "Létrehozva",
        "taken_out" => "Kiszedve db", "order_id" => "Rendelés azonosító", "order_name" => "Rendelő neve", "order_mail" => "Rendelő email-címe",
        "receipt_method" => "Átvételi mód", "note" => "Megjegyzés", "primary_source" => "Elsődleges forrás", "amount_type" => "Mennyiség fajtája",
        "primary_warehouse" => "Elsődleges raktár", "date_end" => "Lezárva", "is_deleted" => "Törölt rendelés", "customer_type" => "Vevőtípus",
      ];

      $query = "SELECT * FROM warehouse_reservation WHERE FROM_UNIXTIME(date_create) >= '$from_date 00:00:00' AND FROM_UNIXTIME(date_create) <= '$to_date 23:59:59' AND is_active = 0 $query_item_id";
      if ($result = $conn->query($query)) {
        while ($c_export = $result->fetch_assoc()) {

          $amount_type = 'pár';
          if ($c_export['amount_type'] == "1") {
            $amount_type = 'jobb';
          } else if ($c_export['amount_type'] == "2") {
            $amount_type = 'bal';
          }

          $parameters[] = [
            "item_id" => $c_export['item_id'],
            "amount" => $c_export['amount'],
            "reason" => $c_export['reason'],
            "date_create" => date('Y. m. d. H:i:s', $c_export['date_create']),
            "taken_out" => $c_export['taken_out'],
            "order_id" => $c_export['order_id'],
            "order_name" => $c_export['order_name'],
            "order_mail" => $c_export['order_mail'],
            "customer_type" => $c_export['customer_type'],
            "receipt_method" => $c_export['receipt_method'],
            "note" => $c_export['note'],
            "primary_source" => $c_export['primary_source'] == 1 ? 'fóliás' : 'dobozos',
            "amount_type" => $amount_type,
            "primary_warehouse" => $c_export['primary_warehouse'],
            "date_end" => date('Y. m. d. H:i:s', $c_export['date_end']),
            "is_deleted" => $c_export['is_deleted'] == 1 ? 'igen' : 'nem'
          ];

        }
      }
    }

    echo json_encode(["result" => "ok", "data" => $parameters]);
  }

  exit();
}

/* Ár lekérés */
$keys = ['plexi_price', 'granules_price', 'kwh_price'];
$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();

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

?>

<!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>
    .container {
			max-width: 1400px;
			margin: 0 auto;
		}

		header {
			margin-bottom: 32px;
			display: flex;
			justify-content: space-between;
			align-items: center;
			flex-wrap: wrap;
			gap: 16px;
		}

		h1 {
			font-size: 28px;
			font-weight: 600;
		}

		.controls {
			display: flex;
			gap: 12px;
			align-items: center;
			flex-wrap: wrap;
		}

		.tabs {
			display: flex;
      justify-content: space-between;
      align-items: center;
			gap: 8px;
			margin-bottom: 24px;
			border-bottom: 1px solid #bdc3c7;
			padding-bottom: 2px;
		}

		.tab {
      color: #333333;
			padding: 12px 24px;
			background: none;
			border: none;
			border-bottom: 2px solid transparent;
			font-weight: 500;
			cursor: pointer;
			transition: all 0.2s;
		}

		.tab.active {
			color: var(--panelcolor);
			border-bottom-color: var(--panelcolor);
		}

		.tab-content {
			display: none;
		}

		.tab-content.active {
			display: block;
		}

		.cards-grid {
			display: grid;
			grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
			gap: 20px;
			margin-bottom: 20px;
		}

		.card {
			background: var(--toppanel);
			border: 1px solid #dddddd;
			border-radius: 5px;
			padding: 24px;
			box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
      position: relative;
		}

    .card .export {
      position: absolute;
      right: 15px;
      top: 15px;
    }

    .loading .load {
      display: flex;
    }

    .load {
      border-radius: 5px;
      position: absolute;
      inset: 0;
      background: rgba(255,255,255,0.5);
      backdrop-filter: blur(3px);
      display: none;
      align-items: center;
      justify-content: center;
      z-index: 10;
    }

    .load::before {
        content: '';
        width: 30px;
        height: 4px;
        background: var(--panelcolor);
        position: relative;
        animation: lineToSquare 2s ease-in-out infinite;
    }

    @keyframes lineToSquare {
        0% {
            width: 30px; height: 4px;
            transform: rotate(0deg);
            border-radius: 2;
        }
        20% {
            width: 30px; height: 4px;
            transform: rotate(90deg);
            border-radius: 2;
        }
        40% {
            width: 30px; height: 30px;
            transform: rotate(90deg);
            border-radius: 5px;
        }
        60% {
            width: 30px; height: 30px;
            transform: rotate(180deg);
            border-radius: 5px;
        }
        80% {
            width: 30px; height: 30px;
            transform: rotate(180deg);
            border-radius: 50%;
        }
        100% {
            width: 30px; height: 4px;
            transform: rotate(180deg);
            border-radius: 2;
        }
    }

		.card h3 {
			font-size: 16px;
			font-weight: 600;
			margin-bottom: 16px;
		}

		.stat-row {
			display: flex;
			justify-content: space-between;
			padding: 8px 0;
			border-bottom: 1px solid #bdc3c7;
		}

		.stat-row:last-child {
			border-bottom: none;
		}

		.stat-label {
			font-size: 14px;
		}

		.stat-value {
			font-weight: 600;
			font-size: 14px;
		}

		.stat-value.highlight {
			color: var(--panelcolor);
		}

		.stat-value.warning {
			color: rgba(168, 75, 47, 1);
		}

		.stat-value.error {
			color: #FF0000;
		}

		.summary-card {
			background: var(--panelcolor);
			color: #ffffff;
			grid-column: 1 / -1;
      margin-bottom: 20px;
		}

		.summary-card h3 {
			color: #ffffff;
		}

		.summary-card .stat-row {
			border-bottom-color: rgba(255, 255, 255, 0.2);
		}

		.summary-card .stat-label,
		.summary-card .stat-value {
			color: #ffffff;
		}

		.chart-container {
			background: var(--toppanel);
			border: 1px solid #ddd;
			border-radius: 5px;
			padding: 24px;
			margin-bottom: 20px;
			box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
      position: relative;
		}

		.chart-container h3 {
			font-size: 18px;
			margin-bottom: 20px;
		}

		.bar-chart {
			display: flex;
			flex-direction: column;
			gap: 16px;
		}

		.bar-item {
			display: flex;
			align-items: center;
			gap: 12px;
		}

		.bar-label {
			min-width: 120px;
			font-size: 14px;
		}

		.bar-visual {
			flex: 1;
			height: 32px;
			background: #bdc3c7;
			border-radius: 5px;
			position: relative;
			overflow: hidden;
		}

		.bar-fill {
			height: 100%;
			background: var(--panelcolor);
			border-radius: 5px;
			transition: width 0.5s ease;
			display: flex;
			align-items: center;
			padding: 0 12px;
			color: #ffffff;
			font-size: 12px;
			font-weight: 600;
		}

		.time-breakdown {
			display: grid;
			grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
			gap: 12px;
		}

		.time-item {
			background: var(--bgcolor);
			padding: 12px;
			border-radius: 5px;
			border: 1px solid #ddd;
		}

		.time-item-label {
			font-size: 12px;
			margin-bottom: 4px;
		}

		.time-item-value {
			font-size: 18px;
			font-weight: 600;
		}

		.export-btn {
			margin-left: auto;
			display: flex;
			gap: 8px;
		}

		@media (max-width: 768px) {
			.cards-grid {
				grid-template-columns: 1fr;
			}

			header {
				flex-direction: column;
				align-items: flex-start;
			}

			.controls {
				width: 100%;
			}
		}
	</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 -->

      <div class="container">
        <header>
          <h1>Statisztika</h1>
          <div class="controls">
            <input type="date" id="filter-date-from" style="height: 17px" value="<?php echo date('Y-m-d', strtotime('first day of last month'));?>">
            <input type="date" id="filter-date-to" style="height: 17px" value="<?php echo date('Y-m-d', strtotime('last day of last month'));?>">
            <input type="text" id="filter-item_id" placeholder="Cikkszám keresés...">
            <button onclick="loadData()">Betöltés</button>
          </div>
        </header>

    		<div class="tabs">
          <div>
      			<button class="tab active" onclick="switchTab('gyartas')">Gyártás</button>
      			<button class="tab" onclick="switchTab('dobozolas')">Dobozolás</button>
      			<button class="tab" onclick="switchTab('rendelesek')">Rendelések</button>
      			<button class="tab" onclick="switchTab('selejt')">Selejt</button>
      			<button class="tab" onclick="switchTab('visszaru')">Visszáru</button>
      			<button class="tab" onclick="switchTab('garancia')">Garancia</button>
          </div>

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

    		<!-- Gyártás TAB -->
    		<div id="gyartas" class="tab-content active">
    			<!-- Cikkszám részletes nézet -->
    			<div id="item-detail-view" class="card" style="display: none; margin-bottom: 24px; border: 2px solid var(--panelcolor);">
            <div class="load"></div>
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
    					<h3 style="margin: 0;">Részletes adatok: <span id="detail-item-id" style="color: var(--panelcolor);"></span></h3>
    					<button onclick="clearSearch()">Vissza az összesítőhöz</button>
    				</div>

    				<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 16px;">

    					<div>
    						<h4 style="font-size: 14px; margin-bottom: 12px;">Gyártási adatok</h4>
    						<div class="stat-row">
    							<span class="stat-label">Darabszám</span>
    							<span class="stat-value highlight" id="detail-quantity">13 db</span>
    						</div>
    						<div class="stat-row">
    							<span class="stat-label">Selejt</span>
    							<span class="stat-value error" id="detail-reject">2 db</span>
    						</div>
    						<div class="stat-row">
    							<span class="stat-label">Selejt %</span>
    							<span class="stat-value warning" id="detail-reject-pct">1 %</span>
    						</div>
                <div class="stat-row">
                  <span class="stat-label">Felhasznált alapanyag</span>
                  <span class="stat-value" id="detail-quantity">5 tábla</span>
                </div>
                <div class="stat-row">
                  <span class="stat-label">Alapanyag ár</span>
                  <span class="stat-value" id="detail-quantity">3000 HUF</span>
                </div>
    					</div>

    					<div>
    						<h4 style="font-size: 14px; margin-bottom: 12px;">Gyártás részletek</h4>
    						<div class="stat-row">
    							<span class="stat-label">Felvágott</span>
    							<span class="stat-value" id="detail-material">5</span>
    						</div>
    						<div class="stat-row">
    							<span class="stat-label">Préselt</span>
    							<span class="stat-value" id="detail-material-cost">4</span>
    						</div>
    						<div class="stat-row">
    							<span class="stat-label">Feldolgozott</span>
    							<span class="stat-value" id="detail-energy">3</span>
    						</div>
                <div class="stat-row">
                  <span class="stat-label">Tisztított</span>
                  <span class="stat-value" id="detail-energy">2</span>
                </div>
                <div class="stat-row">
                  <span class="stat-label">Raktározott</span>
                  <span class="stat-value" id="detail-energy">1</span>
                </div>
    					</div>

    					<div>
    						<h4 style="font-size: 14px; margin-bottom: 12px;">Gyártási lépések ideje</h4>
    						<div class="stat-row">
    							<span class="stat-label">Szerszám előkészítése</span>
    							<span class="stat-value" id="detail-total-time">10:00</span>
    						</div>
    						<div class="stat-row">
    							<span class="stat-label">Terítékfelvágás</span>
    							<span class="stat-value" id="detail-time-cut">3:00</span>
    						</div>
    						<div class="stat-row">
    							<span class="stat-label">Préslégformázás</span>
    							<span class="stat-value" id="detail-time-press">7:10</span>
    						</div>
    						<div class="stat-row">
    							<span class="stat-label">Feldolgozás</span>
    							<span class="stat-value" id="detail-time-process">5:47</span>
    						</div>
                <div class="stat-row">
                  <span class="stat-label">Tisztítás</span>
                  <span class="stat-value" id="detail-time-process">3:42</span>
                </div>
                <div class="stat-row">
                  <span class="stat-label">Teljes gyártás ideje</span>
                  <span class="stat-value" id="detail-time-process">50:10</span>
                </div>
    					</div>
    				</div>

            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 16px;">

              <div>
                <h4 style="font-size: 14px; margin-bottom: 12px;">Dobozolási statisztika</h4>
                <div class="stat-row">
                  <span class="stat-label">Összes raktárra helyezett mennyiség</span>
                  <span class="stat-value" id="detail-total-time">14</span>
                </div>
                <div class="stat-row">
                  <span class="stat-label">Dobozolási átlagidő</span>
                  <span class="stat-value" id="detail-time-cut">12:10</span>
                </div>
              </div>

              <div>
                <h4 style="font-size: 14px; margin-bottom: 12px;">Rendelési statisztika</h4>
                <div class="stat-row">
                  <span class="stat-label">Rendelt pár mennyisége</span>
                  <span class="stat-value" id="detail-total-time">3</span>
                </div>
                <div class="stat-row">
                  <span class="stat-label">Teljesített pár mennyisége</span>
                  <span class="stat-value" id="detail-time-cut">3</span>
                </div>
              </div>

              <div>
                <h4 style="font-size: 14px; margin-bottom: 12px;">Ügyintézési statisztika</h4>
                <div class="stat-row">
                  <span class="stat-label">Selejt kivétek</span>
                  <span class="stat-value" id="detail-total-time">0</span>
                </div>
                <div class="stat-row">
                  <span class="stat-label">Visszárú</span>
                  <span class="stat-value" id="detail-time-cut">1</span>
                </div>
                <div class="stat-row">
                  <span class="stat-label">Garanciális</span>
                  <span class="stat-value" id="detail-time-cut">1</span>
                </div>
              </div>

            </div>

    			</div>


          <!-- Gyártási Statisztika -->
    			<div class="summary-card card" id="summary-view">
            <div class="load"></div>
    				<h3>Összesített Gyártási Adatok</h3>
    				<div class="stat-row">
    					<span class="stat-label">Összes gyártott darab</span>
    					<span class="stat-value" id="total-produced">-</span>
    				</div>
    				<div class="stat-row">
    					<span class="stat-label">Összes selejt</span>
    					<span class="stat-value error" id="total-reject">-</span>
    				</div>
    				<div class="stat-row">
    					<span class="stat-label">Átlagos selejt %</span>
    					<span class="stat-value warning" id="avg-reject-pct">-</span>
    				</div>
    				<div class="stat-row">
    					<span class="stat-label">Teljes anyagköltség</span>
    					<span class="stat-value" id="total-material-cost">-</span>
    				</div>
    			</div>

    			<div class="cards-grid">
    				<div class="card" id="classicProduction">
              <div class="load"></div>
              <a title="Excel export" class="export"><i class="icon" onclick="ExportGenerator('classic');" style="width: 20px; height: 20px; opacity: 0.6;"><i data-feather="download" style="width: 20px; height:20px;"></i></i></a>
    					<h3>Classic</h3>
    					<div class="stat-row">
    						<span class="stat-label">Felvágott</span>
    						<span class="stat-value" id="classic-cut">-</span>
    					</div>
    					<div class="stat-row">
    						<span class="stat-label">Préselt</span>
    						<span class="stat-value" id="classic-pressed">-</span>
    					</div>
    					<div class="stat-row">
    						<span class="stat-label">Feldolgozott</span>
    						<span class="stat-value" id="classic-processed">-</span>
    					</div>
    					<div class="stat-row">
    						<span class="stat-label">Tisztított</span>
    						<span class="stat-value" id="classic-cleaned">-</span>
    					</div>
    					<div class="stat-row">
    						<span class="stat-label">Raktározott</span>
    						<span class="stat-value highlight" id="classic-revenued">-</span>
    					</div>
    					<div class="stat-row">
    						<span class="stat-label">Selejt</span>
    						<span class="stat-value error" id="classic-reject">-</span>
    					</div>
    					<div class="stat-row">
    						<span class="stat-label">Alapanyag</span>
    						<span class="stat-value" id="classic-material">-</span>
    					</div>
    					<div class="stat-row">
    						<span class="stat-label">Anyagköltség</span>
    						<span class="stat-value" id="classic-cost">-</span>
    					</div>
    				</div>

    				<div class="card" id="sportyProduction">
              <div class="load"></div>
              <a title="Excel export" class="export"><i class="icon" onclick="ExportGenerator('sporty');" style="width: 20px; height: 20px; opacity: 0.6;"><i data-feather="download" style="width: 20px; height:20px;"></i></i></a>
    					<h3>Sporty</h3>
    					<div class="stat-row">
    						<span class="stat-label">Felvágott</span>
    						<span class="stat-value" id="sporty-cut">-</span>
    					</div>
    					<div class="stat-row">
    						<span class="stat-label">Préselt</span>
    						<span class="stat-value" id="sporty-pressed">-</span>
    					</div>
    					<div class="stat-row">
    						<span class="stat-label">Raktározott</span>
    						<span class="stat-value highlight" id="sporty-revenued">-</span>
    					</div>
    					<div class="stat-row">
    						<span class="stat-label">Selejt</span>
    						<span class="stat-value error" id="sporty-reject">-</span>
    					</div>
    					<div class="stat-row">
    						<span class="stat-label">Alapanyag</span>
    						<span class="stat-value" id="sporty-material">-</span>
    					</div>
    					<div class="stat-row">
    						<span class="stat-label">Anyagköltség</span>
    						<span class="stat-value" id="sporty-cost">-</span>
    					</div>
    				</div>

    				<div class="card" id="injmoldProduction">
              <div class="load"></div>
              <a title="Excel export" class="export"><i class="icon" onclick="ExportGenerator('injmold');" style="width: 20px; height: 20px; opacity: 0.6;"><i data-feather="download" style="width: 20px; height:20px;"></i></i></a>
    					<h3>Fröccsöntött</h3>
    					<div class="stat-row">
    						<span class="stat-label">Fröccsöntött</span>
    						<span class="stat-value" id="injmold-molded">-</span>
    					</div>
    					<div class="stat-row">
    						<span class="stat-label">Tisztított</span>
    						<span class="stat-value" id="injmold-cleaned">-</span>
    					</div>
    					<div class="stat-row">
    						<span class="stat-label">Raktározott</span>
    						<span class="stat-value highlight" id="injmold-revenued">-</span>
    					</div>
    					<div class="stat-row">
    						<span class="stat-label">Selejt</span>
    						<span class="stat-value error" id="injmold-reject">-</span>
    					</div>
    					<div class="stat-row">
    						<span class="stat-label">Granulátum</span>
    						<span class="stat-value" id="injmold-granulate">-</span>
    					</div>
    					<div class="stat-row">
    						<span class="stat-label">Anyagköltség</span>
    						<span class="stat-value" id="injmold-material-cost">-</span>
    					</div>
    					<div class="stat-row">
    						<span class="stat-label">Áram</span>
    						<span class="stat-value" id="injmold-energy">-</span>
    					</div>
    					<div class="stat-row">
    						<span class="stat-label">Áramköltség</span>
    						<span class="stat-value" id="injmold-energy-cost">-</span>
    					</div>
    				</div>
    			</div>

          <div class="chart-container" id="classicDetails">
            <div class="load"></div>
            <h3>Lezárt munkafolyamatok - Classic</h3>
            <div class="time-breakdown">
              <div class="time-item">
                <div class="time-item-label">Felvágott</div>
                <div class="time-item-value" id="classic-cut-db">-</div>
              </div>
              <div class="time-item">
                <div class="time-item-label">Préselt</div>
                <div class="time-item-value" id="classic-press-db">-</div>
              </div>
              <div class="time-item">
                <div class="time-item-label">Feldolgozott</div>
                <div class="time-item-value" id="classic-process-db">-</div>
              </div>
              <div class="time-item">
                <div class="time-item-label">Tisztított</div>
                <div class="time-item-value" id="classic-clean-db">-</div>
              </div>
            </div>
          </div>

    			<div class="chart-container" id="classicTime">
            <div class="load"></div>
    				<h3>Időbontás - Classic</h3>
    				<div class="time-breakdown">
    					<div class="time-item">
    						<div class="time-item-label">Átlag szerszám előkészítés</div>
    						<div class="time-item-value" id="classic-time-1">-</div>
    					</div>
    					<div class="time-item">
    						<div class="time-item-label">Átlag terítékfelvágás</div>
    						<div class="time-item-value" id="classic-time-2">-</div>
    					</div>
    					<div class="time-item">
    						<div class="time-item-label">Átlag préslégformázás</div>
    						<div class="time-item-value" id="classic-time-3">-</div>
    					</div>
    					<div class="time-item">
    						<div class="time-item-label">Átlag feldolgozás</div>
    						<div class="time-item-value" id="classic-time-4">-</div>
    					</div>
    					<div class="time-item">
    						<div class="time-item-label">Átlag tisztítás</div>
    						<div class="time-item-value" id="classic-time-5">-</div>
    					</div>
              <div class="time-item">
                <div class="time-item-label">Átlagosan összesen</div>
                <div class="time-item-value" id="classic-time-6">-</div>
              </div>
    				</div>

            <br clear="all">

            <div class="time-breakdown">
              <div class="time-item">
                <div class="time-item-label">Összesen szerszám előkészítés</div>
                <div class="time-item-value" id="classic-time-1-sum">-</div>
              </div>
              <div class="time-item">
                <div class="time-item-label">Összesen terítékfelvágás</div>
                <div class="time-item-value" id="classic-time-2-sum">-</div>
              </div>
              <div class="time-item">
                <div class="time-item-label">Összesen préslégformázás</div>
                <div class="time-item-value" id="classic-time-3-sum">-</div>
              </div>
              <div class="time-item">
                <div class="time-item-label">Összesen feldolgozás</div>
                <div class="time-item-value" id="classic-time-4-sum">-</div>
              </div>
              <div class="time-item">
                <div class="time-item-label">Összesen tisztítás</div>
                <div class="time-item-value" id="classic-time-5-sum">-</div>
              </div>
              <div class="time-item">
                <div class="time-item-label">Összesen</div>
                <div class="time-item-value" id="classic-time-6-sum">-</div>
              </div>
            </div>
    			</div>

          <div class="chart-container" id="sportyTime">
            <div class="load"></div>
            <h3>Időbontás - Sporty</h3>
            <div class="time-breakdown">
              <div class="time-item">
                <div class="time-item-label">Átlag terítékfelvágás</div>
                <div class="time-item-value" id="sporty-time-1">-</div>
              </div>
              <div class="time-item">
                <div class="time-item-label">Átlag préselés</div>
                <div class="time-item-value" id="sporty-time-2">-</div>
              </div>
              <div class="time-item">
                <div class="time-item-label">Átlagosan összesen</div>
                <div class="time-item-value" id="sporty-time-3">-</div>
              </div>
            </div>

            <br clear="all">

            <div class="time-breakdown">
              <div class="time-item">
                <div class="time-item-label">Összesen terítékfelvágás</div>
                <div class="time-item-value" id="sporty-time-1-sum">-</div>
              </div>
              <div class="time-item">
                <div class="time-item-label">Összesen préselés</div>
                <div class="time-item-value" id="sporty-time-2-sum">-</div>
              </div>
              <div class="time-item">
                <div class="time-item-label">Összesen</div>
                <div class="time-item-value" id="sporty-time-3-sum">-</div>
              </div>
            </div>
          </div>

          <div class="chart-container" id="injmoldTime">
            <div class="load"></div>
            <h3>Időbontás - Fröccsöntött</h3>
            <div class="time-breakdown">
              <div class="time-item">
                <div class="time-item-label">Átlag szerszám előkészítés</div>
                <div class="time-item-value" id="injmold-time-1">-</div>
              </div>
              <div class="time-item">
                <div class="time-item-label">Átlag fröccsöntés</div>
                <div class="time-item-value" id="injmold-time-2">-</div>
              </div>
              <div class="time-item">
                <div class="time-item-label">Átlag utómunka</div>
                <div class="time-item-value" id="injmold-time-3">-</div>
              </div>
              <div class="time-item">
                <div class="time-item-label">Átlagosan összesen</div>
                <div class="time-item-value" id="injmold-time-4">-</div>
              </div>
            </div>

            <br clear="all">

            <div class="time-breakdown">
              <div class="time-item">
                <div class="time-item-label">Összesen szerszám előkészítés</div>
                <div class="time-item-value" id="injmold-time-1-sum">-</div>
              </div>
              <div class="time-item">
                <div class="time-item-label">Összesen fröccsöntés</div>
                <div class="time-item-value" id="injmold-time-2-sum">-</div>
              </div>
              <div class="time-item">
                <div class="time-item-label">Összesen utómunka</div>
                <div class="time-item-value" id="injmold-time-3-sum">-</div>
              </div>
              <div class="time-item">
                <div class="time-item-label">ősszesen</div>
                <div class="time-item-value" id="injmold-time-4-sum">-</div>
              </div>
            </div>
          </div>

    			<div class="chart-container" id="scrapChart">
            <div class="load"></div>
    				<h3>Selejt Összehasonlítás</h3>
    				<div class="bar-chart">
    					<div class="bar-item">
    						<div class="bar-label">Classic</div>
    						<div class="bar-visual">
    							<div class="bar-fill" style="width: 92%;" id="classic-bar">4.6%</div>
    						</div>
    					</div>
    					<div class="bar-item">
    						<div class="bar-label">Sporty</div>
    						<div class="bar-visual">
    							<div class="bar-fill" style="width: 62%;" id="sporty-bar">3.1%</div>
    						</div>
    					</div>
    					<div class="bar-item">
    						<div class="bar-label">Fröccsöntött</div>
    						<div class="bar-visual">
    							<div class="bar-fill" style="width: 48%;" id="injmold-bar">2.4%</div>
    						</div>
    					</div>
    				</div>
    			</div>
    		</div>

    		<!-- Dobozolás TAB -->
    		<div id="dobozolas" class="tab-content">
    			<div class="cards-grid">
    				<div class="card boxingProduction">
              <div class="load"></div>
    					<h3>Classic Dobozolás</h3>
    					<div class="stat-row">
    						<span class="stat-label">Raktárra helyezett</span>
    						<span class="stat-value highlight" id="pack-classic-qty">-</span>
    					</div>
    					<div class="stat-row">
    						<span class="stat-label">Dobozolási átlagidő</span>
    						<span class="stat-value" id="pack-classic-time">-</span>
    					</div>
              <div class="stat-row">
                <span class="stat-label">Dobozolási összidő</span>
                <span class="stat-value" id="pack-classic-time-sum">-</span>
              </div>
    				</div>

    				<div class="card boxingProduction">
              <div class="load"></div>
    					<h3>Sporty Dobozolás</h3>
    					<div class="stat-row">
    						<span class="stat-label">Raktárra helyezett</span>
    						<span class="stat-value highlight" id="pack-sporty-qty">-</span>
    					</div>
    					<div class="stat-row">
    						<span class="stat-label">Dobozolási átlagidő</span>
    						<span class="stat-value" id="pack-sporty-time">-</span>
    					</div>
              <div class="stat-row">
                <span class="stat-label">Dobozolási összidő</span>
                <span class="stat-value" id="pack-sporty-time-sum">-</span>
              </div>
    				</div>

    				<div class="card boxingProduction">
              <div class="load"></div>
    					<h3>Fröccsöntött Dobozolás</h3>
    					<div class="stat-row">
    						<span class="stat-label">Raktárra helyezett</span>
    						<span class="stat-value highlight" id="pack-injmold-qty">-</span>
    					</div>
    					<div class="stat-row">
    						<span class="stat-label">Dobozolási átlagidő</span>
    						<span class="stat-value" id="pack-injmold-time">-</span>
    					</div>
              <div class="stat-row">
                <span class="stat-label">Dobozolási összidő</span>
                <span class="stat-value" id="pack-injmold-time-sum">-</span>
              </div>
    				</div>
    			</div>

          <div class="card boxingProduction">
            <div class="load"></div>
            <a title="Excel export" class="export"><i class="icon" onclick="ExportGenerator('boxing');" style="width: 20px; height: 20px; opacity: 0.6;"><i data-feather="download" style="width: 20px; height:20px;"></i></i></a>
            <h3>Adatok letöltése</h3>
            <div class="stat-row">
              <span class="stat-label">Excel export</span>
              <span class="stat-value highlight" onclick="ExportGenerator('boxing');" style="cursor: pointer;">Letöltés</span>
            </div>
          </div>
    		</div>

    		<!-- Rendelések TAB -->
    		<div id="rendelesek" class="tab-content">
    			<div class="cards-grid">
    				<div class="card ordersStat">
              <div class="load"></div>
    					<h3>Classic Rendelések</h3>
    					<div class="stat-row">
    						<span class="stat-label">Rendelt pár</span>
    						<span class="stat-value" id="order-classic-ordered">-</span>
    					</div>
    					<div class="stat-row">
    						<span class="stat-label">Teljesített</span>
    						<span class="stat-value highlight" id="order-classic-fulfilled">-</span>
    					</div>
              <div class="stat-row">
                <span class="stat-label">Teljesített %</span>
                <span class="stat-value" id="order-classic-fulfilled-percent">-</span>
              </div>
    				</div>

    				<div class="card ordersStat">
              <div class="load"></div>
    					<h3>Sporty Rendelések</h3>
    					<div class="stat-row">
    						<span class="stat-label">Rendelt pár</span>
    						<span class="stat-value" id="order-sporty-ordered">-</span>
    					</div>
    					<div class="stat-row">
    						<span class="stat-label">Teljesített</span>
    						<span class="stat-value highlight" id="order-sporty-fulfilled">-</span>
    					</div>
              <div class="stat-row">
                <span class="stat-label">Teljesített %</span>
                <span class="stat-value" id="order-sporty-fulfilled-percent">-</span>
              </div>
    				</div>

    				<div class="card ordersStat">
              <div class="load"></div>
    					<h3>Fröccsöntött Rendelések</h3>
    					<div class="stat-row">
    						<span class="stat-label">Rendelt pár</span>
    						<span class="stat-value" id="order-injmold-ordered">-</span>
    					</div>
    					<div class="stat-row">
    						<span class="stat-label">Teljesített</span>
    						<span class="stat-value highlight" id="order-injmold-fulfilled">-</span>
    					</div>
              <div class="stat-row">
                <span class="stat-label">Teljesített %</span>
                <span class="stat-value" id="order-injmold-fulfilled-percent">-</span>
              </div>
    				</div>

    				<div class="card ordersStat">
              <div class="load"></div>
    					<h3>ClimAir Rendelések</h3>
    					<div class="stat-row">
    						<span class="stat-label">Rendelt pár</span>
    						<span class="stat-value" id="order-climair-ordered">-</span>
    					</div>
    					<div class="stat-row">
    						<span class="stat-label">Teljesített</span>
    						<span class="stat-value highlight" id="order-climair-fulfilled">-</span>
    					</div>
              <div class="stat-row">
                <span class="stat-label">Teljesített %</span>
                <span class="stat-value" id="order-climair-fulfilled-percent">-</span>
              </div>
    				</div>
    			</div>

          <div class="card ordersStat">
            <div class="load"></div>
            <a title="Excel export" class="export"><i class="icon" onclick="ExportGenerator('orders');" style="width: 20px; height: 20px; opacity: 0.6;"><i data-feather="download" style="width: 20px; height:20px;"></i></i></a>
            <h3>Adatok letöltése</h3>
            <div class="stat-row">
              <span class="stat-label">Excel export</span>
              <span class="stat-value highlight" onclick="ExportGenerator('orders');" style="cursor: pointer;">Letöltés</span>
            </div>
          </div>
    		</div>

    		<!-- Selejt TAB -->
    		<div id="selejt" class="tab-content">
    			<div class="card" id="scrapTable">
            <div class="load"></div>
            <a title="Excel export" class="export"><i class="icon" onclick="exportCSV('selejt');" style="width: 20px; height: 20px; opacity: 0.6;"><i data-feather="download" style="width: 20px; height:20px;"></i></i></a>
    				<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
    					<h3 style="margin: 0;">Selejt Kivét Lista</h3>
    				</div>
    				<table id="selejt-table">
    					<thead>
    						<tr>
    							<th>Dátum</th>
    							<th>Raktárhely</th>
    							<th>Cikkszám</th>
    							<th>Jobb oldal</th>
    							<th>Bal oldal</th>
    							<th>Selejt oka</th>
    						</tr>
    					</thead>
    					<tbody>
    					</tbody>
    				</table>
    			</div>
    		</div>

    		<!-- Visszáru TAB -->
    		<div id="visszaru" class="tab-content">
    			<div class="card" id="returnGoodsTable">
            <div class="load"></div>
            <a title="Excel export" class="export"><i class="icon" onclick="exportCSV('visszaru');" style="width: 20px; height: 20px; opacity: 0.6;"><i data-feather="download" style="width: 20px; height:20px;"></i></i></a>
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
    					<h3 style="margin: 0;">Visszáru Lista</h3>
    				</div>
    				<table id="visszaru-table">
    					<thead>
    						<tr>
    							<th>Dátum</th>
    							<th>Név</th>
    							<th>Cikkszám</th>
    							<th>Csomagszám</th>
    							<th>Rendelés szám</th>
    							<th>Visszaküldés oka</th>
    							<th>Elállási nyilatkozat</th>
    							<th>Sztornó számla készült</th>
                  <th>Selejt</th>
                  <th>Visszaraktam polcra és bevételeztem</th>
                  <th>Elállás oka</th>
                  <th>Megjegyzés</th>
                  <th>Lezárva</th>
    						</tr>
    					</thead>
    					<tbody>
    					</tbody>
    				</table>
    			</div>
    		</div>

    		<!-- Garancia TAB -->
    		<div id="garancia" class="tab-content">
    			<div class="card" id="warrantyTable">
            <div class="load"></div>
            <a title="Excel export" class="export"><i class="icon" onclick="exportCSV('garancia');" style="width: 20px; height: 20px; opacity: 0.6;"><i data-feather="download" style="width: 20px; height:20px;"></i></i></a>
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
    					<h3 style="margin: 0;">Garanciális Lista</h3>
    				</div>
    				<table id="garancia-table">
    					<thead>
    						<tr>
    							<th>Dátum</th>
    							<th>Ügyfél neve</th>
    							<th>Email</th>
    							<th>Rendelés azonosító</th>
    							<th>Cikkszám</th>
    							<th>Jobb oldal</th>
    							<th>Bal oldal</th>
    							<th>Kivét oka</th>
    							<th>Megjegyzés</th>
    						</tr>
    					</thead>
    					<tbody>
    					</tbody>
    				</table>
    			</div>
    		</div>
    	</div>


      <br clear="all"><br><br>
      <!-- Tartalmi rész vége -->

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

    function switchTab(tabName) {
      document.querySelectorAll('.tab').forEach(tab => tab.classList.remove('active'));
      document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));

      event.target.classList.add('active');
      document.getElementById(tabName).classList.add('active');
    }

    var from_date = '';
    var to_date = '';
    var get_item_id = '';
    function loadData() {
      from_date = document.getElementById('filter-date-from').value;
      to_date = document.getElementById('filter-date-to').value;
      get_item_id = document.getElementById('filter-item_id').value.trim();

      /*if (get_item_id) {
        loadItemDetail();
      } else {
        showSummaryView();
      }*/

      showSummaryView();
    }

    function loadItemDetail() {
      document.getElementById('summary-view').style.display = 'none';
      document.querySelector('.cards-grid').style.display = 'none';
      document.querySelectorAll('.chart-container').forEach(el => el.style.display = 'none');
      document.getElementById('item-detail-view').style.display = 'block';

      switchTab('gyartas');
    }

    var isClassic = false;
    var isSporty = false;
    var isInjmold = false;
    var MaxScrap = 0;
    var ProdData = { classic: {}, sporty: {}, injmold: {} };
    var PriceList = { plexi_price: <?php echo $PriceParams['plexi_price']; ?>, granules_price: <?php echo $PriceParams['granules_price']; ?>, kwh_price: <?php echo $PriceParams['kwh_price']; ?> };
    function showSummaryView() {
      document.getElementById('item-detail-view').style.display = 'none';
      document.getElementById('summary-view').style.display = 'block';
      document.querySelector('.cards-grid').style.display = 'grid';
      document.querySelectorAll('.chart-container').forEach(el => el.style.display = 'block');

      isClassic = false;
      isSporty = false;
      isInjmold = false;
      MaxScrap = 0;
      ProdData = { classic: {}, sporty: {}, injmold: {} };

      document.getElementById('scrapChart').classList.add('loading');
      document.getElementById('summary-view').classList.add('loading');

      classicProduction();
      classicDetails();
      sportyProduction();
      injmoldProduction();
      boxingProduction();
      ordersStat();
      scrapTable();
      returnGoodsTable();
      warrantyTable();
    }

    function formatTime(seconds) {
    	const days = Math.floor(seconds / 86400);
    	const hours = Math.floor((seconds % 86400) / 3600);
    	const minutes = Math.floor((seconds % 3600) / 60);
    	const secs = seconds % 60;
    	return `${days} <span style="opacity: 0.5;">nap</span> ${hours.toString().padStart(2, '0')} <span style="opacity: 0.5;">óra</span> ${minutes.toString().padStart(2, '0')} <span style="opacity: 0.5;">perc</span>`;
    }
    function formatDecimal(num, decimals = 1) {
      const rounded = Math.round(num * Math.pow(10, decimals)) / Math.pow(10, decimals);
      if (Number.isInteger(num)) return num;

      const str = rounded.toFixed(decimals);
      return str.replace(/\.?0+$/, '');
    }

    /* Statisztikák lekérése */
    function classicProduction() {
      document.getElementById('classicProduction').classList.add('loading');
      document.getElementById('classicTime').classList.add('loading');

      const body = 'func=classicProduction&from_date=' + from_date + '&to_date=' + to_date + '&item_id=' + encodeURIComponent(get_item_id).replace(/%20/g, '+');
      get_POST_information("monthlystat.php", body, function(text) {
        let response = JSON.parse(text);
        if (response.result == "ok") {
          Object.keys(response.data).forEach(key => { response.data[key] = response.data[key] ?? 0;});

          document.getElementById("classic-cut").innerHTML = `${response.data.db_cut_r} <span style="opacity: 0.5; margin-right: 15px;">jobb</span> ${response.data.db_cut_l} <span style="opacity: 0.5;">bal</span>`;
          document.getElementById("classic-pressed").innerHTML = `${response.data.db_press_r} <span style="opacity: 0.5; margin-right: 15px;">jobb</span> ${response.data.db_press_l} <span style="opacity: 0.5;">bal</span>`;
          document.getElementById("classic-processed").innerHTML = `${response.data.db_process_r} <span style="opacity: 0.5; margin-right: 15px;">jobb</span> ${response.data.db_process_l} <span style="opacity: 0.5;">bal</span>`;
          document.getElementById("classic-cleaned").innerHTML = `${response.data.db_clean_r} <span style="opacity: 0.5; margin-right: 15px;">jobb</span> ${response.data.db_clean_l} <span style="opacity: 0.5;">bal</span>`;
          document.getElementById("classic-revenued").innerHTML = `${response.data.db_revenue_bulk_r} <span style="opacity: 0.5; margin-right: 15px;">jobb</span> ${response.data.db_revenue_bulk_l} <span style="opacity: 0.5;">bal</span>`;
          document.getElementById("classic-reject").innerHTML = `${response.data.db_scrap} db (${formatDecimal(response.data.percent_scrap, 2)}%)`;
          document.getElementById("classic-material").innerHTML = `${formatDecimal(response.data.tablesize, 2)} <span style="opacity: 0.5; margin-right: 15px;">m<sup style="position: absolute;">2</sup></span>${response.data.db_table} <span style="opacity: 0.5;">tábla</span>`;
          document.getElementById('classicProduction').classList.remove('loading');

          document.getElementById("classic-time-1").innerHTML = formatTime(response.data.prep_time);
          document.getElementById("classic-time-2").innerHTML = formatTime(response.data.cut_time);
          document.getElementById("classic-time-3").innerHTML = formatTime(response.data.press_time);
          document.getElementById("classic-time-4").innerHTML = formatTime(response.data.process_time);
          document.getElementById("classic-time-5").innerHTML = formatTime(response.data.clean_time);
          document.getElementById("classic-time-6").innerHTML = formatTime(response.data.product_time);

          document.getElementById("classic-time-1-sum").innerHTML = formatTime(response.data.prep_time_sum);
          document.getElementById("classic-time-2-sum").innerHTML = formatTime(response.data.cut_time_sum);
          document.getElementById("classic-time-3-sum").innerHTML = formatTime(response.data.press_time_sum);
          document.getElementById("classic-time-4-sum").innerHTML = formatTime(response.data.process_time_sum);
          document.getElementById("classic-time-5-sum").innerHTML = formatTime(response.data.clean_time_sum);
          document.getElementById("classic-time-6-sum").innerHTML = formatTime(response.data.product_time_sum);
          document.getElementById('classicTime').classList.remove('loading');

          isClassic = true;
          ProdData.classic.db_scrap = parseInt(response.data.db_scrap);
          ProdData.classic.percent_scrap = parseFloat(response.data.percent_scrap);
          ProdData.classic.db_revenue = Math.min(parseInt(response.data.db_revenue_bulk_r), parseInt(response.data.db_revenue_bulk_l));
          ProdData.classic.tablesize = parseFloat(response.data.tablesize);
          if (MaxScrap < parseFloat(response.data.percent_scrap)) MaxScrap = parseFloat(response.data.percent_scrap);
          if (isClassic && isSporty && isInjmold) summaryProduction();
          calcPrice('classic');
        } else {
          GenerateAlerts("error", response.result);
        }
      }, function() {
        GenerateAlerts("error", "Hálózati hiba!");
      });
    }
    function sportyProduction() {
      document.getElementById('sportyProduction').classList.add('loading');
      document.getElementById('sportyTime').classList.add('loading');

      const body = 'func=sportyProduction&from_date=' + from_date + '&to_date=' + to_date + '&item_id=' + encodeURIComponent(get_item_id).replace(/%20/g, '+');
      get_POST_information("monthlystat.php", body, function(text) {
        let response = JSON.parse(text);
        if (response.result == "ok") {
          Object.keys(response.data).forEach(key => { response.data[key] = response.data[key] ?? 0;});

          document.getElementById("sporty-cut").innerHTML = `${response.data.db_cut_r} <span style="opacity: 0.5; margin-right: 15px;">jobb</span> ${response.data.db_cut_l} <span style="opacity: 0.5;">bal</span>`;
          document.getElementById("sporty-pressed").innerHTML = `${response.data.db_press_r} <span style="opacity: 0.5; margin-right: 15px;">jobb</span> ${response.data.db_press_l} <span style="opacity: 0.5;">bal</span>`;
          document.getElementById("sporty-revenued").innerHTML = `${response.data.db_revenue_bulk_r} <span style="opacity: 0.5; margin-right: 15px;">jobb</span> ${response.data.db_revenue_bulk_l} <span style="opacity: 0.5;">bal</span>`;
          document.getElementById("sporty-reject").innerHTML = `${response.data.db_scrap} db (${formatDecimal(response.data.percent_scrap, 2)}%)`;
          document.getElementById("sporty-material").innerHTML = `${formatDecimal(response.data.tablesize, 2)} <span style="opacity: 0.5; margin-right: 15px;">m<sup style="position: absolute;">2</sup></span>${response.data.db_table} <span style="opacity: 0.5;">tábla</span>`;
          document.getElementById('sportyProduction').classList.remove('loading');

          document.getElementById("sporty-time-1").innerHTML = formatTime(response.data.cut_time);
          document.getElementById("sporty-time-2").innerHTML = formatTime(response.data.press_time);
          document.getElementById("sporty-time-3").innerHTML = formatTime(response.data.product_time);

          document.getElementById("sporty-time-1-sum").innerHTML = formatTime(response.data.cut_time_sum);
          document.getElementById("sporty-time-2-sum").innerHTML = formatTime(response.data.press_time_sum);
          document.getElementById("sporty-time-3-sum").innerHTML = formatTime(response.data.product_time_sum);
          document.getElementById('sportyTime').classList.remove('loading');

          isSporty = true;
          ProdData.sporty.db_scrap = parseInt(response.data.db_scrap);
          ProdData.sporty.percent_scrap = parseFloat(response.data.percent_scrap);
          ProdData.sporty.db_revenue = Math.min(parseInt(response.data.db_revenue_bulk_r), parseInt(response.data.db_revenue_bulk_l));
          ProdData.sporty.tablesize = parseFloat(response.data.tablesize);
          if (MaxScrap < parseFloat(response.data.percent_scrap)) MaxScrap = parseFloat(response.data.percent_scrap);
          if (isClassic && isSporty && isInjmold) summaryProduction();
          calcPrice('sporty');
        } else {
          GenerateAlerts("error", response.result);
        }
      }, function() {
        GenerateAlerts("error", "Hálózati hiba!");
      });
    }
    function injmoldProduction() {
      document.getElementById('injmoldProduction').classList.add('loading');
      document.getElementById('injmoldTime').classList.add('loading');

      const body = 'func=injmoldProduction&from_date=' + from_date + '&to_date=' + to_date + '&item_id=' + encodeURIComponent(get_item_id).replace(/%20/g, '+');
      get_POST_information("monthlystat.php", body, function(text) {
        let response = JSON.parse(text);
        if (response.result == "ok") {
          Object.keys(response.data).forEach(key => { response.data[key] = response.data[key] ?? 0;});

          document.getElementById("injmold-molded").innerHTML = `${response.data.db_process_r} <span style="opacity: 0.5; margin-right: 15px;">jobb</span> ${response.data.db_process_l} <span style="opacity: 0.5;">bal</span>`;
          document.getElementById("injmold-cleaned").innerHTML = `${response.data.db_clean_r} <span style="opacity: 0.5; margin-right: 15px;">jobb</span> ${response.data.db_clean_l} <span style="opacity: 0.5;">bal</span>`;
          document.getElementById("injmold-revenued").innerHTML = `${response.data.db_revenue_bulk_r} <span style="opacity: 0.5; margin-right: 15px;">jobb</span> ${response.data.db_revenue_bulk_l} <span style="opacity: 0.5;">bal</span>`;
          document.getElementById("injmold-reject").innerHTML = `${response.data.db_scrap} db (${formatDecimal(response.data.percent_scrap, 2)}%)`;
          document.getElementById("injmold-granulate").innerHTML = `${response.data.db_granules_used} <span style="opacity: 0.5;">kg</span>`;
          document.getElementById("injmold-energy").innerHTML = `${response.data.kwh} <span style="opacity: 0.5;">kWh</span>`;
          document.getElementById('injmoldProduction').classList.remove('loading');

          document.getElementById("injmold-time-1").innerHTML = formatTime(response.data.prep_time);
          document.getElementById("injmold-time-2").innerHTML = formatTime(response.data.process_time);
          document.getElementById("injmold-time-3").innerHTML = formatTime(response.data.clean_time);
          document.getElementById("injmold-time-4").innerHTML = formatTime(response.data.product_time);

          document.getElementById("injmold-time-1-sum").innerHTML = formatTime(response.data.prep_time_sum);
          document.getElementById("injmold-time-2-sum").innerHTML = formatTime(response.data.process_time_sum);
          document.getElementById("injmold-time-3-sum").innerHTML = formatTime(response.data.clean_time_sum);
          document.getElementById("injmold-time-4-sum").innerHTML = formatTime(response.data.product_time_sum);
          document.getElementById('injmoldTime').classList.remove('loading');

          isInjmold = true;
          ProdData.injmold.db_scrap = parseInt(response.data.db_scrap);
          ProdData.injmold.percent_scrap = parseFloat(response.data.percent_scrap);
          ProdData.injmold.db_revenue = Math.min(parseInt(response.data.db_revenue_bulk_r), parseInt(response.data.db_revenue_bulk_l));
          ProdData.injmold.db_granules_used = parseFloat(response.data.db_granules_used);
          ProdData.injmold.kwh = parseFloat(response.data.kwh);
          if (MaxScrap < parseFloat(response.data.percent_scrap)) MaxScrap = parseFloat(response.data.percent_scrap);
          if (isClassic && isSporty && isInjmold) summaryProduction();
          calcPrice('injmold');
        } else {
          GenerateAlerts("error", response.result);
        }
      }, function() {
        GenerateAlerts("error", "Hálózati hiba!");
      });
    }
    function summaryProduction() {
      document.getElementById('total-produced').innerHTML = `${ProdData.classic.db_revenue + ProdData.sporty.db_revenue + ProdData.injmold.db_revenue} <span style="opacity: 0.5;">pár</span>`;
      document.getElementById('total-reject').innerHTML = `${ProdData.classic.db_scrap + ProdData.sporty.db_scrap + ProdData.injmold.db_scrap} <span style="opacity: 0.5;">pár</span>`;
      document.getElementById('avg-reject-pct').innerHTML = `${((ProdData.classic.percent_scrap + ProdData.sporty.percent_scrap + ProdData.injmold.percent_scrap) / 3).toFixed(2)} <span style="opacity: 0.5;">%</span>`;

      document.getElementById('summary-view').classList.remove('loading');
      calcScrapChart();
      calcPrice('sum');
    }
    function calcScrapChart() {
      MaxScrap = Math.ceil(MaxScrap);
      document.getElementById('classic-bar').style.width =  ((ProdData.classic.percent_scrap / MaxScrap) * 100) + '%';
      document.getElementById('classic-bar').innerHTML = `${formatDecimal(ProdData.classic.percent_scrap, 2)} %`;
      document.getElementById('sporty-bar').style.width =  ((ProdData.sporty.percent_scrap / MaxScrap) * 100) + '%';
      document.getElementById('sporty-bar').innerHTML = `${formatDecimal(ProdData.sporty.percent_scrap, 2)} %`;
      document.getElementById('injmold-bar').style.width =  ((ProdData.injmold.percent_scrap / MaxScrap) * 100) + '%';
      document.getElementById('injmold-bar').innerHTML = `${formatDecimal(ProdData.injmold.percent_scrap, 2)} %`;

      document.getElementById('scrapChart').classList.remove('loading');
    }
    function calcPrice(type) {
      if (type == "injmold") {
        document.getElementById("injmold-material-cost").innerHTML = `${(ProdData.injmold.db_granules_used * PriceList.granules_price).toLocaleString("hu-HU", { minimumFractionDigits: 0, maximumFractionDigits: 2})} <span style="opacity: 0.5;">Euro</span>`;
        document.getElementById("injmold-energy-cost").innerHTML = `${(ProdData.injmold.kwh * PriceList.kwh_price).toLocaleString("hu-HU", { minimumFractionDigits: 0, maximumFractionDigits: 0})} <span style="opacity: 0.5;">Ft</span>`;
      } else if (type == "sporty") {
        document.getElementById("sporty-cost").innerHTML = `${(ProdData.sporty.tablesize * PriceList.plexi_price).toLocaleString("hu-HU", { minimumFractionDigits: 0, maximumFractionDigits: 2})} <span style="opacity: 0.5;">Euro</span>`;
      } else if (type == "classic") {
        document.getElementById("classic-cost").innerHTML = `${(ProdData.classic.tablesize * PriceList.plexi_price).toLocaleString("hu-HU", { minimumFractionDigits: 0, maximumFractionDigits: 2})} <span style="opacity: 0.5;">Euro</span>`;
      } else if (type == "sum") {
        document.getElementById("total-material-cost").innerHTML = `${((ProdData.injmold.db_granules_used * PriceList.granules_price) + (ProdData.sporty.tablesize * PriceList.plexi_price) + (ProdData.classic.tablesize * PriceList.plexi_price)).toLocaleString("hu-HU", { minimumFractionDigits: 0, maximumFractionDigits: 2})} <span style="opacity: 0.5; margin-right: 15px;">Euro </span>${(ProdData.injmold.kwh * PriceList.kwh_price).toLocaleString("hu-HU", { minimumFractionDigits: 0, maximumFractionDigits: 0})} <span style="opacity: 0.5;">Ft</span>`;
      }
    }

    function classicDetails() {
      document.getElementById('classicDetails').classList.add('loading');

      const body = 'func=classicDetails&from_date=' + from_date + '&to_date=' + to_date + '&item_id=' + encodeURIComponent(get_item_id).replace(/%20/g, '+');
      get_POST_information("monthlystat.php", body, function(text) {
        let response = JSON.parse(text);
        if (response.result == "ok") {
          Object.keys(response.data).forEach(key => { response.data[key] = response.data[key] ?? 0;});

          document.getElementById("classic-cut-db").innerHTML = `${response.data.db_cut_r} <span style="opacity: 0.5; margin-right: 15px;">jobb</span> ${response.data.db_cut_l} <span style="opacity: 0.5;">bal</span>`;
          document.getElementById("classic-press-db").innerHTML = `${response.data.db_press_r} <span style="opacity: 0.5; margin-right: 15px;">jobb</span> ${response.data.db_press_l} <span style="opacity: 0.5;">bal</span>`;
          document.getElementById("classic-process-db").innerHTML = `${response.data.db_process_r} <span style="opacity: 0.5; margin-right: 15px;">jobb</span> ${response.data.db_process_l} <span style="opacity: 0.5;">bal</span>`;
          document.getElementById("classic-clean-db").innerHTML = `${response.data.db_clean_r} <span style="opacity: 0.5; margin-right: 15px;">jobb</span> ${response.data.db_clean_l} <span style="opacity: 0.5;">bal</span>`;

          document.getElementById('classicDetails').classList.remove('loading');
        } else {
          GenerateAlerts("error", response.result);
        }
      }, function() {
        GenerateAlerts("error", "Hálózati hiba!");
      });
    }

    function boxingProduction() {
      document.querySelectorAll('.boxingProduction').forEach(el => {el.classList.add('loading');});

      const body = 'func=boxingProduction&from_date=' + from_date + '&to_date=' + to_date + '&item_id=' + encodeURIComponent(get_item_id).replace(/%20/g, '+');
      get_POST_information("monthlystat.php", body, function(text) {
        let response = JSON.parse(text);
        if (response.result == "ok") {
          Object.keys(response.data).forEach(key => { response.data[key] = response.data[key] ?? 0;});

          document.getElementById("pack-classic-qty").innerHTML = `${response.data.db_revenue_classic} <span style="opacity: 0.5;">doboz</span>`;
          document.getElementById("pack-sporty-qty").innerHTML = `${response.data.db_revenue_sporty} <span style="opacity: 0.5;">doboz</span>`;
          document.getElementById("pack-injmold-qty").innerHTML = `${response.data.db_revenue_injmold} <span style="opacity: 0.5;">doboz</span>`;

          document.getElementById("pack-classic-time").innerHTML = formatTime(response.data.product_time_classic);
          document.getElementById("pack-sporty-time").innerHTML = formatTime(response.data.product_time_sporty);
          document.getElementById("pack-injmold-time").innerHTML = formatTime(response.data.product_time_injmold);

          document.getElementById("pack-classic-time-sum").innerHTML = formatTime(response.data.product_time_classic_sum);
          document.getElementById("pack-sporty-time-sum").innerHTML = formatTime(response.data.product_time_sporty_sum);
          document.getElementById("pack-injmold-time-sum").innerHTML = formatTime(response.data.product_time_injmold_sum);

          document.querySelectorAll('.boxingProduction').forEach(el => {el.classList.remove('loading');});

        } else {
          GenerateAlerts("error", response.result);
        }
      }, function() {
        GenerateAlerts("error", "Hálózati hiba!");
      });
    }
    function ordersStat() {
      document.querySelectorAll('.ordersStat').forEach(el => {el.classList.add('loading');});

      const body = 'func=ordersStat&from_date=' + from_date + '&to_date=' + to_date + '&item_id=' + encodeURIComponent(get_item_id).replace(/%20/g, '+');
      get_POST_information("monthlystat.php", body, function(text) {
        let response = JSON.parse(text);
        if (response.result == "ok") {
          Object.keys(response.data).forEach(key => { response.data[key] = response.data[key] ?? 0;});

          document.getElementById("order-classic-ordered").innerHTML = `${formatDecimal(response.data.amount_classic)} <span style="opacity: 0.5;">pár</span>`;
          document.getElementById("order-sporty-ordered").innerHTML = `${formatDecimal(response.data.amount_sporty)} <span style="opacity: 0.5;">pár</span>`;
          document.getElementById("order-injmold-ordered").innerHTML = `${formatDecimal(response.data.amount_injmold)} <span style="opacity: 0.5;">pár</span>`;
          document.getElementById("order-climair-ordered").innerHTML = `${formatDecimal(response.data.amount_climair)} <span style="opacity: 0.5;">pár</span>`;

          document.getElementById("order-classic-fulfilled").innerHTML = `${formatDecimal(response.data.taken_out_classic)} <span style="opacity: 0.5;">pár</span>`;
          document.getElementById("order-sporty-fulfilled").innerHTML = `${formatDecimal(response.data.taken_out_sporty)} <span style="opacity: 0.5;">pár</span>`;
          document.getElementById("order-injmold-fulfilled").innerHTML = `${formatDecimal(response.data.taken_out_injmold)} <span style="opacity: 0.5;">pár</span>`;
          document.getElementById("order-climair-fulfilled").innerHTML = `${formatDecimal(response.data.taken_out_climair)} <span style="opacity: 0.5;">pár</span>`;

          document.getElementById("order-classic-fulfilled-percent").innerHTML = `${formatDecimal(((parseFloat(response.data.taken_out_classic) / parseFloat(response.data.amount_classic)) * 100), 2)} <span style="opacity: 0.5;">%</span>`;
          document.getElementById("order-sporty-fulfilled-percent").innerHTML = `${formatDecimal(((parseFloat(response.data.taken_out_sporty) / parseFloat(response.data.amount_sporty)) * 100), 2)} <span style="opacity: 0.5;">%</span>`;
          document.getElementById("order-injmold-fulfilled-percent").innerHTML = `${formatDecimal(((parseFloat(response.data.taken_out_injmold) / parseFloat(response.data.amount_injmold)) * 100), 2)} <span style="opacity: 0.5;">%</span>`;
          document.getElementById("order-climair-fulfilled-percent").innerHTML = `${formatDecimal(((parseFloat(response.data.taken_out_climair) / parseFloat(response.data.amount_climair)) * 100), 2)} <span style="opacity: 0.5;">%</span>`;

          document.querySelectorAll('.ordersStat').forEach(el => {el.classList.remove('loading');});

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

    function scrapTable() {
      document.getElementById('scrapTable').classList.add('loading');

      const body = 'func=scrapTable&from_date=' + from_date + '&to_date=' + to_date + '&item_id=' + encodeURIComponent(get_item_id).replace(/%20/g, '+');
      get_POST_information("monthlystat.php", body, function(text) {
        let response = JSON.parse(text);
        if (response.result == "ok") {
          var table = document.getElementById('selejt-table').getElementsByTagName('tbody')[0];
          table.innerHTML = "";

          response.data.forEach((item, i) => {
            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);
            var newCell_6 = newRow.insertCell(5);

            newCell_1.innerHTML = item.date_create;
            newCell_2.innerHTML = item.wh_id;
            newCell_3.innerHTML = item.item_id;
            newCell_4.innerHTML = item.right_db;
            newCell_5.innerHTML = item.left_db;
            newCell_6.innerHTML = item.reason;
          });


          document.getElementById('scrapTable').classList.remove('loading');

        } else {
          GenerateAlerts("error", response.result);
        }
      }, function() {
        GenerateAlerts("error", "Hálózati hiba!");
      });
    }
    function returnGoodsTable() {
      document.getElementById('returnGoodsTable').classList.add('loading');

      const body = 'func=returnGoodsTable&from_date=' + from_date + '&to_date=' + to_date + '&item_id=' + encodeURIComponent(get_item_id).replace(/%20/g, '+');
      get_POST_information("monthlystat.php", body, function(text) {
        let response = JSON.parse(text);
        if (response.result == "ok") {
          var table = document.getElementById('visszaru-table').getElementsByTagName('tbody')[0];
          table.innerHTML = "";

          response.data.forEach((item, i) => {
            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);
            var newCell_6 = newRow.insertCell(5);
            var newCell_7 = newRow.insertCell(6);
            var newCell_8 = newRow.insertCell(7);
            var newCell_9 = newRow.insertCell(8);
            var newCell_10 = newRow.insertCell(9);
            var newCell_11 = newRow.insertCell(10);
            var newCell_12 = newRow.insertCell(11);
            var newCell_13 = newRow.insertCell(12);

            newCell_1.innerHTML = item.date_create;
            newCell_2.innerHTML = item.name;
            newCell_3.innerHTML = item.item_id;
            newCell_4.innerHTML = item.pack_id;
            newCell_5.innerHTML = item.order_id;
            newCell_6.innerHTML = item.return_reason;
            newCell_7.innerHTML = item.is_withdraw;
            newCell_8.innerHTML = item.cancellation_invoice;
            newCell_9.innerHTML = item.is_scrap;
            newCell_10.innerHTML = item.is_warehoused;
            newCell_11.innerHTML = item.reason;
            newCell_12.innerHTML = item.note;
            newCell_13.innerHTML = item.is_saved;
          });


          document.getElementById('returnGoodsTable').classList.remove('loading');

        } else {
          GenerateAlerts("error", response.result);
        }
      }, function() {
        GenerateAlerts("error", "Hálózati hiba!");
      });
    }
    function warrantyTable() {
      document.getElementById('warrantyTable').classList.add('loading');

      const body = 'func=warrantyTable&from_date=' + from_date + '&to_date=' + to_date + '&item_id=' + encodeURIComponent(get_item_id).replace(/%20/g, '+');
      get_POST_information("monthlystat.php", body, function(text) {
        let response = JSON.parse(text);
        if (response.result == "ok") {
          var table = document.getElementById('garancia-table').getElementsByTagName('tbody')[0];
          table.innerHTML = "";

          response.data.forEach((item, i) => {
            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);
            var newCell_6 = newRow.insertCell(5);
            var newCell_7 = newRow.insertCell(6);
            var newCell_8 = newRow.insertCell(7);
            var newCell_9 = newRow.insertCell(8);

            newCell_1.innerHTML = item.date_create;
            newCell_2.innerHTML = item.name;
            newCell_3.innerHTML = item.mail;
            newCell_4.innerHTML = item.order_id;
            newCell_5.innerHTML = item.item_id;
            newCell_6.innerHTML = item.right_db;
            newCell_7.innerHTML = item.left_db;
            newCell_8.innerHTML = item.reason;
            newCell_9.innerHTML = item.note;
          });


          document.getElementById('warrantyTable').classList.remove('loading');

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

    function ExportGenerator(type) {
      if (type == "classic") {
        document.getElementById('classicProduction').classList.add('loading');
        const body = 'func=ExportGenerator&type=classic&from_date=' + from_date + '&to_date=' + to_date + '&item_id=' + encodeURIComponent(get_item_id).replace(/%20/g, '+');
        get_POST_information("monthlystat.php", body, function(text) {
          let response = JSON.parse(text);
          if (response.result == "ok") {
            const hiddenTable = document.createElement('table');
            hiddenTable.id = 'classicgyartas-table';
            hiddenTable.style.cssText = 'position: absolute; left: -9999px; visibility: hidden;';

            document.body.appendChild(hiddenTable);

            response.data.forEach((item, i) => {
              var newRow = hiddenTable.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);
              var newCell_6 = newRow.insertCell(5);
              var newCell_7 = newRow.insertCell(6);
              var newCell_8 = newRow.insertCell(7);
              var newCell_9 = newRow.insertCell(8);
              var newCell_10 = newRow.insertCell(9);
              var newCell_11 = newRow.insertCell(10);
              var newCell_12 = newRow.insertCell(11);
              var newCell_13 = newRow.insertCell(12);
              var newCell_14 = newRow.insertCell(13);
              var newCell_15 = newRow.insertCell(14);
              var newCell_16 = newRow.insertCell(15);
              var newCell_17 = newRow.insertCell(16);
              var newCell_18 = newRow.insertCell(17);
              var newCell_19 = newRow.insertCell(18);
              var newCell_20 = newRow.insertCell(19);
              var newCell_21 = newRow.insertCell(20);
              var newCell_22 = newRow.insertCell(21);
              var newCell_23 = newRow.insertCell(22);
              var newCell_24 = newRow.insertCell(23);
              var newCell_25 = newRow.insertCell(24);
              var newCell_26 = newRow.insertCell(25);
              var newCell_27 = newRow.insertCell(26);
              var newCell_28 = newRow.insertCell(27);
              var newCell_29 = newRow.insertCell(28);
              var newCell_30 = newRow.insertCell(29);
              var newCell_31 = newRow.insertCell(30);
              var newCell_32 = newRow.insertCell(31);

              newCell_1.innerHTML = item.item_id;
              newCell_2.innerHTML = item.db_start;
              newCell_3.innerHTML = item.date_start;
              newCell_4.innerHTML = item.date_prep;
              newCell_5.innerHTML = item.date_prepend;
              newCell_6.innerHTML = item.remain_r;
              newCell_7.innerHTML = item.remain_l;
              newCell_8.innerHTML = item.ordered;
              newCell_9.innerHTML = item.tablesize_x;
              newCell_10.innerHTML = item.tablesize_y;
              newCell_11.innerHTML = item.db_table;
              newCell_12.innerHTML = item.date_cut;
              newCell_13.innerHTML = item.date_cutend;
              newCell_14.innerHTML = item.db_cut_r;
              newCell_15.innerHTML = item.db_cut_l;
              newCell_16.innerHTML = item.date_press;
              newCell_17.innerHTML = item.date_pressend;
              newCell_18.innerHTML = item.db_press_r;
              newCell_19.innerHTML = item.db_press_l;
              newCell_20.innerHTML = item.press_machine;
              newCell_21.innerHTML = item.date_process;
              newCell_22.innerHTML = item.date_processend;
              newCell_23.innerHTML = item.db_process_r;
              newCell_24.innerHTML = item.db_process_l;
              newCell_25.innerHTML = item.process_mode;
              newCell_26.innerHTML = item.date_clean;
              newCell_27.innerHTML = item.date_cleanend;
              newCell_28.innerHTML = item.db_clean_r;
              newCell_29.innerHTML = item.db_clean_l;
              newCell_30.innerHTML = item.date_warehouseend;
              newCell_31.innerHTML = item.db_revenue_bulk_r;
              newCell_32.innerHTML = item.db_revenue_bulk_l;
            });

            exportCSV('hidden', 'Classic gyártás', 'classicgyartas');
            document.getElementById('classicProduction').classList.remove('loading');

          } else {
            GenerateAlerts("error", response.result);
          }
        }, function() {
          GenerateAlerts("error", "Hálózati hiba!");
        });
      } else if (type == "sporty") {
        document.getElementById('sportyProduction').classList.add('loading');
        const body = 'func=ExportGenerator&type=sporty&from_date=' + from_date + '&to_date=' + to_date + '&item_id=' + encodeURIComponent(get_item_id).replace(/%20/g, '+');
        get_POST_information("monthlystat.php", body, function(text) {
          let response = JSON.parse(text);
          if (response.result == "ok") {
            const hiddenTable = document.createElement('table');
            hiddenTable.id = 'sportygyartas-table';
            hiddenTable.style.cssText = 'position: absolute; left: -9999px; visibility: hidden;';

            document.body.appendChild(hiddenTable);

            response.data.forEach((item, i) => {
              var newRow = hiddenTable.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);
              var newCell_6 = newRow.insertCell(5);
              var newCell_7 = newRow.insertCell(6);
              var newCell_8 = newRow.insertCell(7);
              var newCell_9 = newRow.insertCell(8);
              var newCell_10 = newRow.insertCell(9);
              var newCell_11 = newRow.insertCell(10);
              var newCell_12 = newRow.insertCell(11);
              var newCell_13 = newRow.insertCell(12);
              var newCell_14 = newRow.insertCell(13);
              var newCell_15 = newRow.insertCell(14);
              var newCell_16 = newRow.insertCell(15);
              var newCell_17 = newRow.insertCell(16);
              var newCell_18 = newRow.insertCell(17);
              var newCell_19 = newRow.insertCell(18);
              var newCell_20 = newRow.insertCell(19);

              newCell_1.innerHTML = item.item_id;
              newCell_2.innerHTML = item.db_start;
              newCell_3.innerHTML = item.date_start;
              newCell_4.innerHTML = item.remain_r;
              newCell_5.innerHTML = item.remain_l;
              newCell_6.innerHTML = item.ordered;
              newCell_7.innerHTML = item.tablesize_x;
              newCell_8.innerHTML = item.tablesize_y;
              newCell_9.innerHTML = item.db_table;
              newCell_10.innerHTML = item.date_cut;
              newCell_11.innerHTML = item.date_cutend;
              newCell_12.innerHTML = item.db_cut_r;
              newCell_13.innerHTML = item.db_cut_l;
              newCell_14.innerHTML = item.date_press;
              newCell_15.innerHTML = item.date_pressend;
              newCell_16.innerHTML = item.db_press_r;
              newCell_17.innerHTML = item.db_press_l;
              newCell_18.innerHTML = item.date_warehouseend;
              newCell_19.innerHTML = item.db_revenue_bulk_r;
              newCell_20.innerHTML = item.db_revenue_bulk_l;
            });

            exportCSV('hidden', 'Sporty gyártás', 'sportygyartas');
            document.getElementById('sportyProduction').classList.remove('loading');

          } else {
            GenerateAlerts("error", response.result);
          }
        }, function() {
          GenerateAlerts("error", "Hálózati hiba!");
        });
      } else if (type == "injmold") {
        document.getElementById('injmoldProduction').classList.add('loading');
        const body = 'func=ExportGenerator&type=injmold&from_date=' + from_date + '&to_date=' + to_date + '&item_id=' + encodeURIComponent(get_item_id).replace(/%20/g, '+');
        get_POST_information("monthlystat.php", body, function(text) {
          let response = JSON.parse(text);
          if (response.result == "ok") {
            const hiddenTable = document.createElement('table');
            hiddenTable.id = 'injmoldgyartas-table';
            hiddenTable.style.cssText = 'position: absolute; left: -9999px; visibility: hidden;';

            document.body.appendChild(hiddenTable);

            response.data.forEach((item, i) => {
              var newRow = hiddenTable.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);
              var newCell_6 = newRow.insertCell(5);
              var newCell_7 = newRow.insertCell(6);
              var newCell_8 = newRow.insertCell(7);
              var newCell_9 = newRow.insertCell(8);
              var newCell_10 = newRow.insertCell(9);
              var newCell_11 = newRow.insertCell(10);
              var newCell_12 = newRow.insertCell(11);
              var newCell_13 = newRow.insertCell(12);
              var newCell_14 = newRow.insertCell(13);
              var newCell_15 = newRow.insertCell(14);
              var newCell_16 = newRow.insertCell(15);
              var newCell_17 = newRow.insertCell(16);
              var newCell_18 = newRow.insertCell(17);
              var newCell_19 = newRow.insertCell(18);
              var newCell_20 = newRow.insertCell(19);
              var newCell_21 = newRow.insertCell(20);

              newCell_1.innerHTML = item.item_id;
              newCell_2.innerHTML = item.db_start;
              newCell_3.innerHTML = item.date_start;
              newCell_4.innerHTML = item.date_prep;
              newCell_5.innerHTML = item.date_prepend;
              newCell_6.innerHTML = item.ordered;
              newCell_7.innerHTML = item.db_granules;
              newCell_8.innerHTML = item.date_process;
              newCell_9.innerHTML = item.date_processend;
              newCell_10.innerHTML = item.db_process_r;
              newCell_11.innerHTML = item.db_process_l;
              newCell_12.innerHTML = item.db_granules_used;
              newCell_13.innerHTML = item.kwh_start;
              newCell_14.innerHTML = item.kwh_stop;
              newCell_15.innerHTML = item.date_clean;
              newCell_16.innerHTML = item.date_cleanend;
              newCell_17.innerHTML = item.db_clean_r;
              newCell_18.innerHTML = item.db_clean_l;
              newCell_19.innerHTML = item.date_warehouseend;
              newCell_20.innerHTML = item.db_revenue_bulk_r;
              newCell_21.innerHTML = item.db_revenue_bulk_l;
            });

            exportCSV('hidden', 'Fröccsöntött gyártás', 'injmoldgyartas');
            document.getElementById('injmoldProduction').classList.remove('loading');

          } else {
            GenerateAlerts("error", response.result);
          }
        }, function() {
          GenerateAlerts("error", "Hálózati hiba!");
        });
      } else if (type == "boxing") {
        document.querySelectorAll('.boxingProduction').forEach(el => {el.classList.add('loading');});
        const body = 'func=ExportGenerator&type=boxing&from_date=' + from_date + '&to_date=' + to_date + '&item_id=' + encodeURIComponent(get_item_id).replace(/%20/g, '+');
        get_POST_information("monthlystat.php", body, function(text) {
          let response = JSON.parse(text);
          if (response.result == "ok") {
            const hiddenTable = document.createElement('table');
            hiddenTable.id = 'boxing-table';
            hiddenTable.style.cssText = 'position: absolute; left: -9999px; visibility: hidden;';

            document.body.appendChild(hiddenTable);

            response.data.forEach((item, i) => {
              var newRow = hiddenTable.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 = item.item_id;
              newCell_2.innerHTML = item.db_start;
              newCell_3.innerHTML = item.date_start;
              newCell_4.innerHTML = item.date_warehouseend;
              newCell_5.innerHTML = item.db_revenue;

            });

            exportCSV('hidden', 'Dobozolás', 'boxing');
            document.querySelectorAll('.boxingProduction').forEach(el => {el.classList.remove('loading');});

          } else {
            GenerateAlerts("error", response.result);
          }
        }, function() {
          GenerateAlerts("error", "Hálózati hiba!");
        });
      } else if (type == "orders") {
        document.querySelectorAll('.ordersStat').forEach(el => {el.classList.add('loading');});
        const body = 'func=ExportGenerator&type=orders&from_date=' + from_date + '&to_date=' + to_date + '&item_id=' + encodeURIComponent(get_item_id).replace(/%20/g, '+');
        get_POST_information("monthlystat.php", body, function(text) {
          let response = JSON.parse(text);
          if (response.result == "ok") {
            const hiddenTable = document.createElement('table');
            hiddenTable.id = 'orders-table';
            hiddenTable.style.cssText = 'position: absolute; left: -9999px; visibility: hidden;';

            document.body.appendChild(hiddenTable);

            response.data.forEach((item, i) => {
              var newRow = hiddenTable.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);
              var newCell_6 = newRow.insertCell(5);
              var newCell_7 = newRow.insertCell(6);
              var newCell_8 = newRow.insertCell(7);
              var newCell_9 = newRow.insertCell(8);
              var newCell_10 = newRow.insertCell(9);
              var newCell_11 = newRow.insertCell(10);
              var newCell_12 = newRow.insertCell(11);
              var newCell_13 = newRow.insertCell(12);
              var newCell_14 = newRow.insertCell(13);
              var newCell_15 = newRow.insertCell(14);
              var newCell_16 = newRow.insertCell(15);

              newCell_1.innerHTML = item.item_id;
              newCell_2.innerHTML = item.amount;
              newCell_3.innerHTML = item.reason;
              newCell_4.innerHTML = item.date_create;
              newCell_5.innerHTML = item.taken_out;
              newCell_6.innerHTML = item.order_id;
              newCell_7.innerHTML = item.order_name;
              newCell_8.innerHTML = item.order_mail;
              newCell_9.innerHTML = item.customer_type;
              newCell_10.innerHTML = item.receipt_method;
              newCell_11.innerHTML = item.note;
              newCell_12.innerHTML = item.primary_source;
              newCell_13.innerHTML = item.amount_type;
              newCell_14.innerHTML = item.primary_warehouse;
              newCell_15.innerHTML = item.date_end;
              newCell_16.innerHTML = item.is_deleted;

            });

            exportCSV('hidden', 'Rendelések', 'orders');
            document.querySelectorAll('.ordersStat').forEach(el => {el.classList.remove('loading');});

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

    function clearSearch() {
      document.getElementById('filter-item_id').value = '';
      showSummaryView();
    }
    function exportCSV(type, name = null, tableid = null) {
      if (type == "selejt") {
        const table = document.getElementById('selejt-table');
      	const workbook = XLSX.utils.table_to_book(table, {sheet: "Selejt", raw: true});

        workbook.Props = {
          Author: "Szaturnusz",
          Title: "Selejt jelentés",
          Subject: from_date + "-tól " + to_date + "-ig",
          Company: "Szatuna Kft."
        };

      	XLSX.writeFile(workbook, 'selejt_export.xlsx');
      } else if (type == "visszaru") {
        const table = document.getElementById('visszaru-table');
      	const workbook = XLSX.utils.table_to_book(table, {sheet: "Visszárú", raw: true});

        workbook.Props = {
          Author: "Szaturnusz",
          Title: "Visszárú jelentés",
          Subject: from_date + "-tól " + to_date + "-ig",
          Company: "Szatuna Kft."
        };

      	XLSX.writeFile(workbook, 'visszaru_export.xlsx');
      } else if (type == "garancia") {
        const table = document.getElementById('garancia-table');
      	const workbook = XLSX.utils.table_to_book(table, {sheet: "Garancia", raw: true});

        workbook.Props = {
          Author: "Szaturnusz",
          Title: "Garancia jelentés",
          Subject: from_date + "-tól " + to_date + "-ig",
          Company: "Szatuna Kft."
        };

      	XLSX.writeFile(workbook, 'garancia_export.xlsx');
      } else if (type == "hidden") {
        const table = document.getElementById(tableid + '-table');
      	const workbook = XLSX.utils.table_to_book(table, {sheet: name, raw: true});

        workbook.Props = {
          Author: "Szaturnusz",
          Title: name + " jelentés",
          Subject: from_date + "-tól " + to_date + "-ig",
          Company: "Szatuna Kft."
        };

      	XLSX.writeFile(workbook, tableid + '_export.xlsx');

        const tableToRemove = document.getElementById(tableid + '-table');
        if (tableToRemove) {
          document.body.removeChild(tableToRemove);
        }
      }
    }

    function OpenSettings() {
      Loading();
      openwin();
      wintitle.innerHTML = "Beállítások";
      winapp.innerHTML = '<div id="errorDIV"></div>';
      const body = 'func=OpenSettings';
      get_POST_information("monthlystat.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;">Plexi ára: <span style="opacity: 0.5; font-size: 12px; font-weight: normal;">Euro/m<sup>2</sup></span></p>
              <input value="${response.plexi_price}" defaultValue="${response.plexi_price}" onblur="if(this.value !== this.defaultValue) { SaveSettings(); this.defaultValue = this.value; }" type="number" id="plexi_price" min="0" step="0.01" pattern="[0-9]+([,.][0-9]{1,2})?" placeholder="Plexi ára..." 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;">Classic és Sportynál használt plexitábla darab ára</p>
            </div>
          </div>`;

          winapp.innerHTML += `<div style="margin-bottom: 15px; height: 87px;">
            <div style="display: inline; float: left;">
              <p style="font-weight: bold;">Granulátum ára: <span style="opacity: 0.5; font-size: 12px; font-weight: normal;">Euro/kg</span></p>
              <input value="${response.granules_price}" defaultValue="${response.granules_price}" onblur="if(this.value !== this.defaultValue) { SaveSettings(); this.defaultValue = this.value; }" type="number" id="granules_price" min="0" step="0.01" pattern="[0-9]+([,.][0-9]{1,2})?" placeholder="Granulátum ára..." 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;">Fröccsöntésnél használt granulátom kg ára</p>
            </div>
          </div>`;

          winapp.innerHTML += `<div style="margin-bottom: 15px; height: 87px;">
            <div style="display: inline; float: left;">
              <p style="font-weight: bold;">kWh ár: <span style="opacity: 0.5; font-size: 12px; font-weight: normal;">Ft/kWh</span></p>
              <input value="${response.kwh_price}" defaultValue="${response.kwh_price}" onblur="if(this.value !== this.defaultValue) { SaveSettings(); this.defaultValue = this.value; }" type="number" id="kwh_price" min="0" step="0.01" pattern="[0-9]+([,.][0-9]{1,2})?" placeholder="kWh ár..." 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;">Fröccsöntésnél használt kWh ára</p>
            </div>
          </div>`;

          PriceList['plexi_price'] = parseFloat(response.plexi_price);
          PriceList['granules_price'] = parseFloat(response.granules_price);
          PriceList['kwh_price'] = parseFloat(response.kwh_price);

        } 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 plexi_price = document.getElementById("plexi_price").value;
      var granules_price = document.getElementById("granules_price").value;
      var kwh_price = document.getElementById("kwh_price").value;

      PriceList['plexi_price'] = parseFloat(plexi_price);
      PriceList['granules_price'] = parseFloat(granules_price);
      PriceList['kwh_price'] = parseFloat(kwh_price);

      const body = 'func=SaveSettings&plexi_price=' + encodeURIComponent(plexi_price).replace(/%20/g, '+')
                    + '&granules_price=' + encodeURIComponent(granules_price).replace(/%20/g, '+')
                    + '&kwh_price=' + encodeURIComponent(kwh_price).replace(/%20/g, '+');

      get_POST_information("monthlystat.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!");
      });


    }

    loadData();

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