<?php
require_once __DIR__ . '/../../api/lib.php';
hw_require_auth(['client']);
$authUser = hw_get_auth_user();

// CHECK MEMBERSHIP
$db = hw_db();
$membershipStmt = $db->prepare("SELECT id, plan_type, expires_at FROM user_memberships WHERE user_id = ? AND status = 'active' AND expires_at > NOW() LIMIT 1");
$membershipStmt->execute([$authUser['id']]);
if (!$membershipStmt->fetch()) {
    header('Location: /files/atasteofafricanmarketplace/dashboard/user/choose-plan.php');
    exit;
}

$page_title = 'Messages | Wellness Dashboard';
$page_description = 'Communicate with your wellness coach';
$page_content = function () use ($authUser) {
?>
<style>
  nav.fixed { 
    display: none !important; 
    visibility: hidden !important;
    position: absolute !important;
    pointer-events: none !important;
    z-index: -1 !important;
  }
  body > nav { 
    display: none !important; 
    visibility: hidden !important;
  }
  body {
    padding-top: 0 !important;
  }
</style>
<link rel="stylesheet" href="/files/atasteofafricanmarketplace/assets/dashboard.css">

<div class="dashboard-container">
  <!-- Sidebar -->
  <div class="dashboard-sidebar">
    <div class="sidebar-header">
      <div class="sidebar-profile">
        <div class="profile-avatar">
          <?= strtoupper(substr($authUser['first_name'], 0, 1) . substr($authUser['last_name'], 0, 1)) ?>
        </div>
        <div class="profile-info">
          <h3><?= htmlspecialchars($authUser['first_name'] . ' ' . $authUser['last_name']) ?></h3>
          <p>Wellness Member</p>
        </div>
      </div>
    </div>
    <nav class="sidebar-nav">
      <a href="/files/atasteofafricanmarketplace/dashboard/user/index.php"><i class="fas fa-home"></i>Home</a>
      <a href="/files/atasteofafricanmarketplace/dashboard/user/appointments.php"><i class="fas fa-calendar-check"></i>Appointments</a>
      <a href="/files/atasteofafricanmarketplace/dashboard/user/messages.php" class="active"><i class="fas fa-comments"></i>Messages</a>
      <a href="/files/atasteofafricanmarketplace/dashboard/user/records.php"><i class="fas fa-file-medical"></i>Records</a>
      <a href="/files/atasteofafricanmarketplace/dashboard/user/profile.php"><i class="fas fa-user"></i>Profile & Support</a>
      <hr class="sidebar-divider">
      <a href="/files/atasteofafricanmarketplace/store.php"><i class="fas fa-store"></i>Wellness Store</a>
      <a href="/files/atasteofafricanmarketplace/dashboard/user/billing.php"><i class="fas fa-file-invoice-dollar"></i>Billing</a>
      <hr class="sidebar-divider">
      <a href="/files/atasteofafricanmarketplace/index.php"><i class="fas fa-arrow-left"></i>Back to Home</a>
    </nav>
    <div class="sidebar-footer">
      <a href="/files/atasteofafricanmarketplace/api/auth/logout.php" style="display: flex; align-items: center; gap: 12px; color: rgba(255,255,255,0.7); text-decoration: none; font-size: 13px; font-weight: 500; padding: 10px 0; border-top: 1px solid rgba(212, 173, 49, 0.15); transition: all 0.3s;"><i class="fas fa-sign-out-alt"></i>Sign Out</a>
    </div>
  </div>

  <!-- Main Content -->
  <div class="dashboard-content">
    <main>
      <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 32px; flex-wrap: wrap; gap: 16px;">
        <div>
          <h1 style="font-size: 32px; font-weight: 800; color: #0b3d2e; margin: 0 0 8px 0;">Messages</h1>
          <p style="font-size: 16px; color: #64748b; margin: 0;">Chat with your wellness coaches and support team</p>
        </div>
        <button onclick="startNewConversation()" style="display: flex; align-items: center; gap: 10px; background: linear-gradient(135deg, #0f5240, #146651); color: white; padding: 14px 24px; border-radius: 12px; font-size: 15px; font-weight: 700; border: none; cursor: pointer; box-shadow: 0 6px 16px rgba(15, 82, 64, 0.3); transition: all 0.3s;">
          <i class="fas fa-plus"></i>
          <span>New Message</span>
        </button>
      </div>

      <!-- Messaging Container -->
      <div style="display: grid; grid-template-columns: 350px 1fr; gap: 24px; height: calc(100vh - 250px); min-height: 600px;">
        
        <!-- Conversations List -->
        <div style="background: white; border-radius: 16px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05); display: flex; flex-direction: column; overflow: hidden;">
          <div style="padding: 20px; border-bottom: 2px solid #f0f9f6;">
            <h3 style="font-size: 18px; font-weight: 700; color: #0b3d2e; margin: 0 0 12px 0;">Conversations</h3>
            <div style="position: relative;">
              <input type="text" id="search-conversations" placeholder="Search messages..." 
                     style="width: 100%; padding: 10px 10px 10px 36px; border: 2px solid #e5e7eb; border-radius: 8px; font-size: 14px; transition: all 0.3s;" 
                     onkeyup="searchConversations(this.value)">
              <i class="fas fa-search" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #64748b;"></i>
            </div>
          </div>
          
          <div id="conversations-list" style="flex: 1; overflow-y: auto; padding: 8px;">
            <div style="text-align: center; padding: 40px 20px; color: #64748b;">
              <i class="fas fa-spinner fa-spin" style="font-size: 32px; color: #0f5240; margin-bottom: 12px;"></i>
              <p style="margin: 0;">Loading conversations...</p>
            </div>
          </div>
        </div>

        <!-- Message Thread -->
        <div id="message-thread-container" style="background: white; border-radius: 16px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05); display: flex; flex-direction: column; overflow: hidden;">
          <!-- Empty State -->
          <div id="empty-state" style="flex: 1; display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 40px;">
            <div style="width: 120px; height: 120px; background: linear-gradient(135deg, #f0f9f6, #fef9e7); border-radius: 50%; display: flex; align-items: center; justify-content: center; margin-bottom: 24px;">
              <i class="fas fa-comments" style="font-size: 48px; color: #0f5240;"></i>
            </div>
            <h3 style="font-size: 22px; color: #0b3d2e; margin: 0 0 12px 0; font-weight: 700;">Select a conversation</h3>
            <p style="color: #64748b; text-align: center; max-width: 400px; margin: 0;">
              Choose a conversation from the left or start a new one to begin messaging with your wellness coach.
            </p>
          </div>

          <!-- Message Thread (hidden initially) -->
          <div id="active-thread" style="display: none; flex: 1; flex-direction: column;">
            <!-- Thread Header -->
            <div id="thread-header" style="padding: 20px 24px; border-bottom: 2px solid #f0f9f6; display: flex; align-items: center; gap: 16px; background: linear-gradient(135deg, #f0f9f6, #fef9e7);">
              <!-- Will be populated dynamically -->
            </div>

            <!-- Messages Area -->
            <div id="messages-area" style="flex: 1; overflow-y: auto; padding: 24px; background: #fafafa; display: flex; flex-direction: column; gap: 16px;">
              <!-- Messages will be loaded here -->
            </div>

            <!-- Message Input -->
            <div style="padding: 20px 24px; border-top: 2px solid #f0f9f6; background: white;">
              <form id="message-form" onsubmit="sendMessage(event)" style="display: flex; gap: 12px; align-items: flex-end;">
                <div style="flex: 1;">
                  <textarea id="message-input" placeholder="Type your message..." 
                            style="width: 100%; padding: 12px 16px; border: 2px solid #e5e7eb; border-radius: 12px; font-size: 14px; resize: none; font-family: inherit; transition: all 0.3s; min-height: 48px; max-height: 120px;" 
                            rows="1" 
                            onkeydown="handleMessageKeydown(event)"
                            oninput="autoResizeTextarea(this)"></textarea>
                </div>
                <button type="submit" style="background: linear-gradient(135deg, #0f5240, #146651); color: white; padding: 12px 24px; border-radius: 12px; font-size: 15px; font-weight: 700; border: none; cursor: pointer; display: flex; align-items: center; gap: 8px; height: 48px; transition: all 0.3s; box-shadow: 0 4px 12px rgba(15, 82, 64, 0.3);">
                  <span>Send</span>
                  <i class="fas fa-paper-plane"></i>
                </button>
              </form>
              <div style="display: flex; gap: 16px; margin-top: 12px; padding-top: 12px; border-top: 1px solid #f0f9f6;">
                <button onclick="attachFile()" style="background: none; border: none; color: #64748b; cursor: pointer; font-size: 13px; display: flex; align-items: center; gap: 6px; transition: all 0.3s;">
                  <i class="fas fa-paperclip"></i>
                  <span>Attach</span>
                </button>
                <button onclick="insertEmoji()" style="background: none; border: none; color: #64748b; cursor: pointer; font-size: 13px; display: flex; align-items: center; gap: 6px; transition: all 0.3s;">
                  <i class="fas fa-smile"></i>
                  <span>Emoji</span>
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
  </div>
</div>

<style>
#conversations-list::-webkit-scrollbar,
#messages-area::-webkit-scrollbar {
  width: 6px;
}

