<style>


/* General Styling */
body {
  font-family: Arial, sans-serif;
  margin: 0;
  padding: 0;
  background-color: #f5f5f5;
  color: #333;
}

.container {
  max-width: 700px;
  margin: 20px auto;
  padding: 20px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

h1 {
  text-align: center;
  font-size: 24px;
  color: #444;
}

/* Tabs */
.tabs {
  display: flex;
  justify-content: space-around;
  border-bottom: 2px solid #ddd;
  margin-bottom: 15px;
}

.tab {
  padding: 10px 15px;
  cursor: pointer;
  background-color: #f9f9f9;
  border: 1px solid #ddd;
  border-bottom: none;
  transition: background-color 0.3s;
  text-align: center;
  flex: 1;
}

.tab.active {
  background-color: #ffffff;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
  font-weight: bold;
}

.tab:hover {
  background-color: #eaeaea;
}

/* Tab Content */
.tab-content {
  display: none;
  animation: fadeIn 0.3s ease-in-out;
}

.tab-content.active {
  display: block;
}

/* Form */
form {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.form-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 0;
  padding: 0;
}

label {
  flex: 1;
  font-size: 14px;
  color: #555;
}

input, textarea {
  flex: 2;
  padding: 1px;
  font-size: 14px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: #fff;
}

textarea {
  resize: vertical;
  height: 80px;
}

button {
  padding: 10px 15px;
  background-color: #007BFF;
  color: #ffffff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

button:hover {
  background-color: #0056b3;
}

/* Table */
table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 1px;
  text-align: left;
  border: 1px solid #ddd;
}

th {
  background-color: #f4f4f4;
  color: #555;
}

tr:nth-child(even) {
  background-color: #f9f9f9;
}

tr:hover {
  background-color: #f1f1f1;
}

/* Animation */
@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}


</style>


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>vCard Manager</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <div class="container">
   
    <!-- Tabs -->
    <div class="tabs">
      <div class="tab active" data-tab="form-tab">vCard Form</div>
      <div class="tab" data-tab="list-tab">vCard List</div>
    </div>

    <!-- Form Tab -->
    <div class="tab-content active" id="form-tab">
      <form id="vCardForm">

        <input type="text" id="_id" name="_id"  hidden />
     
        <div class="form-row">
          <label for="id">ID</label>
          <input type="text" id="id" name="id" maxlength="10" />
        </div>
        <div class="form-row">
          <label for="firstName">First Name</label>
          <input type="text" id="firstName" name="firstName" maxlength="20" />
        </div>
        <div class="form-row">
          <label for="lastName">Last Name</label>
          <input type="text" id="lastName" name="lastName" maxlength="20" />
        </div>
        <div class="form-row">
          <label for="organization">Organization</label>
          <input type="text" id="organization" name="organization" maxlength="30" />
        </div>
        <div class="form-row">
          <label for="title">Title</label>
          <input type="text" id="title" name="title" maxlength="30" />
        </div>
        <div class="form-row">
          <label for="workPhone">Work Phone</label>
          <input type="tel" id="workPhone" name="workPhone" maxlength="15" />
        </div>

        <div class="form-row">
          <label for="workPhone2">Additional Phone</label>
          <input type="tel" id="workPhone2" name="workPhone2" maxlength="15" />
        </div>
        <div class="form-row">
          <label for="email">Email</label>
          <input type="email" id="email" name="email" maxlength="50" />
        </div>
        <div class="form-row">
          <label for="url">Website</label>
          <input type="url" id="url" name="url" />
        </div>
        <div class="form-row">
          <label for="address">Address</label>
          <input type="text" id="address" name="address" maxlength="100" />
        </div>
        <div class="form-row">
          <label for="location">Location</label>
          <input type="text" id="location" name="location" maxlength="50" />
        </div>
        <div class="form-row">
          <label for="item-image-url">Image</label>
          <input type="file" id="item-image-url" name="image" />
        </div>
        <div class="form-row">
          <label for="note">Note</label>
          <textarea id="note" name="note" maxlength="200"></textarea>
        </div>
        <button type="submit">Save vCard</button>
      </form>
    </div>

    <!-- List Tab -->
    <div class="tab-content" id="list-tab">

      <div class="search-bar">
        <input type="text" id="search-input" placeholder="Search by ID, Name, Phone Number">
      
      </div>


      <table id="vCardTable">
        <thead>
          <tr>
            <th>ID</th>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Email</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          <!-- Dynamic rows -->
        </tbody>
      </table>
    </div>
  </div>

  <script>
    // Tab functionality
    document.querySelectorAll('.tab').forEach(tab => {
      tab.addEventListener('click', () => {
        document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));

        document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
        tab.classList.add('active');
        document.getElementById(tab.dataset.tab).classList.add('active');
      });
    });
  </script>
</body>
</html>

<script>

// JavaScript Code
const API_BASE_URL = '/api/vcard';
let vCardsData = []; // Local storage for vCards

// Fetch and display all vCards
async function fetchVCards() {
  const response = await fetch(API_BASE_URL);
  const vCards = await response.json();

  vCardsData = vCards; // Store the fetched data locally

  const tableBody = document.querySelector('#vCardTable tbody');
  tableBody.innerHTML = ''; // Clear existing rows

  vCards.forEach((vCard) => {
    const row = document.createElement('tr');
    row.innerHTML = `
      <td>${vCard.id}</td>
      <td>${vCard.firstName}</td>
      <td>${vCard.lastName}</td>
      <td>${vCard.email}</td>
      <td>
        <button onclick="editVCard('${vCard._id}')">Edit</button>
        <button onclick="deleteVCard('${vCard._id}')">Delete</button>
      </td>
    `;
    tableBody.appendChild(row);
  });
}

