<!DOCTYPE html>
<html lang="pl">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Logowanie i Panel Użytkownika</title>
  <style>
    /* Prosty reset */
    * {
      box-sizing: border-box;
      margin: 0;
      padding: 0;
    }

    body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
      background: linear-gradient(120deg, #f3f9ff, #ddefff);
      min-height: 100vh;
      display: flex;
      flex-direction: column;
      align-items: stretch;
      transition: background 0.3s ease, color 0.3s ease;
    }

    @keyframes fadeIn {
      from {
        opacity: 0;
        transform: translateY(15px);
      }
      to {
        opacity: 1;
        transform: translateY(0);
      }
    }
    footer {
      text-align: center;
      margin: 20px 0;
      font-size: 14px;
      color: #555;  /* Kolor tekstu w trybie jasnym */
      transition: color 0.3s ease;
    }

    /* W trybie ciemnym – uwzględnij klasę .dark-mode na <body> */
    body.dark-mode footer {
      color: #dfdff6; /* Jaśniejszy tekst na ciemnym tle */
    }
    /* ------- NAGŁÓWEK (HEADER) ------- */
    header {
      background-color: #72a6ff;
      color: #fff;
      padding: 10px 20px;
      display: flex;
      justify-content: flex-end; /* przycisk w prawym górnym rogu */
      align-items: center;
    }
    header button {
      background-color: #72a6ff;
      color: #fff;
      border: 1px solid #fff;
      border-radius: 8px;
      font-size: 14px;
      padding: 8px 16px;
      cursor: pointer;
      transition: background 0.3s, transform 0.2s;
    }
    header button:hover {
      background-color: #5e90e7;
      transform: scale(1.03);
    }

    /* ------- SEKCJA LOGOWANIA ------- */
    #loginSection, #registerSection {
      background-color: #ffffff;
      max-width: 400px;
      width: 90%;
      padding: 30px 20px;
      border-radius: 12px;
      box-shadow: 0 12px 24px rgba(0, 0, 0, 0.15);
      animation: fadeIn 0.6s ease;
      text-align: center;
      margin: 80px auto 20px auto; /* margines, by nie wchodzić na header */
      transition: background-color 0.3s ease, color 0.3s ease;
    }
    #loginSection h1, #registerSection h1 {
      margin-bottom: 20px;
      color: #333;
      transition: color 0.3s ease;
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
    }
    #usernameLogin, #adminPassword, #usernameRegister, #passwordRegister {
      display: block;
      width: 100%;
      padding: 12px;
      margin: 10px auto;
      border: 1px solid #ccc;
      border-radius: 8px;
      font-size: 16px;
      transition: border-color 0.3s;
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
    }
    #usernameLogin:focus, #adminPassword:focus,
    #usernameRegister:focus, #passwordRegister:focus {
      border-color: #72a6ff;
      outline: none;
    }
    #loginSection button, #registerSection button {
      padding: 14px 24px;
      border: none;
      border-radius: 8px;
      font-size: 16px;
      cursor: pointer;
      background: #72a6ff;
      color: #fff;
      font-weight: 600;
      letter-spacing: 1px;
      transition: background 0.3s, transform 0.2s;
      margin-top: 10px;
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
    }
    #loginSection button:hover, #registerSection button:hover {
      background: #5e90e7;
      transform: scale(1.02);
    }
    #loginError, #registerError {
      margin-top: 10px;
      color: red;
      font-weight: 500;
      transition: color 0.3s ease;
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
    }

    /* ------- PANEL ADMINISTRACYJNY ------- */
    #adminPanel, #userPanel {
      background-color: #ffffff;
      max-width: 1000px;
      width: 90%;
      padding: 30px;
      border-radius: 12px;
      box-shadow: 0 12px 24px rgba(0, 0, 0, 0.15);
      animation: fadeIn 0.6s ease;
      margin: 20px auto;
      transition: background-color 0.3s ease, color 0.3s ease;
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
    }
    #adminPanel h1, #userPanel h1 {
      text-align: center;
      margin-bottom: 20px;
      color: #333;
      transition: color 0.3s ease;
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
    }

    .buttons-container {
      display: flex;
      justify-content: center;
      margin-bottom: 20px;
      gap: 10px;
    }

    /* Przykładowe przyciski w panelu */
    .btn {
      padding: 10px 16px;
      border: none;
      border-radius: 8px;
      background-color: #72a6ff;
      color: #fff;
      font-weight: 600;
      cursor: pointer;
      transition: background 0.3s, transform 0.2s;
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
    }
    .btn:hover {
      background-color: #5e90e7;
      transform: scale(1.02);
    }

    table {
      width: 100%;
      border-collapse: collapse;
      margin-top: 20px;
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
    }
    thead {
      background-color: #72a6ff;
      color: #fff;
    }
    th, td {
      padding: 12px;
      text-align: left;
      border-bottom: 1px solid #ddd;
      transition: background-color 0.3s ease, color 0.3s ease;
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
    }
    th {
      font-weight: 600;
    }
    tr:last-child td {
      border-bottom: none;
    }
    #errorMessage, #userErrorMessage {
      text-align: center;
      color: red;
      margin-top: 20px;
      font-weight: 500;
      transition: color 0.3s ease;
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
    }

    /* ------- TRYB CIEMNY ------- */
    body.dark-mode {
      background: linear-gradient(120deg, #2f2a51, #34324a);
      color: #eee;
    }

    /* Header w trybie ciemnym */
    body.dark-mode header {
      background-color: #4b2e87;
    }
    body.dark-mode header button {
      background-color: #4b2e87;
      border: 1px solid #cfc0f5;
    }
    body.dark-mode header button:hover {
      background-color: #633ead;
    }

    /* Sekcja logowania w trybie ciemnym */
    body.dark-mode #loginSection, body.dark-mode #registerSection {
      background-color: #3c336a;
      color: #dfdff6;
    }
    body.dark-mode #loginSection h1, body.dark-mode #registerSection h1 {
      color: #c4c4e4;
    }
    body.dark-mode #usernameLogin, body.dark-mode #adminPassword,
    body.dark-mode #usernameRegister, body.dark-mode #passwordRegister {
      background-color: #4b4485;
      color: #dfdff6;
      border-color: #746fb4;
    }
    body.dark-mode #usernameLogin:focus, body.dark-mode #adminPassword:focus,
    body.dark-mode #usernameRegister:focus, body.dark-mode #passwordRegister:focus {
      border-color: #a099d9;
    }
    body.dark-mode #loginSection button, body.dark-mode #registerSection button {
      background-color: #4b2e87;
    }
    body.dark-mode #loginSection button:hover, body.dark-mode #registerSection button:hover {
      background-color: #633ead;
    }
    body.dark-mode #loginError, body.dark-mode #registerError {
      color: #ff9e9e;
    }

    /* Panel admina w trybie ciemnym */
    body.dark-mode #adminPanel, body.dark-mode #userPanel {
      background-color: #3c336a;
      color: #dfdff6;
    }
    body.dark-mode #adminPanel h1, body.dark-mode #userPanel h1 {
      color: #bfbfe1;
    }
    body.dark-mode thead {
      background-color: #4b2e87;
    }
    body.dark-mode th, 
    body.dark-mode td {
      border-bottom: 1px solid #5f5993;
    }
    body.dark-mode tr:nth-child(odd) td {
      background-color: #48406f;
    }
    body.dark-mode tr:nth-child(even) td {
      background-color: #423a67;
    }
    body.dark-mode #errorMessage, body.dark-mode #userErrorMessage {
      color: #ff9e9e;
    }
    body.dark-mode .btn {
      background-color: #4b2e87;
    }
    body.dark-mode .btn:hover {
      background-color: #633ead;
    }

    /* ------- FORMULARZ DODAWANIA REZERWACJI ------- */
    #addAppointmentForm {
      margin-top: 20px;
      padding: 20px;
      background-color: #f9f9f9;
      border-radius: 8px;
      box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
      display: none; /* Ukryty domyślnie */
      transition: background-color 0.3s ease, color 0.3s ease;
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
    }
    #addAppointmentForm h2 {
      margin-bottom: 15px;
      color: #333;
      text-align: center;
      transition: color 0.3s ease;
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
    }
    #addAppointmentForm label {
      display: block;
      margin-bottom: 5px;
      color: #444;
      transition: color 0.3s ease;
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
    }
    #addAppointmentForm input,
    #addAppointmentForm select {
      width: 100%;
      padding: 10px;
      margin-bottom: 15px;
      border: 1px solid #ccc;
      border-radius: 6px;
      font-size: 14px;
      transition: border-color 0.3s, background-color 0.3s, color 0.3s;
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
    }
    #addAppointmentForm input:focus,
    #addAppointmentForm select:focus {
      border-color: #72a6ff;
      outline: none;
    }
    #addAppointmentForm button {
      padding: 12px 20px;
      border: none;
      border-radius: 6px;
      background-color: #4caf50;
      color: #fff;
      font-size: 16px;
      cursor: pointer;
      transition: background-color 0.3s, transform 0.2s;
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
    }
    #addAppointmentForm button:hover {
      background-color: #45a049;
      transform: scale(1.02);
    }
    body.dark-mode #addAppointmentForm {
      background-color: #48406f;
      color: #dfdff6;
    }
    body.dark-mode #addAppointmentForm h2 {
      color: #bfbfe1;
    }
    body.dark-mode #addAppointmentForm label {
      color: #dfdff6;
    }
    body.dark-mode #addAppointmentForm input,
    body.dark-mode #addAppointmentForm select {
      background-color: #4b4485;
      color: #dfdff6;
      border-color: #5f5993;
    }
    body.dark-mode #addAppointmentForm input:focus,
    body.dark-mode #addAppointmentForm select:focus {
      border-color: #a099d9;
    }
    body.dark-mode #addAppointmentForm button {
      background-color: #4b2e87;
    }
    body.dark-mode #addAppointmentForm button:hover {
      background-color: #633ead;
    }
  </style>
