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

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

if (isset($_POST["func"])) {
  if (htmlspecialchars($_POST["func"]) == "LoadClimAir") {

    $return_list = array();

    /* Normál elemek */
    $query = "SELECT item_id, name_in_db, car_type, car_brand, front_and_rear FROM pr_parameters WHERE category = 'ClimAir' and data_status = 1";
    if ($result = $conn->query($query)) {
      while ($c_climair = $result->fetch_assoc()) {
        $c_item_id = $c_climair['item_id'];

        $annual_query = mysqli_query($conn, "SELECT AVG(total_consumption) AS avg_total_consumption FROM statistics_annual WHERE item_id = '$c_item_id' AND year >= YEAR(CURDATE()) - 2");
        $annual_data = mysqli_fetch_assoc($annual_query);

        $avg_total_consumption = 0;
        $is_new = false;
        if ($annual_data != null && $annual_data['avg_total_consumption'] != null) {
          $avg_total_consumption = $annual_data['avg_total_consumption'];
        } else {
          $is_new = true;
        }

        if ($avg_total_consumption == 0) {
          $c_car_type = $c_climair['car_type'];
          $c_car_brand = $c_climair['car_brand'];
          $stmt = $conn->prepare("SELECT AVG(total_consumption) AS avg_total_consumption
                                  FROM statistics_annual sa
                                  WHERE sa.item_id IN (
                                      SELECT item_id
                                      FROM pr_parameters
                                      WHERE category = 'ClimAir'
                                        AND data_status = 1
                                        AND car_type = ?
                                        AND car_brand = ?
                                  )
                                  AND sa.year >= YEAR(CURDATE()) - 2");

          $stmt->bind_param("ss", $c_car_type, $c_car_brand);
          $stmt->execute();
          $annual_data_type = $stmt->get_result();
          while ($row = $annual_data_type->fetch_assoc()) {
            $avg_total_consumption = $row['avg_total_consumption'];
          }

        }

        $month_4_consumption = ($avg_total_consumption / 365) * (4 + 2) * 30; // Napi fogyás * 4 hónapos tervezés + 2 hónap beérkezési idő

        $daily_query = mysqli_query($conn, "SELECT under_sales FROM statistics_daily WHERE item_id = '$c_item_id'");
        $daily_data = mysqli_fetch_assoc($daily_query);

        if ($daily_data != null) {
          $month_4_consumption += $daily_data['under_sales'];
        }

        $set_items = splitSetitem_id($c_item_id);
        if ($set_items != null) {
          $return_list[] = [
            "item_id" => $set_items['item1'],
            "amount" => ceil($month_4_consumption),
            "name_in_db" => $c_climair['name_in_db'],
            "is_new" => $is_new
          ];
          $return_list[] = [
            "item_id" => $set_items['item2'],
            "amount" => ceil($month_4_consumption),
            "name_in_db" => $c_climair['name_in_db'],
            "is_new" => $is_new
          ];
        } else {
          $return_list[] = [
            "item_id" => $c_item_id,
            "amount" => ceil($month_4_consumption),
            "name_in_db" => $c_climair['name_in_db'],
            "is_new" => $is_new
          ];
        }
      }
    }

    /* Return előkészítése */
    $return_list = array_reduce($return_list, function($carry, $item) {
      $id = $item['item_id'];
      if (isset($carry[$id])) {
        $carry[$id]['amount'] += $item['amount'];
      } else {
        $carry[$id] = $item;
      }
      return $carry;
    }, []);
    $return_list = array_values($return_list);
    usort($return_list, function($a, $b) {
      if ($a['is_new'] != $b['is_new']) {
        return $b['is_new'] - $a['is_new'];
      }
      return $a['amount'] <=> $b['amount'];
    });
    echo json_encode(['result' => 'ok', 'return_list' => $return_list]);
  }

  exit();
}

?>
<!DOCTYPE html>
<html lang="hu" dir="ltr">
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="../css/panel.css">
    <script src="../js/feather-icons.js"></script>
    <title>Kezelőfelület</title>
  </head>
  <style>
    .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;
        }
    }
  </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">

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

      <!-- KATEGÓRIA GOMBOK -->
      <div class="category-tabs" style="grid-template-columns: repeat(1, 1fr);">
        <div class="category-tab active" onclick="switchCategory(this, 'climair')">
          <div class="category-tab-icon">
            <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM/rhtAAAACXBIWXMAAAsTAAALEwEAmpwYAAAF2UlEQVR4nO2WfUwTZxzH65ZtmVmyZW5LtizZYjLjHzMxkzs0c9whM+K4A4xrFgfcXQGZgEB56XOlWsr7GCAvFpG2zxVwQiuKicg0MJwbb2pm/GNbXGbMphvqfEHQTBCYPMtT09r2igJWXIy/5Js0z/N7ft/P3XO/p49C8aRHnCX9VR6KYZwkJsY36MrjGrK3CVCTFG0R2Q2mjNceC1SCyTA/3qoT4xp0Z1T12tuJTfrxjY1bUFJTDkrbk4c27tqCEnfrJwSr9nZcffZZwSpuVdYYXnrkYAaD4RleAkCwam9k7CsYK+yoQpttBsRBgFRWLdrRb0F1xyUHIB7Dc8Wd1ShrX9G4StL+4wBtUT77SOBioeat2AbtyRR77mhVjwlVfF+L4hqyHSBYWa1FyHTC6pC+vcw1jnMqu3ei6h4TSrXljqis2lNRZvC2X+FizNpFKqt4TX+wfKLuhOQwi62/B8dBgEq6jC7A7T0mj7m4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yTN5PgVzgVEM/UkxVbfA2TtskZxiwCa+YygmWa3fDVBs93e37PfAm8VQbNnAoKYtXcNGc39GsXRCDQL8O/lQRFLSJq5uCL4k5mddzONZTT74Uch7IAuivkgel1YVOgapk9KDFvoS6Fr2B+iw8O4otiw96lV7Bn8mSjmIsyJ4ZftGevHW4FyqDlTObkfKK/7ki3z0zs4x56xfgwmscOKuQq7et3Z87Z8dK2tfFoaaClETerIC3MHmBZpsqkjxu3qiDt2deQDZUuLmLCpIxsVcxnNaREDNw9XIdQLHbrevg1d3Ffs0ODBba7xW51G1JwafnVO4XwB9lcko858waHe8k3/P0A0hZ4CThVPAR82ngL6A/CkUY1+NoP76tSOjMcD+HXK2vimVKZyOtqVJL/yPzHxH9ZWbatLyxtEAAAAAElFTkSuQmCC" alt="drop-shipping">
          </div>
          <div class="category-tab-title">ClimAir rendelés</div>
          <div class="category-tab-desc">Generálja le a ClimAir rendeléshez szükséges excelt</div>
        </div>
      </div>

      <!-- ClimAir -->
      <div id="climair" class="cat-tab form-section active" style="position: relative;">
        <div class="load"></div>
        <div class="form-title">ClimAir rendelés</div>
        <div class="form-desc">Generálja le a ClimAir rendeléshez szükséges excelt</div>

        <a title="Excel export" style="position: absolute; right: 15px; top: 15px;"><i class="icon" onclick="exportCSV('climair');" style="width: 20px; height: 20px; opacity: 0.6;"><i data-feather="download" style="width: 20px; height:20px;"></i></i></a>

        <table id="climair-table">
          <thead>
            <tr>
              <th>Cikkszám</th>
              <th>Mennyiség <span><i class="icon" style="width: 12px; height: 12px; opacity: 0.8;"><i data-feather="edit-2" style="width: 12px; height:12px;"></i></i></span></th>
              <th>Terméknév</th>
            </tr>
          </thead>
          <tbody>
          </tbody>
        </table>

      </div>

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

    </div>
    <script src="../js/default.js" type="text/javascript"></script>
    <script src="../js/xlsx.full.min.js" type="text/javascript"></script>
    <script type="text/javascript">
      var ActiveCategory = "climair";
      function switchCategory(element, categoryId) {
        document.querySelectorAll('.category-tab').forEach(tab => tab.classList.remove('active'));
        element.classList.add('active');

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

        ActiveCategory = categoryId;
        InitCategorySpecificData();
      }
      feather.replace();

      function InitCategorySpecificData() {
        if (ActiveCategory == "climair") {
          LoadClimAir();
        }
      }
      InitCategorySpecificData();

      function LoadClimAir() {
        document.getElementById("climair").classList.add('loading');
        const body = 'func=LoadClimAir';
        get_POST_information("acquire.php", body, function(text) {
          Loading(false);
          document.getElementById("climair").classList.remove('loading');
          let response = JSON.parse(text);
          if (response.result == "ok") {

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

            response.return_list.forEach((item, i) => {
              var newRow = table.insertRow();
              var list_item_id = newRow.insertCell(0);
              var list_amount = newRow.insertCell(1);
              var list_name_in_db = newRow.insertCell(2);

              list_item_id.innerHTML = item.item_id;
              list_amount.innerHTML = item.amount;
              list_amount.setAttribute('contenteditable', 'true');
              list_name_in_db.innerHTML = item.name_in_db;

              if (item.is_new) {
                list_item_id.innerHTML += `<span style="margin-left: 10px; height: 20px; position: absolute; color: var(--panelcolor); font-size: 14px; font-weight: bold; margin-top: 3px; cursor: default;" title="Új termék">Új!</span>`;
              }

            });

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

      function exportCSV(type) {
        if (type == "climair") {
          const table = document.getElementById('climair-table').cloneNode(true);

          table.querySelectorAll('span').forEach(span => {
            span.replaceWith('');
          });

          const workbook = XLSX.utils.table_to_book(table, {sheet: "ClimAir", raw: true});

          workbook.Props = {
            Author: "Szaturnusz",
            Title: "ClimAir rendelés",
            Company: "Szatuna Kft."
          };

          XLSX.writeFile(workbook, 'climair_order.xlsx');
        }
      }
    </script>
  </body>
</html>
