<?php

if (!isset($baseDir)) {
  $baseDir = $_SERVER['DOCUMENT_ROOT'];
}

require $baseDir . '/../scripts/db/db-verbindung-script-guest.php';

require $baseDir . '/../scripts/db/db-functions.php';
require $baseDir . '/../scripts/db/db-tables.php';

require_once $baseDir . '/../scripts/session_functions.php';

$riegeneinteilung_public = db_get_variable($guest, $db_tabelle_var, ['riegeneinteilungPublic']) ?? 0;

if (!$riegeneinteilung_public) {
  ini_wkvs_session(false);
  check_user_permission('wk_leitung', false, true);
}


$allGeraete = db_select($guest, $db_tabelle_disziplinen, "name, start_index, id", "", [], "start_index ASC");
$allAbt = db_select($guest, $db_tabelle_gruppen, "name, id, order_index", "", [], "order_index ASC");

$zeitplanTypes = db_select($guest, $db_tabelle_zeitplan_types, '*', '', [], '`display_index` ASC');

$all_zeiten = db_select($guest, $db_tabelle_gruppen_zeiten, '*');

$indexed_zeitplanTypes = array_column($zeitplanTypes, null, 'id');

$indexed_all_zeiten = [];

foreach ($all_zeiten as $zeit) {
  $indexed_all_zeiten[$zeit['abt_id']][] = $zeit;
}

