<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Special Need CRUD</title>
  <style>
    /* Inline CSS */
    body {
      font-family: Arial, sans-serif;
      margin: 20px;
    }
    .form-container, .table-container {
      margin-bottom: 20px;
    }
    table {
      width: 100%;
      border-collapse: collapse;
    }
    table, th, td {
      border: 1px solid black;
    }
    th, td {
      padding: 8px;
      text-align: left;
    }
    .form-field {
      margin-bottom: 10px;
    }
  </style>
</head>
<body>
  <h1>Special Need CRUD</h1>

  <!-- Form for Adding/Updating Special Needs -->
  <div class="form-container">
    <h2>Add/Update Special Need</h2>
    <form id="specialNeedForm">
      <div class="form-field">
        <label for="category">Category:</label>
        <select id="category" required>
          <option value="">Select a category</option>
        </select>
      </div>
      <div class="form-field">
        <label for="name">Name:</label>
        <input type="text" id="name" placeholder="Enter name" required>
      </div>
      <button type="submit">Save</button>
    </form>
  </div>

  <!-- Table to Display Special Needs -->
  <div class="table-container">
    <h2>Special Needs List</h2>
    <table>
      <thead>
        <tr>
          <th>Category</th>
          <th>Name</th>
          <th>Actions</th>
        </tr>
      </thead>
      <tbody id="specialNeedsTableBody">
      </tbody>
    </table>
  </div>

  <!-- Inline JavaScript -->
  <script>
    const CATEGORY_API = '/api/category';
    const SPECIAL_NEED_API = '/api/special-need'; // Adjust according to your backend

    const categoryDropdown = document.getElementById('category');
    const nameInput = document.getElementById('name');
    const specialNeedForm = document.getElementById('specialNeedForm');
    const tableBody = document.getElementById('specialNeedsTableBody');

    // Fetch Categories and Populate Dropdown
    async function loadCategories() {
      try {
        const response = await fetch(CATEGORY_API);
        const categories = await response.json();
        categories.forEach(category => {
          const option = document.createElement('option');
          option.value = category._id; // Assuming category has _id
          option.textContent = category.name;
          categoryDropdown.appendChild(option);
        });
      } catch (error) {
        console.error('Error fetching categories:', error);
      }
    }

    // Fetch Special Needs and Populate Table
    async function loadSpecialNeeds() {
      try {
        const response = await fetch(SPECIAL_NEED_API);
        const specialNeeds = await response.json();
        tableBody.innerHTML = '';
        specialNeeds.forEach(specialNeed => {
          const row = document.createElement('tr');
          row.innerHTML = `
            <td>${specialNeed.categoryId.name}</td>
            <td>${specialNeed.name}</td>
            <td>
              <button onclick="editSpecialNeed('${specialNeed._id}')">Edit</button>
              <button onclick="deleteSpecialNeed('${specialNeed._id}')">Delete</button>
            </td>
          `;
          tableBody.appendChild(row);
        });
      } catch (error) {
        console.error('Error fetching special needs:', error);
      }
    }

    // Save (Create or Update) Special Need
    specialNeedForm.addEventListener('submit', async (event) => {
      event.preventDefault();
      const categoryId = categoryDropdown.value;
      const name = nameInput.value;
      const specialNeed = { categoryId, name };

      try {
        await fetch(SPECIAL_NEED_API, {
          method: 'POST', // Use PUT for updates
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(specialNeed),
        });
        specialNeedForm.reset();
        loadSpecialNeeds();
      } catch (error) {
        console.error('Error saving special need:', error);
      }
    });

    // Delete Special Need
    async function deleteSpecialNeed(id) {
      try {
        await fetch(`${SPECIAL_NEED_API}/${id}`, { method: 'DELETE' });
        loadSpecialNeeds();
      } catch (error) {
        console.error('Error deleting special need:', error);
      }
    }

    // Edit Special Need (Prefill the form for update)
    async function editSpecialNeed(id) {
      try {
        const response = await fetch(`${SPECIAL_NEED_API}/${id}`);
        const specialNeed = await response.json();
               categoryDropdown.value = specialNeed.categoryId;
        nameInput.value = specialNeed.name;
      } catch (error) {
        console.error('Error editing special need:', error);
      }
    }

    // Initialize
    loadCategories();
    loadSpecialNeeds();
  </script>
</body>
</html>