#conversations-list::-webkit-scrollbar-track,
#messages-area::-webkit-scrollbar-track {
  background: #f0f9f6;
}

#conversations-list::-webkit-scrollbar-thumb,
#messages-area::-webkit-scrollbar-thumb {
  background: #d4ad31;
  border-radius: 3px;
}

.conversation-item {
  padding: 14px;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s;
  margin-bottom: 8px;
  border: 2px solid transparent;
}

.conversation-item:hover {
  background: #f0f9f6;
  border-color: #d4ad31;
}

.conversation-item.active {
  background: linear-gradient(135deg, #f0f9f6, #fef9e7);
  border-color: #0f5240;
}

.message-bubble {
  max-width: 70%;
  padding: 12px 16px;
  border-radius: 16px;
  word-wrap: break-word;
  animation: slideIn 0.3s ease;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.message-sent {
  background: linear-gradient(135deg, #0f5240, #146651);
  color: white;
  align-self: flex-end;
  border-bottom-right-radius: 4px;
}

.message-received {
  background: white;
  color: #0b3d2e;
  align-self: flex-start;
  border-bottom-left-radius: 4px;
  border: 1px solid #e5e7eb;
}

#message-input:focus {
  border-color: #0f5240;
  outline: none;
}

button:hover {
  transform: translateY(-2px);
}

button:active {
  transform: translateY(0);
}
</style>

<script>
let currentConversationId = null;
let currentCoachId = null;
let messagesPollingInterval = null;
let allConversations = [];

// Auto-resize textarea
function autoResizeTextarea(textarea) {
  textarea.style.height = '48px';
  textarea.style.height = Math.min(textarea.scrollHeight, 120) + 'px';
}

// Handle Enter key for sending
function handleMessageKeydown(event) {
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault();
    sendMessage(event);
  }
}

// Load conversations
async function loadConversations() {
  try {
    const response = await fetch('/files/atasteofafricanmarketplace/api/messages/conversations.php', {
      credentials: 'include'
    });
    
    const data = await response.json();
    const list = document.getElementById('conversations-list');
    
    if (data.conversations && data.conversations.length > 0) {
      allConversations = data.conversations;
      renderConversations(data.conversations);
    } else {
      list.innerHTML = `
        <div style="text-align: center; padding: 40px 20px; color: #64748b;">
          <i class="fas fa-inbox" style="font-size: 48px; color: #d4ad31; margin-bottom: 12px; display: block;"></i>
          <p style="margin: 0; font-size: 14px;">No conversations yet</p>
          <button onclick="startNewConversation()" style="margin-top: 16px; background: #0f5240; color: white; padding: 8px 16px; border: none; border-radius: 8px; cursor: pointer; font-size: 13px; font-weight: 600;">
            Start Chatting
          </button>
        </div>
      `;
    }
  } catch (error) {
    console.error('Error loading conversations:', error);
    document.getElementById('conversations-list').innerHTML = `
      <div style="text-align: center; padding: 40px 20px; color: #ef4444;">
        <i class="fas fa-exclamation-circle" style="font-size: 48px; margin-bottom: 12px; display: block;"></i>
        <p style="margin: 0;">Error loading messages</p>
      </div>
    `;
  }
}

// Render conversations
function renderConversations(conversations) {
  const list = document.getElementById('conversations-list');
  list.innerHTML = conversations.map(conv => {
    const isActive = conv.id === currentConversationId;
    const lastMessageTime = new Date(conv.last_message_time);
    const timeAgo = formatTimeAgo(lastMessageTime);
    
    return `
      <div class="conversation-item ${isActive ? 'active' : ''}" onclick="openConversation(${conv.id}, ${conv.coach_id}, '${conv.coach_name}')">
        <div style="display: flex; gap: 12px; align-items: center;">
          <div style="position: relative; flex-shrink: 0;">
            <div style="width: 48px; height: 48px; border-radius: 12px; background: linear-gradient(135deg, #d4ad31, #c9a227); display: flex; align-items: center; justify-content: center; color: white; font-size: 18px; font-weight: bold;">
              ${conv.coach_name.charAt(0).toUpperCase()}
            </div>
            ${conv.is_online ? `
              <div style="position: absolute; bottom: 0; right: 0; width: 14px; height: 14px; background: #10b981; border: 2px solid white; border-radius: 50%;"></div>
            ` : ''}
          </div>
          <div style="flex: 1; min-width: 0;">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 4px;">
              <h4 style="font-size: 15px; font-weight: 700; color: #0b3d2e; margin: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
                ${conv.coach_name}
              </h4>
              ${conv.unread_count > 0 ? `
                <span style="background: #ef4444; color: white; padding: 2px 8px; border-radius: 10px; font-size: 11px; font-weight: 700;">
                  ${conv.unread_count}
                </span>
              ` : ''}
            </div>
            <p style="font-size: 13px; color: #64748b; margin: 0 0 4px 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
              ${conv.last_message || 'No messages yet'}
            </p>
            <span style="font-size: 11px; color: #94a3b8;">
              ${timeAgo}
            </span>
          </div>
        </div>
      </div>
    `;
  }).join('');
}

// Search conversations
function searchConversations(query) {
  const filtered = allConversations.filter(conv => 
    conv.coach_name.toLowerCase().includes(query.toLowerCase()) ||
    (conv.last_message && conv.last_message.toLowerCase().includes(query.toLowerCase()))
  );
  renderConversations(filtered);
}

// Open conversation
async function openConversation(conversationId, coachId, coachName) {
  currentConversationId = conversationId;
  currentCoachId = coachId;
  
  // Hide empty state, show thread
  document.getElementById('empty-state').style.display = 'none';
  document.getElementById('active-thread').style.display = 'flex';
  
  // Update header
  document.getElementById('thread-header').innerHTML = `
    <div style="width: 56px; height: 56px; border-radius: 12px; background: linear-gradient(135deg, #d4ad31, #c9a227); display: flex; align-items: center; justify-content: center; color: white; font-size: 24px; font-weight: bold;">
      ${coachName.charAt(0).toUpperCase()}
    </div>
    <div style="flex: 1;">
      <h3 style="font-size: 18px; font-weight: 700; color: #0b3d2e; margin: 0 0 4px 0;">${coachName}</h3>
      <p style="font-size: 13px; color: #64748b; margin: 0; display: flex; align-items: center; gap: 6px;">
        <i class="fas fa-circle" style="font-size: 6px; color: #10b981;"></i>
        <span>Wellness Coach</span>
      </p>
    </div>
    <button onclick="viewCoachProfile(${coachId})" style="background: white; border: 2px solid #0f5240; color: #0f5240; padding: 10px 20px; border-radius: 10px; font-size: 13px; font-weight: 600; cursor: pointer; transition: all 0.3s;">
      <i class="fas fa-user"></i> View Profile
    </button>
  `;
  
  // Load messages
  await loadMessages();
  
  // Update conversation list
  document.querySelectorAll('.conversation-item').forEach(item => {
    item.classList.remove('active');
  });
  event.currentTarget.classList.add('active');
  
  // Start polling for new messages
  if (messagesPollingInterval) {
    clearInterval(messagesPollingInterval);
  }
  messagesPollingInterval = setInterval(loadMessages, 5000); // Poll every 5 seconds
}

// Load messages
async function loadMessages() {
  if (!currentConversationId) return;
  
  try {
    const response = await fetch(`/files/atasteofafricanmarketplace/api/messages/list.php?conversation_id=${currentConversationId}`, {
      credentials: 'include'
    });
    
    const data = await response.json();
    const messagesArea = document.getElementById('messages-area');
    
    if (data.messages && data.messages.length > 0) {
      const shouldScroll = messagesArea.scrollHeight - messagesArea.scrollTop === messagesArea.clientHeight;
      
      messagesArea.innerHTML = data.messages.map(msg => {
        const isSent = msg.sender_type === 'client';
        const time = new Date(msg.created_at);
        
        return `
          <div style="display: flex; flex-direction: column; ${isSent ? 'align-items: flex-end;' : 'align-items: flex-start;'}">
            <div class="message-bubble ${isSent ? 'message-sent' : 'message-received'}">
              <p style="margin: 0; font-size: 14px; line-height: 1.5;">${escapeHtml(msg.message)}</p>
              <span style="font-size: 11px; margin-top: 6px; display: block; opacity: 0.7;">
                ${time.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' })}
              </span>
            </div>
          </div>
        `;
      }).join('');
      
      if (shouldScroll || messagesArea.children.length === data.messages.length) {
        messagesArea.scrollTop = messagesArea.scrollHeight;
      }
    } else {
      messagesArea.innerHTML = `
        <div style="text-align: center; padding: 40px; color: #64748b;">
          <i class="fas fa-comment-dots" style="font-size: 48px; color: #d4ad31; margin-bottom: 12px; display: block;"></i>
          <p style="margin: 0;">No messages yet. Start the conversation!</p>
        </div>
      `;
    }
  } catch (error) {
    console.error('Error loading messages:', error);
  }
}

// Send message
async function sendMessage(event) {
  event.preventDefault();
  
  const input = document.getElementById('message-input');
  const message = input.value.trim();
  
  if (!message || !currentConversationId) return;
  
  try {
    const response = await fetch('/files/atasteofafricanmarketplace/api/messages/send.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'include',
      body: JSON.stringify({
        conversation_id: currentConversationId,
        coach_id: currentCoachId,
        message: message
      })
    });
    
    const data = await response.json();
    
    if (data.success) {
      input.value = '';
      input.style.height = '48px';
      await loadMessages();
      await loadConversations();
    } else {
      alert('Failed to send message. Please try again.');
    }
  } catch (error) {
    console.error('Error sending message:', error);
    alert('Error sending message. Please check your connection.');
  }
}