</head>
<body>
  <!-- Header -->
  <header>
    <button id="toggleDarkMode">Tryb ciemny</button>
  </header>

  <!-- Formularz logowania -->
  <div id="loginSection">
    <h1>Logowanie</h1>
    <label for="usernameLogin">Nazwa użytkownika</label>
    <input type="text" id="usernameLogin" placeholder="Wpisz nazwę użytkownika" />
    <label for="adminPassword">Hasło</label>
    <input type="password" id="adminPassword" placeholder="Wpisz hasło" />
    <div class="buttons-container">
      <button type="button" onclick="login()">Zaloguj</button>
      <button type="button" onclick="showRegister()">Zarejestruj</button>
    </div>
    <div id="loginError" class="error" style="display: none;">Nieprawidłowe dane logowania.</div>
  </div>

  <!-- Formularz rejestracji -->
  <div id="registerSection" style="display: none;">
    <h1>Rejestracja</h1>
    <form id="registerForm">
      <label for="usernameRegister">Nazwa użytkownika</label>
      <input type="text" id="usernameRegister" placeholder="Wpisz nazwę użytkownika" />
      
      <label for="passwordRegister">Hasło</label>
      <input type="password" id="passwordRegister" placeholder="Wpisz hasło" />
      
      <div class="buttons-container">
        <button type="button" onclick="register()">Zarejestruj</button>
        <button type="button" onclick="hideRegister()">Anuluj</button>
      </div>
    </form>
    
    <div id="registerError" class="error" style="display: none;">Wystąpił błąd podczas rejestracji.</div>
    <div id="registerSuccess" class="success" style="display: none; color: green;">Rejestracja zakończona sukcesem. Możesz się zalogować.</div>
  </div>

  <!-- Panel Administratora -->
  <div id="adminPanel" style="display: none;">
    <h1>Panel Administratora</h1>
    <div class="buttons-container">
      <button class="btn" onclick="showActiveAppointments()">Aktywne Rezerwacje</button>
      <button class="btn" onclick="showArchivedAppointments()">Zarchiwizowane Rezerwacje</button>
      <button class="btn" onclick="toggleAddAppointmentForm()">Dodaj Rezerwację</button>
      <button class="btn" onclick="clearDatabase()">Wyczyść Wszystkie Tabele</button> <!-- Nowy guzik -->
      <button class="btn" onclick="logout()">Wyloguj się</button>
    </div>
  
    <!-- Formularz Dodawania Rezerwacji -->
    <form id="addAppointmentForm" style="display: none;">
      <!-- Pola formularza -->
      <label for="appointmentUser">Użytkownik</label>
      <select id="appointmentUser" required>
        <option value="">-- Wybierz użytkownika --</option>
        <!-- Opcje użytkowników będą dodawane dynamicznie -->
      </select>
  
      <label for="appointmentName">Imię i Nazwisko</label>
      <input type="text" id="appointmentName" placeholder="Wpisz imię i nazwisko" />
  
      <label for="appointmentEmail">Email</label>
      <input type="email" id="appointmentEmail" placeholder="Wpisz email" />
  
      <label for="appointmentPhone">Telefon</label>
      <input type="tel" id="appointmentPhone" placeholder="Wpisz numer telefonu" />
  
      <label for="appointmentDate">Data</label>
      <input type="date" id="appointmentDate" required />
  
      <label for="appointmentTime">Godzina</label>
      <select id="appointmentTime" required>
        <option value="">-- Wybierz godzinę --</option>
        <option value="09:00">09:00</option>
        <option value="09:30">09:30</option>
        <option value="10:00">10:00</option>
        <!-- Dodaj więcej opcji godzin -->
      </select>
  
      <button type="button" onclick="addAppointment()">Dodaj Rezerwację</button>
      <button type="button" onclick="toggleAddAppointmentForm()">Zamknij</button>
      <div id="addAppointmentError" class="error" style="display: none; color: red;">Wystąpił błąd podczas dodawania rezerwacji.</div>
      <div id="addAppointmentSuccess" class="success" style="display: none; color: green;">Rezerwacja została dodana pomyślnie.</div>
    </form>

    <!-- Tabela aktywnych rezerwacji -->
    <div id="activeAppointments">
      <h2>Aktywne Rezerwacje</h2>
      <table>
        <thead>
          <tr>
            <th>ID</th>
            <th>Data</th>
            <th>Godzina</th>
            <th>Imię i Nazwisko</th>
            <th>Email</th>
            <th>Telefon</th>
            <th>Akcje</th>
          </tr>
        </thead>
        <tbody id="activeAppointmentsBody">
          <!-- Rezerwacje będą dodawane dynamicznie -->
        </tbody>
      </table>
    </div>

    <!-- Tabela zarchiwizowanych rezerwacji -->
    <div id="archivedAppointments" style="display: none;">
      <h2>Zarchiwizowane Rezerwacje</h2>
      <table>
        <thead>
          <tr>
            <th>ID</th>
            <th>Data</th>
            <th>Godzina</th>
            <th>Imię i Nazwisko</th>
            <th>Email</th>
            <th>Telefon</th>
            <th>Powód Archiwizacji</th>
            <th>Data Archiwizacji</th>
          </tr>
        </thead>
        <tbody id="archivedAppointmentsBody">
          <!-- Zarchiwizowane rezerwacje będą dodawane dynamicznie -->
        </tbody>
      </table>
    </div>
  </div>

  <!-- Panel Użytkownika -->
  <div id="userPanel" style="display: none;">
    <h1>Panel Użytkownika</h1>
    <div class="buttons-container">
      <button class="btn" onclick="showUserAppointments()">Moje Rezerwacje</button>
      <button class="btn" onclick="logout()">Wyloguj się</button>
    </div>

    <!-- Tabela rezerwacji użytkownika -->
    <div id="userAppointments">
      <h2>Moje Aktywne Rezerwacje</h2>
      <table>
        <thead>
          <tr>
            <th>ID</th>
            <th>Data</th>
            <th>Godzina</th>
            <th>Imię i Nazwisko</th>
            <th>Email</th>
            <th>Telefon</th>
          </tr>
        </thead>
        <tbody id="userAppointmentsBody">
          <!-- Rezerwacje użytkownika będą dodawane dynamicznie -->
        </tbody>
      </table>
    </div>
  </div>

  <!-- Footer -->
  <footer>
    <p>Developed By Xarond</p>
  </footer>

  <script>
    // Tryb ciemny
    document.getElementById('toggleDarkMode').addEventListener('click', () => {
      document.body.classList.toggle('dark-mode');
      localStorage.setItem('darkMode', document.body.classList.contains('dark-mode'));
    });

    // Sprawdzenie, czy użytkownik jest już zalogowany po odświeżeniu strony
    document.addEventListener('DOMContentLoaded', () => {
      const isDarkMode = localStorage.getItem('darkMode');
      if (isDarkMode === 'true') {
        document.body.classList.add('dark-mode');
      }

      checkAuthStatus();
    });

    // Funkcja logowania
    function login() {
      const username = document.getElementById('usernameLogin').value.trim();
      const password = document.getElementById('adminPassword').value.trim();

      if (!username || !password) {
        document.getElementById('loginError').textContent = 'Wszystkie pola są wymagane.';
        document.getElementById('loginError').style.display = 'block';
        return;
      }

      fetch('/users/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username, password }),
        credentials: 'include' // Uwzględnij ciasteczka
      })
        .then((res) => {
          if (!res.ok) throw new Error('Invalid login');
          return res.json(); // Oczekiwane dane: { isAdmin: true/false, isUser: true }
        })
        .then((data) => {
          if (data.isAdmin || data.isUser) { // Zakładając, że backend zwraca isAdmin lub isUser
            document.getElementById('loginSection').style.display = 'none';
            document.getElementById('registerSection').style.display = 'none';
            if (data.isAdmin) {
              document.getElementById('adminPanel').style.display = 'block';
              loadActiveAppointments();
              loadUsers(); // Załaduj listę użytkowników do formularza rezerwacji
            } else {
              document.getElementById('userPanel').style.display = 'block';
              loadUserAppointments();
            }
          } else {
            throw new Error('Unauthorized');
          }
        })
        .catch(() => {
          document.getElementById('loginError').textContent = 'Nieprawidłowe dane logowania.';
          document.getElementById('loginError').style.display = 'block';
        });
    }

    // Funkcja wylogowania
    function logout() {
      fetch('/users/logout', {
        method: 'POST',
        credentials: 'include'
      })
        .then((res) => {
          if (res.ok) {
            document.getElementById('adminPanel').style.display = 'none';
            document.getElementById('userPanel').style.display = 'none';
            document.getElementById('loginSection').style.display = 'block';
            document.getElementById('registerSection').style.display = 'none';
          } else {
            throw new Error('Logout failed');
          }
        })
        .catch(() => {
          alert('Wystąpił błąd podczas wylogowywania.');
        });
    }

    // Funkcja ładowania aktywnych rezerwacji (admin)
    function loadActiveAppointments() {
      fetch('/appointments', {
        method: 'GET',
        credentials: 'include'
      })
        .then((res) => {
          if (!res.ok) throw new Error('Failed to fetch active appointments');
          return res.json();
        })
        .then((appointments) => {
          const activeTableBody = document.getElementById('activeAppointmentsBody');
          activeTableBody.innerHTML = ''; // Wyczyść tabelę

          if (appointments.length === 0) {
            activeTableBody.innerHTML = '<tr><td colspan="7">Brak aktywnych rezerwacji.</td></tr>';
            return;
          }

          appointments.forEach((ap) => {
            const row = document.createElement('tr');

            const idCell = document.createElement('td');
            idCell.textContent = ap.id;
            row.appendChild(idCell);

            const dateCell = document.createElement('td');
            dateCell.textContent = ap.date;
            row.appendChild(dateCell);

            const timeCell = document.createElement('td');
            timeCell.textContent = ap.time;
            row.appendChild(timeCell);

            const nameCell = document.createElement('td');
            nameCell.textContent = ap.name || 'Brak danych';
            row.appendChild(nameCell);

            const emailCell = document.createElement('td');
            emailCell.textContent = ap.email || 'Brak danych';
            row.appendChild(emailCell);

            const phoneCell = document.createElement('td');
            phoneCell.textContent = ap.phone || 'Brak danych';
            row.appendChild(phoneCell);

            const actionsCell = document.createElement('td');
            const archiveButton = document.createElement('button');
            archiveButton.textContent = 'Archiwizuj';
            archiveButton.classList.add('btn');
            archiveButton.onclick = () => archiveAppointment(ap.id);
            actionsCell.appendChild(archiveButton);
            row.appendChild(actionsCell);

            activeTableBody.appendChild(row);
          });
        })
        .catch(() => {
          alert('Wystąpił błąd podczas ładowania aktywnych rezerwacji.');
        });
    }

    // Funkcja archiwizacji rezerwacji (admin)
    function archiveAppointment(appointmentId) {
      if (!confirm('Czy na pewno chcesz archiwizować tę rezerwację?')) return;

      fetch(`/appointments/archive/${appointmentId}`, {
        method: 'POST',
        credentials: 'include'
      })
        .then((res) => {
          if (!res.ok) throw new Error('Failed to archive appointment');
          return res.json();
        })
        .then(() => {
          alert('Rezerwacja została zarchiwizowana.');
          loadActiveAppointments(); // Odśwież listę rezerwacji
          loadArchivedAppointments(); // Odśwież zarchiwizowane rezerwacje
        })
        .catch(() => {
          alert('Wystąpił błąd podczas archiwizacji rezerwacji.');
        });
    }

    // Funkcja ładowania zarchiwizowanych rezerwacji (admin)
    function loadArchivedAppointments() {
      fetch('/appointments/archived', {
        method: 'GET',
        credentials: 'include'
      })
        .then((res) => {
          if (!res.ok) throw new Error('Failed to fetch archived appointments');
          return res.json();
        })
        .then((appointments) => {
          const archivedTableBody = document.getElementById('archivedAppointmentsBody');
          archivedTableBody.innerHTML = ''; // Wyczyść tabelę

          if (appointments.length === 0) {
            archivedTableBody.innerHTML = '<tr><td colspan="8">Brak zarchiwizowanych rezerwacji.</td></tr>';
            return;
          }

          appointments.forEach((ap) => {
            const row = document.createElement('tr');

            const idCell = document.createElement('td');
            idCell.textContent = ap.id;
            row.appendChild(idCell);

            const dateCell = document.createElement('td');
            dateCell.textContent = ap.date;
            row.appendChild(dateCell);

            const timeCell = document.createElement('td');
            timeCell.textContent = ap.time;
            row.appendChild(timeCell);

            const nameCell = document.createElement('td');
            nameCell.textContent = ap.name || 'Brak danych';
            row.appendChild(nameCell);

            const emailCell = document.createElement('td');
            emailCell.textContent = ap.email || 'Brak danych';
            row.appendChild(emailCell);

            const phoneCell = document.createElement('td');
            phoneCell.textContent = ap.phone || 'Brak danych';
            row.appendChild(phoneCell);

            const reasonCell = document.createElement('td');
            reasonCell.textContent = ap.archive_reason || 'Brak powodu';
            row.appendChild(reasonCell);

            const archivedAtCell = document.createElement('td');
            archivedAtCell.textContent = ap.archived_at ? new Date(ap.archived_at).toLocaleString() : 'Brak daty';
            row.appendChild(archivedAtCell);

            archivedTableBody.appendChild(row);
          });
        })
        .catch(() => {
          alert('Wystąpił błąd podczas ładowania zarchiwizowanych rezerwacji.');
        });
    }

    // Funkcja toggle dla formularza dodawania rezerwacji (admin)
    function toggleAddAppointmentForm() {
      const form = document.getElementById('addAppointmentForm');
      if (form.style.display === 'none' || form.style.display === '') {
        form.style.display = 'block';
      } else {
        form.style.display = 'none';
      }
    }

    // Funkcja dodawania rezerwacji (admin)
    function addAppointment() {
      const userId = document.getElementById('appointmentUser').value;
      const name = document.getElementById('appointmentName').value.trim();
      const email = document.getElementById('appointmentEmail').value.trim();
      const phone = document.getElementById('appointmentPhone').value.trim();
      const date = document.getElementById('appointmentDate').value;
      const time = document.getElementById('appointmentTime').value;

      // Walidacja danych
      if (!userId || !date || !time) {
        document.getElementById('addAppointmentError').textContent = 'Użytkownik, data i godzina są wymagane.';
        document.getElementById('addAppointmentError').style.display = 'block';
        document.getElementById('addAppointmentSuccess').style.display = 'none';
        return;
      }

      const appointment = { userId, name, email, phone, date, time };
      console.log('Dodawanie rezerwacji:', appointment); // Logowanie danych

      fetch('/appointments', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(appointment),
        credentials: 'include'
      })
        .then((res) => {
          console.log('Odpowiedź z serwera:', res); // Logowanie odpowiedzi
          if (!res.ok) throw new Error('Failed to add appointment');
          return res.json();
        })
        .then((data) => {
          console.log('Dane odpowiedzi:', data); // Logowanie danych odpowiedzi
          document.getElementById('addAppointmentError').style.display = 'none';
          document.getElementById('addAppointmentSuccess').textContent = 'Rezerwacja została dodana pomyślnie.';
          document.getElementById('addAppointmentSuccess').style.display = 'block';
          document.getElementById('addAppointmentForm').reset();
          loadActiveAppointments();
        })
        .catch((error) => {
          console.error('Błąd podczas dodawania rezerwacji:', error); // Logowanie błędów
          document.getElementById('addAppointmentError').textContent = 'Wystąpił błąd podczas dodawania rezerwacji.';
          document.getElementById('addAppointmentError').style.display = 'block';
          document.getElementById('addAppointmentSuccess').style.display = 'none';
        });
    }

    // Funkcja czyszczenia bazy danych (admin)
    function clearDatabase() {
      if (!confirm('Czy na pewno chcesz wyczyścić wszystkie tabele w bazie danych? Ta operacja jest nieodwracalna.')) {
        return;
      }

      fetch('/admin/clear-database', {
        method: 'DELETE',
        credentials: 'include' // Upewnij się, że ciasteczka są dołączone
      })
        .then((res) => {
          console.log('Odpowiedź z serwera:', res);
          if (!res.ok) {
            return res.json().then(err => { throw new Error(err.error || 'Failed to clear database'); });
          }
          return res.json();
        })
        .then((data) => {
          console.log('Dane odpowiedzi:', data);
          alert(data.message);
          // Opcjonalnie, możesz odświeżyć stronę lub przekierować administratora
          window.location.reload();
        })
        .catch((error) => {
          console.error('Błąd podczas czyszczenia bazy danych:', error);
          alert(error.message || 'Wystąpił błąd podczas czyszczenia bazy danych.');
        });
    }

    // Funkcja ładowania listy użytkowników do formularza rezerwacji (admin)
    function loadUsers() {
      fetch('/users/list', { // Endpoint do pobrania listy użytkowników
        method: 'GET',
        credentials: 'include'
      })
        .then((res) => {
          if (!res.ok) throw new Error('Failed to fetch users');
          return res.json();
        })
        .then((users) => {
          const userSelect = document.getElementById('appointmentUser');
          userSelect.innerHTML = '<option value="">-- Wybierz użytkownika --</option>'; // Resetuj opcje
          users.forEach((user) => {
            const option = document.createElement('option');
            option.value = user.id;
            option.textContent = user.username;
            userSelect.appendChild(option);
          });
        })
        .catch(() => {
          alert('Wystąpił błąd podczas ładowania listy użytkowników.');
        });
    }

    // Funkcja ładowania rezerwacji użytkownika
    function loadUserAppointments() {
      fetch('/appointments/user', {
        method: 'GET',
        credentials: 'include'
      })
        .then((res) => {
          if (!res.ok) throw new Error('Failed to fetch user appointments');
          return res.json();
        })
        .then((appointments) => {
          const userTableBody = document.getElementById('userAppointmentsBody');
          userTableBody.innerHTML = ''; // Wyczyść tabelę

          if (appointments.length === 0) {
            userTableBody.innerHTML = '<tr><td colspan="6">Brak aktywnych rezerwacji.</td></tr>';
            return;
          }

          appointments.forEach((ap) => {
            const row = document.createElement('tr');

            const idCell = document.createElement('td');
            idCell.textContent = ap.id;
            row.appendChild(idCell);

            const dateCell = document.createElement('td');
            dateCell.textContent = ap.date;
            row.appendChild(dateCell);

            const timeCell = document.createElement('td');
            timeCell.textContent = ap.time;
            row.appendChild(timeCell);

            const nameCell = document.createElement('td');
            nameCell.textContent = ap.name || 'Brak danych';
            row.appendChild(nameCell);

            const emailCell = document.createElement('td');
            emailCell.textContent = ap.email || 'Brak danych';
            row.appendChild(emailCell);

            const phoneCell = document.createElement('td');
            phoneCell.textContent = ap.phone || 'Brak danych';
            row.appendChild(phoneCell);

            userTableBody.appendChild(row);
          });
        })
        .catch(() => {
          alert('Wystąpił błąd podczas ładowania Twoich rezerwacji.');
        });
    }

    // Funkcja pokazywania rezerwacji użytkownika
    function showUserAppointments() {
      document.getElementById('userAppointments').style.display = 'block';
    }

    // Funkcja pokazywania formularza rejestracji
    function showRegister() {
      document.getElementById('loginSection').style.display = 'none';
      document.getElementById('registerSection').style.display = 'block';
      document.getElementById('loginError').style.display = 'none';
    }

    // Funkcja ukrywania formularza rejestracji
    function hideRegister() {
      document.getElementById('registerSection').style.display = 'none';
      document.getElementById('loginSection').style.display = 'block';
      document.getElementById('registerError').style.display = 'none';
      document.getElementById('registerSuccess').style.display = 'none';
    }

    // Funkcja rejestracji
    function register() {
  const username = document.getElementById('usernameRegister').value.trim();
  const password = document.getElementById('passwordRegister').value.trim();

  if (!username || !password) {
    document.getElementById('registerError').textContent = 'Wszystkie pola są wymagane.';
    document.getElementById('registerError').style.display = 'block';
    document.getElementById('registerSuccess').style.display = 'none';
    return;
  }

  fetch('/users/register', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ username, password }),
    credentials: 'include'
  })
    .then((res) => {
      if (!res.ok) {
        return res.json().then(err => { throw new Error(err.error || 'Rejestracja nie powiodła się'); });
      }
      return res.json();
    })
    .then((data) => {
      document.getElementById('registerError').style.display = 'none';
      document.getElementById('registerSuccess').textContent = data.message;
      document.getElementById('registerSuccess').style.display = 'block';
      document.getElementById('registerForm').reset(); // Reset formularza po sukcesie
    })
    .catch((error) => {
      console.error('Błąd podczas rejestracji:', error);
      document.getElementById('registerError').textContent = error.message || 'Wystąpił błąd podczas rejestracji.';
      document.getElementById('registerError').style.display = 'block';
      document.getElementById('registerSuccess').style.display = 'none';
    });
}

    // Sprawdzenie statusu użytkownika po odświeżeniu strony
    function checkAuthStatus() {
      fetch('/users/status', {
        method: 'GET',
        credentials: 'include'
      })
        .then((res) => {
          if (res.ok) return res.json();
          throw new Error('Not authenticated');
        })
        .then((data) => {
          if (data.isAdmin || data.isUser) { // Zakładając, że backend zwraca isAdmin lub isUser
            document.getElementById('loginSection').style.display = 'none';
            document.getElementById('registerSection').style.display = 'none';
            if (data.isAdmin) {
              document.getElementById('adminPanel').style.display = 'block';
              loadActiveAppointments();
              loadUsers(); // Załaduj listę użytkowników do formularza rezerwacji
            } else {
              document.getElementById('userPanel').style.display = 'block';
              loadUserAppointments();
            }
          }
        })
        .catch(() => {
          // Użytkownik nie jest zalogowany, pozostaje na formularzu logowania
        });
    }
  </script>
</body>
</html>
