<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Cheaters.rip - Leaderboard</title>
    <link rel="icon" type="image/png" href="cheatersrip.png" />
    <link
      href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css"
      rel="stylesheet"
    />
    <script src="https://www.google.com/recaptcha/api.js"></script>
  </head>
  <body
    class="bg-gradient-to-b from-gray-900 to-black text-gray-200 min-h-screen flex flex-col relative"
  >
    <header class="p-4 sm:p-6 bg-gray-800 shadow-md">
      <div
        class="max-w-6xl mx-auto flex flex-col md:flex-row md:items-center md:justify-between"
      >
        <div class="mb-4 md:mb-0">
          <h1 class="text-2xl sm:text-3xl font-bold text-white">
            Cheaters.rip
          </h1>
          <p class="text-gray-300 text-sm mt-1">
            Exposing game cheaters for a fairer gaming experience.
          </p>
        </div>
        <div
          class="flex flex-col space-y-2 md:flex-row md:space-y-0 md:space-x-4 items-start md:items-center w-full md:w-auto"
        >
          <input
            type="text"
            id="searchInput"
            placeholder="Search Gamertag..."
            class="bg-gray-700 text-gray-200 px-3 py-2 rounded outline-none focus:ring-2 focus:ring-blue-500 transition text-sm"
          />
          <select
            id="filterGameType"
            class="bg-gray-700 text-gray-200 px-3 py-2 rounded outline-none focus:ring-2 focus:ring-blue-500 transition text-sm"
          >
            <option value="">All Game Types</option>
            <option value="zombies">Zombies</option>
            <option value="multiplayer">Multiplayer</option>
          </select>
          <select
            id="filterHackType"
            class="bg-gray-700 text-gray-200 px-3 py-2 rounded outline-none focus:ring-2 focus:ring-blue-500 transition text-sm"
          >
            <option value="">All Hack Types</option>
            <option value="infection">Infection Menu</option>
            <option value="gmode">GMode Class</option>
          </select>
          <button
            id="filterBtn"
            class="bg-blue-600 hover:bg-blue-700 text-white px-3 py-2 rounded transition text-sm"
          >
            Apply Filters
          </button>
          <button
            id="addCheaterBtn"
            class="bg-green-600 hover:bg-green-700 text-white px-3 py-2 rounded transition text-sm"
          >
            Add Cheater
          </button>
        </div>
      </div>
    </header>

    <main class="flex-grow py-8 px-4">
      <div class="max-w-6xl mx-auto">
        <div class="overflow-x-auto rounded shadow-lg">
          <table
            id="cheatersTable"
            class="w-full table-auto bg-gray-800 rounded"
          >
            <thead class="bg-gray-700">
              <tr>
                <th
                  class="px-4 py-3 cursor-pointer text-left font-medium text-gray-300 hover:text-white transition"
                  data-sort="gamertag"
                  title="Sort by Gamertag"
                >
                  Gamertag
                </th>
                <th
                  class="px-4 py-3 cursor-pointer text-left font-medium text-gray-300 hover:text-white transition"
                  data-sort="xuid"
                  title="Sort by XUID"
                >
                  XUID
                </th>
                <th
                  class="px-4 py-3 cursor-pointer text-left font-medium text-gray-300 hover:text-white transition"
                  data-sort="type_of_hack"
                  title="Sort by Hack Type"
                >
                  Type of Hack
                </th>
                <th
                  class="px-4 py-3 cursor-pointer text-left font-medium text-gray-300 hover:text-white transition"
                  data-sort="game_type"
                  title="Sort by Game Type"
                >
                  Game Type
                </th>
                <th
                  class="px-4 py-3 cursor-pointer text-left font-medium text-gray-300 hover:text-white transition"
                  data-sort="action_taken"
                  title="Sort by Action Taken"
                >
                  Action Taken
                </th>
                <th
                  class="px-4 py-3 cursor-pointer text-left font-medium text-gray-300 hover:text-white transition"
                  data-sort="date_added"
                  title="Sort by Date Added"
                >
                  Date Added
                </th>
              </tr>
            </thead>
            <tbody id="cheatersBody" class="divide-y divide-gray-700">
              <!-- Rows inserted by JS -->
            </tbody>
          </table>
        </div>
      </div>
    </main>

    <footer class="p-4 bg-gray-800 text-center text-gray-400 text-sm">
      &copy; 2024 Cheaters.rip. All rights reserved.
    </footer>

    <!-- Modal for Adding a Cheater -->
    <div
      id="addCheaterModal"
      class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden z-50"
    >
      <div class="bg-gray-800 rounded p-6 w-full max-w-md mx-2">
        <h2 class="text-xl font-bold mb-4 text-white">Add a Cheater</h2>
        <!-- Added inputmode and pattern for XUID -->
        <form id="addCheaterForm" class="space-y-4">
          <div>
            <label for="cheaterGamertag" class="block mb-1 text-gray-300">
              Gamertag
            </label>
            <input
              type="text"
              id="cheaterGamertag"
              name="gamertag"
              required
              class="w-full bg-gray-700 text-gray-200 px-3 py-2 rounded outline-none focus:ring-2 focus:ring-blue-500 transition"
            />
          </div>
          <div>
            <label for="cheaterXUID" class="block mb-1 text-gray-300">
              XUID (Numbers Only)
            </label>
            <input
              type="text"
              id="cheaterXUID"
              name="xuid"
              inputmode="numeric"
              pattern="^[0-9]+$"
              class="w-full bg-gray-700 text-gray-200 px-3 py-2 rounded outline-none focus:ring-2 focus:ring-blue-500 transition"
            />
            <p class="text-xs text-gray-400 mt-1">Please enter digits only.</p>
          </div>
          <div>
            <label for="cheaterHackType" class="block mb-1 text-gray-300">
              Type of Hack
            </label>
            <select
              id="cheaterHackType"
              name="type_of_hack"
              required
              class="w-full bg-gray-700 text-gray-200 px-3 py-2 rounded outline-none focus:ring-2 focus:ring-blue-500 transition"
            >
              <option value="">Select Hack Type</option>
              <option value="infection">Infection Menu</option>
              <option value="gmode">GMode Class</option>
            </select>
          </div>
          <div>
            <label for="cheaterGameType" class="block mb-1 text-gray-300">
              Game Type
            </label>
            <select
              id="cheaterGameType"
              name="game_type"
              required
              class="w-full bg-gray-700 text-gray-200 px-3 py-2 rounded outline-none focus:ring-2 focus:ring-blue-500 transition"
            >
              <option value="">Select Game Type</option>
              <option value="zombies">Zombies</option>
              <option value="multiplayer">Multiplayer</option>
            </select>
          </div>
          <div>
            <label for="cheaterActionTaken" class="block mb-1 text-gray-300">
              Action Taken
            </label>
            <select
              id="cheaterActionTaken"
              name="action_taken"
              required
              class="w-full bg-gray-700 text-gray-200 px-3 py-2 rounded outline-none focus:ring-2 focus:ring-blue-500 transition"
            >
              <option value="">Select Action</option>
              <option value="Deranked">Deranked</option>
              <option value="Clips">Clips Deleted/Spammed</option>
              <option value="Barracks Reset">Barracks Reset</option>
              <option value="Classes Removed">Classes Removed</option>
              <option value="all">Everything Listed</option>
            </select>
          </div>
          <div>
            <label for="captchaAnswer" class="block mb-1 text-gray-300">
              Solve:
              <span id="captchaQuestion" class="font-bold text-white"></span>
            </label>
            <input
              type="text"
              id="captchaAnswer"
              name="captchaAnswer"
              required
              class="w-full bg-gray-700 text-gray-200 px-3 py-2 rounded outline-none focus:ring-2 focus:ring-blue-500 transition"
              placeholder="Answer"
            />
          </div>
          <div class="flex space-x-4 mt-6">
            <button
              type="submit"
              class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded transition"
            >
              Submit
            </button>
            <button
              type="button"
              id="cancelAddCheaterBtn"
              class="bg-gray-600 hover:bg-gray-700 text-white px-4 py-2 rounded transition"
            >
              Cancel
            </button>
          </div>
        </form>
      </div>
    </div>

    <script src="app.js"></script>

    <script>
      function generateCaptcha() {
        const operations = [
          { operator: "+", fn: (a, b) => a + b },
          { operator: "-", fn: (a, b) => a - b },
          { operator: "*", fn: (a, b) => a * b },
          { operator: "/", fn: (a, b) => Math.floor(a / b) }
        ];

        // Generate random numbers
        const num1 = Math.floor(Math.random() * 20) + 1;
        const num2 = Math.floor(Math.random() * 15) + 1;
        const num3 = Math.floor(Math.random() * 10) + 1;

        const operation1 =
          operations[Math.floor(Math.random() * operations.length)];
        const operation2 =
          operations[Math.floor(Math.random() * operations.length)];

        const useParentheses = Math.random() > 0.5;
        const question = useParentheses
          ? `(${num1} ${operation1.operator} ${num2}) ${operation2.operator} ${num3}`
          : `${num1} ${operation1.operator} ${num2} ${operation2.operator} ${num3}`;

        const intermediateResult = operation1.fn(num1, num2);
        const answer = operation2.fn(intermediateResult, num3);

        return { question, answer };
      }

      let captcha;

      document.addEventListener("DOMContentLoaded", () => {
        const addCheaterBtn = document.getElementById("addCheaterBtn");
        const addCheaterModal = document.getElementById("addCheaterModal");
        const cancelAddCheaterBtn = document.getElementById(
          "cancelAddCheaterBtn"
        );
        const addCheaterForm = document.getElementById("addCheaterForm");
        const captchaQuestion = document.getElementById("captchaQuestion");
        const captchaAnswerInput = document.getElementById("captchaAnswer");

        // Ensure modal opens when button is clicked
        addCheaterBtn.addEventListener("click", () => {
          captcha = generateCaptcha();
          captchaQuestion.textContent = captcha.question;
          captchaAnswerInput.value = "";
          addCheaterModal.classList.remove("hidden");
        });

        cancelAddCheaterBtn.addEventListener("click", () => {
          addCheaterModal.classList.add("hidden");
        });

        addCheaterForm.addEventListener("submit", async (e) => {
          e.preventDefault();

          const userAnswer = parseInt(captchaAnswerInput.value, 10);
          if (isNaN(userAnswer) || userAnswer !== captcha.answer) {
            alert("CAPTCHA validation failed. Please try again.");
            return;
          }

          const formData = new FormData(addCheaterForm);
          let payload = Object.fromEntries(formData.entries());
          payload = sanitizePayload(payload);

          if (
            !payload.gamertag ||
            !payload.type_of_hack ||
            !payload.game_type ||
            !payload.action_taken
          ) {
            alert("Please fill in all required fields.");
            return;
          }

          if (payload.xuid && !/^[0-9]+$/.test(payload.xuid)) {
            alert("XUID must contain only numbers.");
            return;
          }

          try {
            const response = await fetch("https://cheaters.rip/api/cheaters", {
              method: "POST",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify(payload)
            });

            if (response.ok) {
              alert("Cheater added successfully!");
              addCheaterModal.classList.add("hidden");
              addCheaterForm.reset();
              fetchCheaters();
            } else {
              alert("Failed to add cheater. Please try again.");
            }
          } catch (error) {
            alert("Error adding cheater. Please check your connection.");
          }
        });
      });

      // Basic sanitization functions
      function sanitizeString(str) {
        const temp = document.createElement("div");
        temp.textContent = str;
        return temp.innerHTML.trim();
      }

      function sanitizePayload(payload) {
        for (const key in payload) {
          if (payload.hasOwnProperty(key)) {
            payload[key] = sanitizeString(payload[key]);
            if (key === "xuid") {
              payload[key] = payload[key].replace(/\D/g, "");
            }
          }
        }
        return payload;
      }
    </script>
  </body>
</html>
