// owner.js: client‑side logic for the owner portal (owner.html)

document.addEventListener('DOMContentLoaded', () => {
  const metricsContainer = document.getElementById('metrics-container');
  const ownerListEl = document.getElementById('owner-property-list');
  const propForm = document.getElementById('property-form');

  // Load initial data
  loadMetrics();
  loadProperties();

  /**
   * Fetch and display dashboard metrics
   */
  function loadMetrics() {
    fetch('/api/dashboard')
      .then((res) => res.json())
      .then((data) => {
        metricsContainer.innerHTML = '';
        const metrics = [
          { label: 'Total Properties', value: data.totalProperties },
          { label: 'Total Bookings', value: data.totalBookings },
          { label: 'Total Revenue (BWP)', value: data.totalRevenue },
          { label: 'Occupancy Rate', value: `${data.occupancyRate}%` }
        ];
        metrics.forEach((m) => {
          const card = document.createElement('div');
          card.className = 'metric-card';
          card.innerHTML = `<h4>${m.label}</h4><p>${m.value}</p>`;
          metricsContainer.appendChild(card);
        });
      })
      .catch((err) => {
        console.error('Error fetching dashboard metrics:', err);
        metricsContainer.innerHTML = '<p>Unable to load metrics.</p>';
      });
  }

  /**
   * Fetch and display owner’s properties
   */
  function loadProperties() {
    fetch('/api/properties')
      .then((res) => res.json())
      .then((data) => {
        ownerListEl.innerHTML = '';
        if (data.length === 0) {
          ownerListEl.innerHTML = '<p>You have no properties yet.</p>';
          return;
        }
        data.forEach((prop) => {
          const card = document.createElement('div');
          card.className = 'property-card';
          card.innerHTML = `
            <h4>${prop.name}</h4>
            <p><strong>Location:</strong> ${prop.location}</p>
            <p><strong>Price:</strong> BWP ${prop.price} per night</p>
            <p><strong>Total Rooms:</strong> ${prop.totalRooms}</p>
            <p><strong>Available:</strong> ${prop.availableRooms}</p>
          `;
          ownerListEl.appendChild(card);
        });
      })
      .catch((err) => {
        console.error('Error fetching properties:', err);
        ownerListEl.innerHTML = '<p>Unable to load properties.</p>';
      });
  }

  // Handle property form submission
  propForm.addEventListener('submit', (e) => {
    e.preventDefault();
    const name = document.getElementById('prop-name').value.trim();
    const location = document.getElementById('prop-location').value.trim();
    const price = parseFloat(document.getElementById('prop-price').value);
    const rooms = parseInt(document.getElementById('prop-rooms').value, 10);
    if (!name || !location || isNaN(price) || isNaN(rooms)) {
      alert('Please fill out all fields correctly.');
      return;
    }
    const payload = { name, location, price, totalRooms: rooms };
    fetch('/api/properties', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(payload)
    })
      .then((res) => {
        if (!res.ok) throw new Error('Failed to add property');
        return res.json();
      })
      .then((data) => {
        alert('Property added successfully!');
        propForm.reset();
        loadProperties();
        loadMetrics();
      })
      .catch((err) => {
        console.error(err);
        alert('An error occurred while adding the property.');
      });
  });
});