// Start new conversation
async function startNewConversation() {
  // For now, redirect to coaches page to select a coach
  window.location.href = '/files/atasteofafricanmarketplace/all-coaches.php';
}

// Helper functions
function formatTimeAgo(date) {
  const seconds = Math.floor((new Date() - date) / 1000);
  
  if (seconds < 60) return 'Just now';
  if (seconds < 3600) return Math.floor(seconds / 60) + 'm ago';
  if (seconds < 86400) return Math.floor(seconds / 3600) + 'h ago';
  if (seconds < 604800) return Math.floor(seconds / 86400) + 'd ago';
  
  return date.toLocaleDateString();
}

function escapeHtml(text) {
  const div = document.createElement('div');
  div.textContent = text;
  return div.innerHTML;
}

function viewCoachProfile(coachId) {
  alert('Coach profile feature coming soon!');
}

function attachFile() {
  alert('File attachment feature coming soon!');
}

function insertEmoji() {
  const emojis = ['😊', '👍', '❤️', '🙏', '💚', '✨', '🌿', '💪'];
  const emoji = emojis[Math.floor(Math.random() * emojis.length)];
  const input = document.getElementById('message-input');
  input.value += emoji;
  input.focus();
}

// Initialize
loadConversations();

// Cleanup on page unload
window.addEventListener('beforeunload', () => {
  if (messagesPollingInterval) {
    clearInterval(messagesPollingInterval);
  }
});
</script>

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