/**
 * Ragreen - Business dashboard & profile logic
 * Requires config.js + jQuery loaded first.
 */

const BusinessDashboard = {
  init() {
    $.get(`${API_BASE}/business/dashboard.php`)
      .done((res) => this.render(res.data.stats, res.data.recent_sales))
      .fail((xhr) => {
        $('#dashboardContent').html(`<div class="empty-state"><h3>Could not load your dashboard</h3><p>${xhr.responseJSON?.message || ''}</p></div>`);
      });
  },

  render(stats, sales) {
    $('#statGrid').html(`
      <div class="stat-card"><div class="num">${stats.active_listings}</div><div class="label">Active listings</div></div>
      <div class="stat-card ${stats.low_stock > 0 ? 'warn' : ''}"><div class="num">${stats.low_stock}</div><div class="label">Low stock (≤3)</div></div>
      <div class="stat-card"><div class="num">$${stats.total_sales.toFixed(2)}</div><div class="label">Total sales (completed)</div></div>
      <div class="stat-card ${stats.pending_sales > 0 ? 'warn' : ''}"><div class="num">${stats.pending_sales}</div><div class="label">Awaiting confirmation</div></div>
      <div class="stat-card"><div class="num">${stats.total_orders}</div><div class="label">Orders completed</div></div>
      <div class="stat-card"><div class="num">${stats.sold_listings}</div><div class="label">Sold out</div></div>
      <div class="stat-card"><div class="num">${stats.inactive_listings}</div><div class="label">Inactive</div></div>
    `);

    const $sales = $('#recentSales');
    const statusLabels = { pending: 'Pending', fulfilled: 'Completed', cancelled: 'Cancelled' };
    const statusClass = { pending: 'inactive', fulfilled: 'active', cancelled: 'expired' };
    if (!sales.length) {
      $sales.html('<p style="color:var(--ink-muted); font-size:13px;">No sales yet.</p>');
      return;
    }
    $sales.html(`
      <table class="data-table">
        <thead><tr><th>Product</th><th>Qty</th><th>Amount</th><th>Order</th><th>Date</th><th>Status</th></tr></thead>
        <tbody>
          ${sales.map(s => `
            <tr>
              <td>${escapeHtml(s.product_name)}</td>
              <td>${s.quantity}</td>
              <td>$${(s.quantity * s.unit_price).toFixed(2)}</td>
              <td>#${s.order_id}</td>
              <td>${formatDate(s.created_at.split(' ')[0])}</td>
              <td><span class="status-pill status-${statusClass[s.status]}">${statusLabels[s.status]}</span></td>
            </tr>
          `).join('')}
        </tbody>
      </table>
      <a href="sales-history.html" style="display:inline-block; margin-top:14px; font-size:13px; font-weight:600; color:var(--leaf-dark); text-decoration:none;">View full sales history →</a>
    `);
  },
};

const BusinessProfile = {
  map: null,
  marker: null,

  init() {
    this.initMap();

    $.get(`${API_BASE}/business/profile.php`)
      .done((res) => this.fill(res.data.profile))
      .fail(() => showAlert($('#profileAlert'), 'Could not load your business profile.'));

    $('#businessProfileForm').on('submit', (e) => this.save(e));
  },

  initMap() {
    // Default view: centered roughly on Lebanon since that's this deployment's
    // primary market - the pin itself only gets placed once the vendor clicks.
    this.map = L.map('locationMap').setView([33.8547, 35.8623], 8);
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      attribution: '&copy; OpenStreetMap contributors',
      maxZoom: 19,
    }).addTo(this.map);

    this.map.on('click', (e) => this.setPin(e.latlng.lat, e.latlng.lng));

    $('#useMyLocationBtn').on('click', () => {
      if (!navigator.geolocation) {
        alert('Your browser does not support location detection - please click the map instead.');
        return;
      }
      navigator.geolocation.getCurrentPosition(
        (pos) => {
          this.map.setView([pos.coords.latitude, pos.coords.longitude], 15);
          this.setPin(pos.coords.latitude, pos.coords.longitude);
        },
        () => alert('Could not detect your location - please click the map to place the pin manually.')
      );
    });
  },

  setPin(lat, lng) {
    $('#latitude').val(lat.toFixed(7));
    $('#longitude').val(lng.toFixed(7));

    if (this.marker) {
      this.marker.setLatLng([lat, lng]);
    } else {
      this.marker = L.marker([lat, lng], { draggable: true }).addTo(this.map);
      this.marker.on('dragend', () => {
        const pos = this.marker.getLatLng();
        $('#latitude').val(pos.lat.toFixed(7));
        $('#longitude').val(pos.lng.toFixed(7));
      });
    }
  },

  fill(p) {
    $('#business_name').val(p.business_name);
    $('#category').val(p.category);
    $('#contact_person').val(p.contact_person);
    $('#address').val(p.address);
    $('#city').val(p.city);
    $('#country').val(p.country);
    $('#phone').val(p.phone);
    if (p.logo_url) {
      $('#logoPreview').attr('src', p.logo_url).show();
    }
    if (p.latitude && p.longitude) {
      const lat = parseFloat(p.latitude);
      const lng = parseFloat(p.longitude);
      this.map.setView([lat, lng], 15);
      this.setPin(lat, lng);
    }
  },

  save(e) {
    e.preventDefault();
    const $alert = $('#profileAlert');
    hideAlert($alert);

    const formData = new FormData();
    ['business_name', 'category', 'contact_person', 'address', 'city', 'country', 'phone', 'latitude', 'longitude'].forEach((id) => {
      formData.append(id, valTrim('#' + id));
    });
    const logoFile = $('#logo')[0].files[0];
    if (logoFile) formData.append('logo', logoFile);

    const $btn = $('#saveProfileBtn');
    setLoading($btn, true, 'Save changes', 'Saving…');

    $.ajax({
      url: `${API_BASE}/business/profile_update.php`, method: 'POST', data: formData, processData: false, contentType: false,
    })
      .done(() => showAlert($alert, 'Business profile updated.', 'success'))
      .fail((xhr) => showAlert($alert, xhr.responseJSON?.message || 'Could not save changes.'))
      .always(() => setLoading($btn, false, 'Save changes', 'Saving…'));
  },
};