// Create or update a vCard
async function saveVCard(event) {
  event.preventDefault();

  const formData = new FormData();
  const imageFile = document.getElementById('item-image-url').files[0];
  const _id = document.querySelector('#_id').value; // Internal hidden ID for backend

  // Append vCard fields to FormData
  formData.append('_id', _id);
  formData.append('id', document.querySelector('#id').value);
  formData.append('firstName', document.querySelector('#firstName').value);
  formData.append('lastName', document.querySelector('#lastName').value);
  formData.append('organization', document.querySelector('#organization').value);
  formData.append('title', document.querySelector('#title').value);
  formData.append('workPhone', document.querySelector('#workPhone').value);
  formData.append('workPhone2', document.querySelector('#workPhone2').value);
  
  formData.append('email', document.querySelector('#email').value);
  formData.append('url', document.querySelector('#url').value);
  formData.append('address', document.querySelector('#address').value);
  formData.append('map', document.querySelector('#location').value);
  formData.append('note', document.querySelector('#note').value);

  // Append the image file if it exists
  if (imageFile) {
    formData.append('image', imageFile);
  }

  const method = _id ? 'PUT' : 'POST'; // Determine HTTP method based on _id presence
  const endpoint = _id ? `${API_BASE_URL}/${_id}` : API_BASE_URL; // Use _id for updates
  const response = await fetch(endpoint, {
    method,
    body: formData,
  });

  if (response.ok) {
    document.querySelector('#vCardForm').reset(); // Clear the form
    const result = await response.json(); // Parse the JSON response
    alert(result.message); // Show success message
    fetchVCards(); // Refresh the list
   
    document.querySelector('#_id').value = ''; // Reset hidden _id field
  } else {
    alert(await response.text());
    console.error('Error saving vCard:', await response.text());
  }
}

// Populate the form for editing a vCard
function editVCard(_id) {
  // Find the vCard from locally stored data
  const vCard = vCardsData.find(card => card._id === _id);

  if (!vCard) {
    console.error('vCard not found in local data');
    return;
  }

  // Populate the form with the vCard's data
  document.querySelector('#_id').value = vCard._id || ''; // Hidden backend ID
  document.querySelector('#id').value = vCard.id || '';
  document.querySelector('#firstName').value = vCard.firstName || '';
  document.querySelector('#lastName').value = vCard.lastName || '';
  document.querySelector('#organization').value = vCard.organization || '';
  document.querySelector('#title').value = vCard.title || '';
  document.querySelector('#workPhone').value = vCard.workPhone || '';
  document.querySelector('#workPhone2').value = vCard.workPhone2 || '';
  document.querySelector('#email').value = vCard.email || '';
  document.querySelector('#url').value = vCard.url || '';
  document.querySelector('#address').value = vCard.address || '';
  document.querySelector('#location').value = vCard.map || '';
  document.querySelector('#note').value = vCard.note || '';
 activateTab('form-tab');
}

// Function to activate a tab
function activateTab(tabId) {
  // Remove active class from all tabs and contents
  document.querySelectorAll('.tab').forEach(tab => tab.classList.remove('active'));
  document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));

  // Add active class to the clicked tab and corresponding content
  document.querySelector(`.tab[data-tab="${tabId}"]`).classList.add('active');
  document.querySelector(`#${tabId}`).classList.add('active');
}
// Delete a vCard
async function deleteVCard(_id) {
  const response = await fetch(`${API_BASE_URL}/${_id}`, { method: 'DELETE' });

  if (response.ok) {
    // Remove the deleted vCard from local storage
    vCardsData = vCardsData.filter(card => card._id !== _id);
    fetchVCards(); // Refresh the list
  } else {
    console.error('Error deleting vCard:', await response.text());
  }
}

// Event listener for the form
document.querySelector('#vCardForm').addEventListener('submit', saveVCard);

















function searchVCards(searchTerm) {
  // Filter the vCardsData based on the search term
  const searchTextLower = searchTerm.toLowerCase();
  const filteredVCards = vCardsData.filter(vCard => {
   
    return (
      vCard.id?.toLowerCase().includes(searchTextLower) ||
      vCard.firstName?.toLowerCase().includes(searchTextLower) ||
      vCard.lastName?.toLowerCase().includes(searchTextLower) ||
      vCard.workPhone?.toLowerCase().includes(searchTextLower) ||
      vCard.workPhone2?.toLowerCase().includes(searchTextLower)
    );
  });

  // Update the table body with the filtered results
  updateTable(filteredVCards);
}

function updateTable(vCards) {
  const tableBody = document.querySelector('#vCardTable tbody');
  tableBody.innerHTML = ''; // Clear existing rows

  vCards.forEach((vCard) => {
    const row = document.createElement('tr');
    row.innerHTML = `
      <td>${vCard.id}</td>
      <td>${vCard.firstName}</td>
      <td>${vCard.lastName}</td>
      <td>${vCard.email}</td>
      <td>
        <button onclick="editVCard('${vCard._id}')">Edit</button>
        <button onclick="deleteVCard('${vCard._id}')">Delete</button>
      </td>
    `;
    tableBody.appendChild(row);
  });
}




document.getElementById('search-input').addEventListener('keydown', () => {
 
  const searchTerm = document.getElementById('search-input').value;
  if (searchTerm) {
    searchVCards(searchTerm);
  } else {
    // Handle empty search or reset the table if needed
    fetchVCards(); // Refetch all vCards
  }
});




// Initial fetch of vCards
fetchVCards();













</script>