$stmt = $guest->prepare("SELECT
    t.id,
    t.name,
    t.vorname,
    t.programm,
    p.id AS programm_id,
    t.verein,
    ta.turnerin_index AS start_index,
    a.name AS abteilung,
    g.name AS geraet
FROM $db_tabelle_teilnehmende t
LEFT JOIN $db_tabelle_teilnehmende_gruppen ta ON ta.turnerin_id = t.id
LEFT JOIN $db_tabelle_gruppen a ON a.id = ta.abteilung_id
LEFT JOIN $db_tabelle_disziplinen g ON g.id = ta.geraet_id
LEFT JOIN $db_tabelle_kategorien p ON p.programm = t.programm
GROUP BY t.id
ORDER BY ta.turnerin_index ASC;
");

$stmt->execute();


$result = $stmt->get_result();
$allTurnerinnen = $result->fetch_all(MYSQLI_ASSOC);

$grouped = [];

$alleVereine = array_unique(array_column($allTurnerinnen, 'verein'));

foreach ($allTurnerinnen as $entry) {
  if ($entry['abteilung'] == '') {
    $grouped['null']['null'][] = $entry;
  } else {
    $grouped[$entry['abteilung']][$entry['geraet']][] = $entry;
  }
}

$countAbt = count($allAbt);

$guest->close();

?>

<!DOCTYPE html>
<html lang="de">

<head>
  <meta charset="utf-8">
  <title>Riegeneinteilung</title>
  <link rel="icon" type="png" href="/intern/img/icon.png">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="/css/riegeneinteilung.css">
  <link href="/files/fonts/fonts.css" rel="stylesheet">
  <script src="/intern/js/jquery/jquery-3.7.1.min.js"></script>
</head>

<body>

  <div class="bgSection">
    <?php

    foreach ($allAbt as $abt):

      $abtName = $abt['name'];
      $abtId = $abt['id'];
      $abtIndex = $abt['order_index'];

      $max_button = $countAbt === intval($abtIndex) ? "disabled" : "";
      $min_button = 1 === intval($abtIndex) ? "disabled" : "";

      ?>

      <div class="singleAbtDiv" style="display:flex; flex-direction:column;">
        <div class="stickyDivHeader">
          <div class="headerAbt">
            <h2><b>Abteilung:</b> <?= htmlspecialchars($abtName) ?></h2>
          </div>
          <div class="subHeaderAbt">
            <?php if (isset($indexed_all_zeiten[$abtId])):
              $zeiten_entry = $indexed_all_zeiten[$abtId];
              foreach ($zeiten_entry as $se):

                if (!isset($indexed_zeitplanTypes[$se['zeitplan_id']]))
                  continue;

                $zeitplan_type = $indexed_zeitplanTypes[$se['zeitplan_id']];
                ?>
                <span class="timeSpan">
                  <?= $zeitplan_type['name'] ?> ab <?= date('H:i', strtotime($se['start_time'])) ?? '' ?>
                  <?php if (intval($zeitplan_type['has_endtime']) === 1): ?>
                    bis <?= date('H:i', strtotime($se['end_time'])) ?? '' ?>
                  <?php endif; ?>
                </span>
              <?php endforeach;
            endif; ?>
          </div>
        </div>
        <div class="allGeraeteDiv">



          <?php foreach ($allGeraete as $geraet):

            $geraetName = $geraet['name'];
            $geraetId = $geraet['id'];

            $entries = $grouped[$abtName][$geraetName] ?? []; ?>

            <table class="geraet-table" data-abteilung-id="<?= (int) $abtId ?>" data-geraet-id="<?= (int) $geraetId ?>">

              <thead>
                <tr>
                  <th>
                    Gerät: <?= htmlspecialchars($geraetName) ?>
                    <i><span><?= count($entries) ?></span></i>
                  </th>
                </tr>
              </thead>

              <tbody>

                <?php foreach ($entries as $entry): ?>

                  <tr class="turnerin-row" data-id="<?= (int) $entry['id'] ?>"
                    data-verein="<?= htmlspecialchars($entry['verein']) ?>"
                    data-programm="<?= htmlspecialchars($entry['programm']) ?>"
                    data-programm-id="<?= (int) $entry['programm_id'] ?>">
                    <td>
                      <b> <?= htmlspecialchars($entry['verein']) ?></b>,<br>
                      <?= htmlspecialchars($entry['vorname']) ?>
                      <?= htmlspecialchars($entry['name']) ?>,
                      <?= htmlspecialchars($entry['programm']) ?>
                    </td>
                  </tr>

                <?php endforeach;

                $grouped[$abtName][$geraetName] = []; ?>

              </tbody>
            </table>
          <?php endforeach; ?>


        </div>
      </div>

    <?php endforeach; ?>
  </div>
  </div>
  </div>
  <div class="buttonsDiv">
    <button id="groupByVereinProgramm">
      Vereine gruppieren
    </button>
    <button id="ungroup">
      Gruppierung aufheben
    </button>
    <select id="filterVerein">
      <option value="">Alle Vereine</option>
      <?php foreach ($alleVereine as $verein): ?>
        <option value="<?= htmlspecialchars($verein) ?>"><?= htmlspecialchars($verein) ?></option>
      <?php endforeach; ?>
    </select>
  </div>
  <script>
    $(function () {

      $(".turnerin-row").each(function () {
        $(this).data("original-table", $(this).closest(".geraet-table"));
      });



      const vereinColorMap = {};
      let nextColorIndex = 1;
      let filteredVerein = "";

      function getColorForVerein(verein) {
        if (!vereinColorMap[verein]) {
          vereinColorMap[verein] = colors[nextColorIndex % Object.keys(colors).length];
          nextColorIndex++;
        }
        return vereinColorMap[verein];
      }


      $(".turnerin-row").each(function () {
        let color = getColorForVerein($(this).data("verein"));

        $(this).css({
          background: color.background,
          color: color.foreground
        });
      });

      function groupByVereinProgramm() {
        $(".geraet-table tbody").each(function () {
          const tbody = $(this);
          const groups = {};
          let diffCounter = 0;
          let lastVerein = null;
          let lastProgramm = null;

          tbody.find(".turnerin-row").each(function () {
            const row = $(this);

            if (lastVerein !== row.data("verein") || lastProgramm !== row.data("programm")) {
              diffCounter++;
              lastVerein = row.data("verein");
              lastProgramm = row.data("programm");
            }

            if (!groups[diffCounter]) {
              groups[diffCounter] = [];
            }

            if (row.data("payed") === 0) {
              groups[diffCounter]['notPayed'] = true;
            }

            groups[diffCounter].push(row);
          });

          tbody.empty();

          Object.keys(groups).forEach(function (key) {
            const rows = groups[key];
            const verein = rows[0].data("verein");
            const programm = rows[0].data("programm");
            const programmId = rows[0].data("programm-id");

            const color = getColorForVerein(verein);

            const nichtbezahlt_string = rows['notPayed'] ? ' <span class="nichtBezahlt">*</span>' : '';

            const filteredClass = (filteredVerein === "" || verein === filteredVerein) ? "" : "filtered-out filtered-out-border"

            const groupRow = $(`
          <div class="group-row" data-verein="${verein}" data-programm="${programm}" data-programm-id="${programmId}">
            <td>
              <div class="group-header ${filteredClass}"
                  style="
                    background:${color.background};
                    color:${color.foreground};
                    border: 1px solid ${color.borderTop};
                  ">
                <span><b>${verein}${nichtbezahlt_string}</b><br>${programm}</span><span>(${rows.length})</span>
              </div>
              <table class="group-inner">
                <tbody></tbody>
              </table>
            </td>
          </div>
        `);

            rows.forEach(r => {
              groupRow.find(".group-inner tbody").append(r);
            });

            tbody.append(groupRow);
          });
        });
      }

      //groupByVereinProgramm();

      function ungroup() {

        $(".geraet-table tbody").each(function () {
          const tbody = $(this);

          tbody.find(".group-row").each(function () {
            const group = $(this);
            group.find(".turnerin-row").appendTo(tbody);
            group.remove();
          });
        });
      }

      $("#groupByVereinProgramm").on("click", groupByVereinProgramm);
      $("#ungroup").on("click", ungroup);


      $("#filterVerein").on("change", function () {
        const selectedVerein = $(this).val();

        filteredVerein = selectedVerein;

        $(".turnerin-row").each(function () {
          const row = $(this);
          if (selectedVerein === "" || row.data("verein") === selectedVerein) {
            row.removeClass("filtered-out");
          } else {
            row.addClass("filtered-out");
          }
        });
        $(".group-row").each(function () {
          const row = $(this);
          if (selectedVerein === "" || row.data("verein") === selectedVerein) {
            row.find(".group-header").removeClass("filtered-out");
            row.find(".group-header").removeClass("filtered-out-border");
          } else {
            row.find(".group-header").addClass("filtered-out");
            row.find(".group-header").addClass("filtered-out-border");
          }
        });
      });

    });

    const colors = {
      "0": {
        "background": "rgba(172, 172, 172, 0.18)",
        "foreground": "#4b4b4bff",
        "borderTop": "#5a5a5aff"
      },
      "1": {
        "background": "rgba(59, 130, 246, 0.18)",
        "foreground": "#1e3a8a",
        "borderTop": "#1e3a8a"
      },
      "2": {
        "background": "rgba(20, 184, 166, 0.18)",
        "foreground": "#065f46",
        "borderTop": "#065f46"
      },
      "3": {
        "background": "rgba(34, 197, 94, 0.18)",
        "foreground": "#14532d",
        "borderTop": "#14532d"
      },
      "4": {
        "background": "rgba(163, 230, 53, 0.20)",
        "foreground": "#365314",
        "borderTop": "#365314"
      },
      "5": {
        "background": "rgba(245, 158, 11, 0.20)",
        "foreground": "#92400e",
        "borderTop": "#92400e"
      },
      "6": {
        "background": "rgba(249, 115, 22, 0.20)",
        "foreground": "#9a3412",
        "borderTop": "#9a3412"
      },
      "7": {
        "background": "rgba(244, 63, 94, 0.18)",
        "foreground": "#9f1239",
        "borderTop": "#9f1239"
      },
      "8": {
        "background": "rgba(236, 72, 153, 0.18)",
        "foreground": "#9d174d",
        "borderTop": "#9d174d"
      },
      "9": {
        "background": "rgba(168, 85, 247, 0.18)",
        "foreground": "#581c87",
        "borderTop": "#581c87"
      },
      "10": {
        "background": "rgba(99, 102, 241, 0.18)",
        "foreground": "#312e81",
        "borderTop": "#312e81"
      },
      "11": {
        "background": "rgba(100, 116, 139, 0.20)",
        "foreground": "#1e293b",
        "borderTop": "#1e293b"
      },
      "12": {
        "background": "rgba(6, 182, 212, 0.18)",
        "foreground": "#164e63",
        "borderTop": "#164e63"
      }
    };
  </script>

</body>

</html>