<?php
require_once __DIR__ . '/../../api/lib.php';

hw_require_auth(['client']);

$authUser = hw_get_auth_user();
$page_title = 'Activity History | Herbal Wellness Care';
$page_description = 'View your complete activity history';

$page_content = function () use ($authUser) {
?>
<link rel="stylesheet" href="/files/atasteofafricanmarketplace/assets/dashboard.css">

<div style="max-width: 1200px; margin: 0 auto; padding: 40px 24px;">
  <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 32px;">
    <a href="/files/atasteofafricanmarketplace/dashboard/user/index.php" style="color: #059669; font-size: 14px; text-decoration: none;">
      <i class="fas fa-arrow-left"></i> Back to Dashboard
    </a>
  </div>
  
  <h1 style="font-size: 32px; color: var(--forest); margin-bottom: 12px;">Activity History</h1>
  <p style="color: var(--muted); margin-bottom: 32px;">View all your activities, from sessions to health updates and purchases.</p>
  
  <!-- Activity Type Filter -->
  <div style="display: flex; gap: 12px; margin-bottom: 24px; flex-wrap: wrap;">
    <button onclick="filterActivityType('all')" class="activity-filter-btn active" data-type="all" style="padding: 8px 16px; border-radius: 6px; border: 1px solid #059669; background: #059669; color: white; font-weight: 600; cursor: pointer; transition: all 0.2s ease;">All Activity</button>
    <button onclick="filterActivityType('appointment')" class="activity-filter-btn" data-type="appointment" style="padding: 8px 16px; border-radius: 6px; border: 1px solid #059669; background: transparent; color: #059669; font-weight: 600; cursor: pointer; transition: all 0.2s ease;">Sessions</button>
    <button onclick="filterActivityType('order')" class="activity-filter-btn" data-type="order" style="padding: 8px 16px; border-radius: 6px; border: 1px solid #059669; background: transparent; color: #059669; font-weight: 600; cursor: pointer; transition: all 0.2s ease;">Orders</button>
    <button onclick="filterActivityType('health')" class="activity-filter-btn" data-type="health" style="padding: 8px 16px; border-radius: 6px; border: 1px solid #059669; background: transparent; color: #059669; font-weight: 600; cursor: pointer; transition: all 0.2s ease;">Health Data</button>
    <button onclick="filterActivityType('document')" class="activity-filter-btn" data-type="document" style="padding: 8px 16px; border-radius: 6px; border: 1px solid #059669; background: transparent; color: #059669; font-weight: 600; cursor: pointer; transition: all 0.2s ease;">Documents</button>
    <button onclick="filterActivityType('intake')" class="activity-filter-btn" data-type="intake" style="padding: 8px 16px; border-radius: 6px; border: 1px solid #059669; background: transparent; color: #059669; font-weight: 600; cursor: pointer; transition: all 0.2s ease;">Intake Forms</button>
  </div>
  
  <!-- Stats Cards -->
  <div id="activityStatsContainer" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 16px; margin-bottom: 32px;">
    <!-- Stats will be loaded here -->
  </div>
  
  <!-- Activity List -->
  <div id="activityHistoryContainer" style="display: flex; flex-direction: column; gap: 16px;">
    <div style="text-align: center; color: var(--muted); padding: 60px 24px; font-size: 14px;">
      <i class="fas fa-spinner fa-spin"></i> Loading activity history...
    </div>
  </div>
  
  <!-- Pagination Controls -->
  <div id="historyPaginationControls" style="display: flex; justify-content: center; gap: 12px; margin-top: 32px;"></div>
</div>

<script>
let currentActivityType = 'all';
let currentActivityPage = 0;
const iconMap = {
  'appointment': { icon: 'fas fa-calendar-check', color: '#3b82f6' },
  'order': { icon: 'fas fa-shopping-bag', color: '#8b5cf6' },
  'health': { icon: 'fas fa-heartbeat', color: '#ef4444' },
  'document': { icon: 'fas fa-file-pdf', color: '#f59e0b' },
  'intake': { icon: 'fas fa-clipboard-list', color: '#10b981' }
};
const statusColors = {
  'completed': '#059669',
  'pending': '#f59e0b',
  'confirmed': '#3b82f6',
  'logged': '#10b981',
  'uploaded': '#8b5cf6',
  'submitted': '#06b6d4'
};

async function loadActivityHistory() {
  try {
    const response = await fetch(`/files/atasteofafricanmarketplace/api/users/activity-feed.php?type=${currentActivityType}&limit=20&offset=${currentActivityPage * 20}`, {
      credentials: 'include'
    });
    const data = await response.json();
    
    if (data.success) {
      renderActivityHistory(data);
      renderStats(data.type_counts);
    } else {
      document.getElementById('activityHistoryContainer').innerHTML = '<div style="color: red; font-size: 12px;">Error loading activity</div>';
    }
  } catch (err) {
    console.error('Error loading activity history:', err);
    document.getElementById('activityHistoryContainer').innerHTML = '<div style="color: red; font-size: 12px;">Error loading activity</div>';
  }
}

function renderStats(counts) {
  const container = document.getElementById('activityStatsContainer');
  container.innerHTML = '';
  
  const stats = [
    { label: 'Sessions', value: counts.appointments || 0 },
    { label: 'Orders', value: counts.orders || 0 },
    { label: 'Health Entries', value: counts.health || 0 },
    { label: 'Documents', value: counts.documents || 0 },
    { label: 'Intake Forms', value: counts.intakes || 0 }
  ];
  
  stats.forEach(stat => {
    const card = document.createElement('div');
    card.style.padding = '16px';
    card.style.borderRadius = '8px';
    card.style.backgroundColor = '#f0fdf4';
    card.style.borderLeft = '4px solid #059669';
    card.style.textAlign = 'center';
    card.innerHTML = `
      <div style="font-size: 24px; font-weight: 700; color: #059669;">${stat.value}</div>
      <div style="font-size: 12px; color: var(--muted); margin-top: 4px;">${stat.label}</div>
    `;
    container.appendChild(card);
  });
}

function renderActivityHistory(data) {
  const container = document.getElementById('activityHistoryContainer');
  
  if (!data.activities || data.activities.length === 0) {
    container.innerHTML = '<div style="text-align: center; color: var(--muted); padding: 60px 24px;">No activity to display</div>';
    document.getElementById('historyPaginationControls').innerHTML = '';
    return;
  }
  
  container.innerHTML = '';
  
  data.activities.forEach(activity => {
    const typeInfo = iconMap[activity.type] || { icon: 'fas fa-circle', color: '#6b7280' };
    const statusColor = statusColors[activity.status] || '#6b7280';
    
    const item = document.createElement('div');
    item.style.display = 'flex';
    item.style.gap = '20px';
    item.style.padding = '20px';
    item.style.borderRadius = '8px';
    item.style.backgroundColor = '#f9fafb';
    item.style.borderLeft = '4px solid ' + typeInfo.color;
    item.style.transition = 'all 0.2s ease';
    item.onmouseover = () => item.style.backgroundColor = '#ffffff';
    item.onmouseout = () => item.style.backgroundColor = '#f9fafb';
    
    item.innerHTML = `
      <div style="flex-shrink: 0; width: 48px; height: 48px; background-color: ${typeInfo.color}20; border-radius: 10px; display: flex; align-items: center; justify-content: center;">
        <i class="${typeInfo.icon}" style="color: ${typeInfo.color}; font-size: 20px;"></i>
      </div>
      <div style="flex: 1;">
        <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 8px;">
          <div style="font-weight: 700; color: var(--forest); font-size: 16px;">${activity.action}</div>
          <span style="background-color: ${statusColor}20; color: ${statusColor}; padding: 4px 12px; border-radius: 4px; font-size: 11px; font-weight: 700; text-transform: uppercase;">
            ${activity.status}
          </span>
        </div>
        <div style="color: var(--ink); font-size: 14px; margin-bottom: 12px;">${activity.description}</div>
        <div style="display: flex; gap: 24px; flex-wrap: wrap;">
          ${activity.duration_minutes ? `<div style="color: var(--muted); font-size: 12px;"><i class="fas fa-clock"></i> ${activity.duration_minutes} min</div>` : ''}
          ${activity.total_amount ? `<div style="color: var(--muted); font-size: 12px;"><i class="fas fa-dollar-sign"></i> $${parseFloat(activity.total_amount).toFixed(2)}</div>` : ''}
          ${activity.file_size ? `<div style="color: var(--muted); font-size: 12px;"><i class="fas fa-file"></i> ${(activity.file_size / 1024 / 1024).toFixed(2)} MB</div>` : ''}
          <div style="color: var(--muted); font-size: 12px;"><i class="fas fa-calendar"></i> ${activity.formatted_date}</div>
        </div>
      </div>
    `;
    
    container.appendChild(item);
  });
  
  // Render pagination controls
  renderPaginationControls(data.pagination);
}

function renderPaginationControls(pagination) {
  const controls = document.getElementById('historyPaginationControls');
  controls.innerHTML = '';
  
  if (pagination.total <= pagination.limit) {
    return;
  }
  
  const totalPages = Math.ceil(pagination.total / pagination.limit);
  
  // Previous button
  const prevBtn = document.createElement('button');
  prevBtn.innerHTML = '<i class="fas fa-chevron-left"></i> Previous';
  prevBtn.style.padding = '10px 18px';
  prevBtn.style.borderRadius = '6px';
  prevBtn.style.border = '1px solid #ddd';
  prevBtn.style.backgroundColor = currentActivityPage > 0 ? '#fff' : '#f3f4f6';
  prevBtn.style.cursor = currentActivityPage > 0 ? 'pointer' : 'not-allowed';
  prevBtn.style.color = currentActivityPage > 0 ? '#059669' : '#9ca3af';
  prevBtn.style.fontWeight = '600';
  prevBtn.disabled = currentActivityPage <= 0;
  prevBtn.onclick = () => {
    if (currentActivityPage > 0) {
      currentActivityPage--;
      loadActivityHistory();
      window.scrollTo({ top: 0, behavior: 'smooth' });
    }
  };
  controls.appendChild(prevBtn);
  
  // Page numbers
  for (let i = 0; i < Math.min(totalPages, 5); i++) {
    const pageBtn = document.createElement('button');
    pageBtn.textContent = i + 1;
    pageBtn.style.width = '40px';
    pageBtn.style.height = '40px';
    pageBtn.style.borderRadius = '6px';
    pageBtn.style.border = i === currentActivityPage ? '2px solid #059669' : '1px solid #ddd';
    pageBtn.style.backgroundColor = i === currentActivityPage ? '#059669' : '#fff';
    pageBtn.style.color = i === currentActivityPage ? '#fff' : '#059669';
    pageBtn.style.cursor = 'pointer';
    pageBtn.style.fontWeight = '600';
    pageBtn.onclick = () => {
      currentActivityPage = i;
      loadActivityHistory();
      window.scrollTo({ top: 0, behavior: 'smooth' });
    };
    controls.appendChild(pageBtn);
  }
  
  // Next button
  const nextBtn = document.createElement('button');
  nextBtn.innerHTML = 'Next <i class="fas fa-chevron-right"></i>';
  nextBtn.style.padding = '10px 18px';
  nextBtn.style.borderRadius = '6px';
  nextBtn.style.border = '1px solid #ddd';
  nextBtn.style.backgroundColor = pagination.has_more ? '#fff' : '#f3f4f6';
  nextBtn.style.cursor = pagination.has_more ? 'pointer' : 'not-allowed';
  nextBtn.style.color = pagination.has_more ? '#059669' : '#9ca3af';
  nextBtn.style.fontWeight = '600';
  nextBtn.disabled = !pagination.has_more;
  nextBtn.onclick = () => {
    if (pagination.has_more) {
      currentActivityPage++;
      loadActivityHistory();
      window.scrollTo({ top: 0, behavior: 'smooth' });
    }
  };
  controls.appendChild(nextBtn);
}

function filterActivityType(type) {
  currentActivityType = type;
  currentActivityPage = 0;
  
  // Update button states
  document.querySelectorAll('.activity-filter-btn').forEach(btn => {
    if (btn.dataset.type === type) {
      btn.style.backgroundColor = '#059669';
      btn.style.color = 'white';
      btn.style.borderColor = '#059669';
    } else {
      btn.style.backgroundColor = 'transparent';
      btn.style.color = '#059669';
      btn.style.borderColor = '#059669';
    }
  });
  
  loadActivityHistory();
}

// Load on page load
document.addEventListener('DOMContentLoaded', loadActivityHistory);
</script>

<?php };
include __DIR__ . '/../../partials/layout.php';
?>
