<?php
require_once __DIR__ . '/../config/auth.php';
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/functions.php';
requireLogin();
$uid = (int)$_SESSION['user_id'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Messages – RELINK</title>
<script>if(localStorage.getItem('theme')==='dark'){document.documentElement.classList.add('dark-mode-pre');document.body&&document.body.classList.add('dark-mode');}</script>
<link rel="stylesheet" href="/lostfound_relink/assets/css/style.css">
</head>
<body>
<div class="layout">
<?php include __DIR__ . '/../includes/user_sidebar.php'; ?>
<div class="main-content">
<?php include __DIR__ . '/../includes/topbar.php'; ?>

<div class="page-content msg-page" style="padding:0;height:calc(100vh - 65px);display:flex;">

  <!-- Conversation List -->
  <div class="msg-sidebar" id="msgSidebar">
    <div class="msg-sidebar-header">
      <span class="msg-sidebar-title">💬 Messages</span>
      <button class="btn btn-primary btn-sm" id="newChatBtn" title="New Conversation">✏️ New</button>
    </div>
    <div class="msg-search-wrap">
      <input type="text" class="form-control" id="convSearch" placeholder="🔍 Search conversations…">
    </div>
    <div class="msg-conv-list" id="convList">
      <div class="msg-empty-state">Loading…</div>
    </div>
  </div>

  <!-- Chat Window -->
  <div class="msg-chat" id="msgChat">
    <div class="msg-chat-empty" id="chatEmpty">
      <div class="msg-chat-empty-icon">💬</div>
      <div class="msg-chat-empty-title">Select a conversation</div>
      <div class="msg-chat-empty-sub">Choose from your existing conversations or start a new one.</div>
      <button class="btn btn-primary mt-16" id="newChatBtn2">✏️ Start New Chat</button>
    </div>

    <div class="msg-chat-inner" id="chatInner" style="display:none;">
      <div class="msg-chat-header" id="chatHeader"></div>
      <div class="msg-messages" id="msgMessages"></div>
      <div class="msg-input-bar">
        <textarea class="msg-input" id="msgInput" placeholder="Type a message…" rows="1"></textarea>
        <button class="msg-send-btn" id="sendBtn">➤</button>
      </div>
    </div>
  </div>

</div><!-- end page-content -->
</div><!-- end main-content -->
</div><!-- end layout -->

<!-- New Chat Modal -->
<div class="modal-overlay" id="newChatModal">
  <div class="modal" style="max-width:420px;">
    <div class="modal-header">
      <h3>✏️ New Conversation</h3>
      <button class="modal-close" onclick="closeModal('newChatModal')">×</button>
    </div>
    <div class="form-group">
      <label>Search user</label>
      <input type="text" class="form-control" id="userSearch" placeholder="Type a name…">
    </div>
    <div id="userSearchResults" class="msg-user-results"></div>
  </div>
</div>

<!-- Profile Modal -->
<div class="modal-overlay" id="profileModal">
  <div class="modal" style="max-width:360px;">
    <div class="modal-header">
      <h3>👤 Profile</h3>
      <button class="modal-close" onclick="closeModal('profileModal')">×</button>
    </div>
    <div id="profileModalBody" style="text-align:center;padding:8px 0 16px;"></div>
  </div>
</div>

<!-- Report Modal -->
<div class="modal-overlay" id="reportModal">
  <div class="modal" style="max-width:400px;">
    <div class="modal-header">
      <h3>🚨 Report Conversation</h3>
      <button class="modal-close" onclick="closeModal('reportModal')">×</button>
    </div>
    <input type="hidden" id="reportConvId">
    <input type="hidden" id="reportUserId">
    <div class="form-group">
      <label>Reason</label>
      <textarea class="form-control" id="reportReason" rows="3" placeholder="Describe the issue…"></textarea>
    </div>
    <button class="btn btn-danger btn-block" id="submitReportBtn">Submit Report</button>
  </div>
</div>

<script>
const ME = <?= $uid ?>;
const AJAX = '/lostfound_relink/messaging_ajax.php';
let activeConvId = null, pollTimer = null, lastMsgId = 0;

// ── Helpers ────────────────────────────────────────────────────────────────
function post(data) {
  return fetch(AJAX, { method:'POST', body: new URLSearchParams(data) }).then(r=>r.json());
}
function get(params) {
  return fetch(AJAX + '?' + new URLSearchParams(params)).then(r=>r.json()).catch(() => ({}));
}
function closeModal(id) { document.getElementById(id).classList.remove('open'); }
function openModal(id)  { document.getElementById(id).classList.add('open'); }
function timeAgo(ts) {
  const d = new Date(ts.replace(' ','T')), now = new Date();
  const diff = Math.floor((now - d) / 1000);
  if (diff < 60) return 'just now';
  if (diff < 3600) return Math.floor(diff/60) + 'm ago';
  if (diff < 86400) return Math.floor(diff/3600) + 'h ago';
  return d.toLocaleDateString();
}
function avatarHtml(name, avatar, size=32) {
  if (avatar) return `<img src="/lostfound_relink/${avatar}" class="msg-avatar" style="width:${size}px;height:${size}px;">`;
  return `<div class="msg-avatar-fallback" style="width:${size}px;height:${size}px;font-size:${Math.floor(size*0.4)}px;">${(name||'?')[0].toUpperCase()}</div>`;
}

// ── Load conversation list ─────────────────────────────────────────────────
function loadConversations() {
  get({ action:'list' }).then(data => {
    const list = document.getElementById('convList');
    if (data.error === 'unauthenticated') { list.innerHTML = '<div class="msg-empty-state">Session expired. Please <a href="/lostfound_relink/auth/login.php">log in</a>.</div>'; return; }
    if (!data.conversations || data.conversations.length === 0) {
      list.innerHTML = '<div class="msg-empty-state">No conversations yet.<br>Start a new chat!</div>';
      return;
    }
    const q = document.getElementById('convSearch').value.toLowerCase();
    const filtered = data.conversations.filter(c => !q || (c.other_name||'').toLowerCase().includes(q));
    list.innerHTML = filtered.map(c => `
      <div class="msg-conv-item ${c.id == activeConvId ? 'active' : ''}" data-id="${c.id}" data-other="${c.other_id||''}" data-name="${c.other_name||'Admin'}" data-avatar="${c.other_avatar||''}" style="position:relative;">
        <div class="msg-conv-avatar">${avatarHtml(c.other_name||'Admin', c.other_avatar, 40)}</div>
        <div class="msg-conv-info">
          <div class="msg-conv-name">${c.other_name || 'Admin'} ${c.type==='user_admin'?'<span class="badge badge-admin" style="font-size:10px;">Admin</span>':''}</div>
          <div class="msg-conv-last">${c.last_msg ? c.last_msg.substring(0,40)+(c.last_msg.length>40?'…':'') : 'No messages yet'}</div>
        </div>
        <div class="msg-conv-meta">
          <div class="msg-conv-time">${c.last_time ? timeAgo(c.last_time) : ''}</div>
          ${c.unread > 0 ? `<div class="msg-unread-badge">${c.unread}</div>` : ''}
        </div>
        <button class="msg-conv-delete-btn" data-id="${c.id}" title="Delete conversation" onclick="event.stopPropagation();">🗑️</button>
      </div>
    `).join('');
    list.querySelectorAll('.msg-conv-item').forEach(el => {
      el.addEventListener('click', () => openConversation(
        parseInt(el.dataset.id), el.dataset.name, el.dataset.avatar, parseInt(el.dataset.other)||null
      ));
      const deleteBtn = el.querySelector('.msg-conv-delete-btn');
      if (deleteBtn) {
        deleteBtn.addEventListener('click', (e) => {
          e.stopPropagation();
          deleteConversation(parseInt(deleteBtn.dataset.id));
        });
      }
    });
  });
}

// ── Open conversation ──────────────────────────────────────────────────────
function openConversation(cid, name, avatar, otherId) {
  activeConvId = cid;
  lastMsgId = 0;
  clearInterval(pollTimer);

  document.getElementById('chatEmpty').style.display = 'none';
  document.getElementById('chatInner').style.display = 'flex';

  document.getElementById('chatHeader').innerHTML = `
    <button class="msg-back-btn" id="msgBackBtn">◀</button>
    <div style="display:flex;align-items:center;gap:12px;flex:1;cursor:${otherId?'pointer':'default'};" ${otherId ? `onclick="viewProfile(${otherId})"` : ''}>
      ${avatarHtml(name, avatar, 38)}
      <div>
        <div style="font-weight:700;font-size:15px;">${name}</div>
        <div style="font-size:12px;color:var(--text-muted);">${otherId ? 'Click to view profile' : 'Active conversation'}</div>
      </div>
    </div>
    <button class="btn btn-sm" style="background:var(--text-muted);color:#fff;margin-right:8px;" onclick="event.stopPropagation();clearMessages(${cid})" title="Clear all messages">🗑️ Clear</button>
    ${otherId ? `<button class="btn btn-sm" style="background:var(--danger);color:#fff;" onclick="event.stopPropagation();openReport(${cid},${otherId})">🚨 Report</button>` : ''}
  `;

  document.getElementById('msgMessages').innerHTML = '';
  fetchMessages();
  pollTimer = setInterval(fetchMessages, 3000);
  loadConversations();

  // Mobile: slide chat in, sidebar out
  if (window.innerWidth <= 768) {
    document.getElementById('msgSidebar').classList.add('msg-slide-out');
    document.getElementById('msgChat').classList.add('msg-slide-in');
    history.pushState({ chat: true }, '');
  }

  document.getElementById('msgBackBtn').addEventListener('click', backToList);
}

function backToList() {
  document.getElementById('msgSidebar').classList.remove('msg-slide-out');
  document.getElementById('msgChat').classList.remove('msg-slide-in');
}

window.addEventListener('popstate', function(e) {
  if (document.getElementById('msgChat').classList.contains('msg-slide-in')) {
    backToList();
  }
});

// ── Fetch messages ─────────────────────────────────────────────────────────
function fetchMessages() {
  if (!activeConvId) return;
  get({ action:'fetch', conversation_id: activeConvId, after: lastMsgId }).then(data => {
    if (!data.messages || data.messages.length === 0) return;
    const container = document.getElementById('msgMessages');
    data.messages.forEach(m => {
      const isMine = m.sender_id == ME;
      const div = document.createElement('div');
      div.className = 'msg-bubble-wrap ' + (isMine ? 'mine' : 'theirs');
      div.dataset.msgId = m.id;
      div.innerHTML = `
        ${!isMine ? `<div class="msg-bubble-avatar">${avatarHtml(m.sender_name, m.sender_avatar, 28)}</div>` : ''}
        <div style="position:relative;">
          ${!isMine ? `<div class="msg-bubble-name">${m.sender_name}</div>` : ''}
          <div class="msg-bubble">${escHtml(m.message)}</div>
          <div class="msg-bubble-time">${timeAgo(m.created_at)} ${isMine ? (m.seen_status==='seen'?'&#10003;&#10003;':'&#10003;') : ''}</div>
          ${isMine ? `<button class="msg-delete-btn" data-id="${m.id}" title="Delete">&#128465;</button>` : ''}
        </div>
      `;
      container.appendChild(div);
      lastMsgId = Math.max(lastMsgId, parseInt(m.id));
    });
    container.querySelectorAll('.msg-delete-btn').forEach(btn => {
      btn.addEventListener('click', e => { e.stopPropagation(); deleteMessage(parseInt(btn.dataset.id), btn); });
    });
    container.scrollTop = container.scrollHeight;
  });
}

function deleteMessage(mid, btn) {
  if (!confirm('Delete this message?')) return;
  post({ action: 'delete_message', message_id: mid }).then(data => {
    if (data.ok) btn.closest('.msg-bubble-wrap').remove();
    else alert('Could not delete message.');
  });
}

function deleteConversation(cid) {
  if (!confirm('Delete this conversation? This cannot be undone.')) return;
  post({ action: 'delete_conversation', conversation_id: cid }).then(data => {
    if (data.ok) {
      if (activeConvId === cid) {
        // Close chat if we're currently viewing it
        document.getElementById('msgChat').classList.remove('msg-slide-in');
        document.getElementById('msgSidebar').classList.remove('msg-slide-out');
        document.getElementById('chatEmpty').style.display = 'flex';
        document.getElementById('chatInner').style.display = 'none';
        activeConvId = null;
        clearInterval(pollTimer);
      }
      loadConversations();
    } else {
      alert('Could not delete conversation.');
    }
  });
}

function clearMessages(cid) {
  if (!confirm('Delete all messages in this conversation? This cannot be undone.')) return;
  post({ action: 'clear_messages', conversation_id: cid }).then(data => {
    if (data.ok) {
      document.getElementById('msgMessages').innerHTML = '';
      fetchMessages();
    } else {
      alert('Could not clear messages.');
    }
  });
}

function escHtml(s) {
  return s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/\n/g,'<br>');
}

// ── Send message ───────────────────────────────────────────────────────────
document.getElementById('sendBtn').addEventListener('click', sendMessage);
document.getElementById('msgInput').addEventListener('keydown', e => {
  if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendMessage(); }
});
function sendMessage() {
  const input = document.getElementById('msgInput');
  const msg = input.value.trim();
  if (!msg || !activeConvId) return;
  input.value = '';
  input.style.height = 'auto';
  post({ action:'send', conversation_id: activeConvId, message: msg }).then(() => fetchMessages());
}

// Auto-resize textarea
document.getElementById('msgInput').addEventListener('input', function() {
  this.style.height = 'auto';
  this.style.height = Math.min(this.scrollHeight, 120) + 'px';
});

// ── New chat ───────────────────────────────────────────────────────────────
['newChatBtn','newChatBtn2'].forEach(id => {
  const el = document.getElementById(id);
  if (el) el.addEventListener('click', () => { openModal('newChatModal'); loadUserSearch(''); });
});

document.getElementById('userSearch').addEventListener('input', function() {
  loadUserSearch(this.value);
});

function loadUserSearch(q) {
  get({ action:'users_list', q }).then(data => {
    const res = document.getElementById('userSearchResults');
    if (!data.users || data.users.length === 0) {
      res.innerHTML = '<div class="msg-empty-state" style="padding:12px;">No users found</div>';
      return;
    }
    res.innerHTML = data.users.map(u => `
      <div class="msg-user-item" data-id="${u.id}" data-name="${u.name}" data-avatar="${u.avatar||''}" data-role="${u.role}">
        ${avatarHtml(u.name, u.avatar, 36)}
        <div>
          <div style="font-weight:600;font-size:14px;">${u.name}</div>
          <div style="font-size:12px;color:var(--text-muted);">${u.role}</div>
        </div>
      </div>
    `).join('');
    res.querySelectorAll('.msg-user-item').forEach(el => {
      el.addEventListener('click', () => {
        const type = el.dataset.role === 'admin' ? 'user_admin' : 'user_user';
        post({ action:'start_conversation', other_id: el.dataset.id, type }).then(data => {
          closeModal('newChatModal');
          document.getElementById('userSearch').value = '';
          openConversation(data.conversation_id, el.dataset.name, el.dataset.avatar, parseInt(el.dataset.id));
          loadConversations();
        });
      });
    });
  });
}

// ── View profile ──────────────────────────────────────────────────────────
function viewProfile(uid) {
  get({ action: 'get_profile', user_id: uid }).then(data => {
    if (!data.profile) return;
    const p = data.profile;
    const av = p.avatar
      ? `<img src="/lostfound_relink/${p.avatar}" style="width:80px;height:80px;border-radius:50%;object-fit:cover;border:3px solid var(--primary);margin-bottom:10px;">`
      : `<div class="msg-avatar-fallback" style="width:80px;height:80px;font-size:32px;margin:0 auto 10px;">${(p.name||'?')[0].toUpperCase()}</div>`;
    document.getElementById('profileModalBody').innerHTML = `
      ${av}
      <div style="font-weight:700;font-size:17px;margin-bottom:4px;">${p.name}</div>
      <div style="margin-bottom:6px;"><span class="badge badge-${p.role}">${p.role}</span></div>
      <div style="font-size:13px;color:var(--text-muted);margin-bottom:4px;">📧 ${p.email}</div>
      ${p.gender ? `<div style="font-size:13px;color:var(--text-muted);margin-bottom:4px;">${p.gender==='male'?'👨':'👩'} ${p.gender.charAt(0).toUpperCase()+p.gender.slice(1)}</div>` : ''}
      <div style="font-size:12px;color:var(--text-muted);margin-top:8px;">Member since ${new Date(p.created_at).toLocaleDateString('en-US',{year:'numeric',month:'long'})}</div>
    `;
    openModal('profileModal');
  });
}

// ── Report ─────────────────────────────────────────────────────────────────
function openReport(cid, uid) {
  document.getElementById('reportConvId').value = cid;
  document.getElementById('reportUserId').value = uid;
  document.getElementById('reportReason').value = '';
  openModal('reportModal');
}
document.getElementById('submitReportBtn').addEventListener('click', () => {
  const reason = document.getElementById('reportReason').value.trim();
  if (!reason) return alert('Please enter a reason.');
  post({
    action: 'report',
    conversation_id: document.getElementById('reportConvId').value,
    reported_user_id: document.getElementById('reportUserId').value,
    reason
  }).then(() => { closeModal('reportModal'); alert('Report submitted.'); });
});

// ── Search filter ──────────────────────────────────────────────────────────
document.getElementById('convSearch').addEventListener('input', loadConversations);



// ── Close modals on overlay click ─────────────────────────────────────────
document.querySelectorAll('.modal-overlay').forEach(el => {
  el.addEventListener('click', e => { if (e.target === el) el.classList.remove('open'); });
});

// ── Init ───────────────────────────────────────────────────────────────────
loadConversations();
setInterval(loadConversations, 10000);

// Auto-open conversation from browse redirect
(function() {
    const params = new URLSearchParams(window.location.search);
    const convId = params.get('conv');
    if (convId) {
        // Wait for list to load then open
        setTimeout(() => {
            get({ action: 'list' }).then(data => {
                if (!data.conversations) return;
                const c = data.conversations.find(x => String(x.id) === String(convId));
                if (c) openConversation(parseInt(c.id), c.other_name || 'User', c.other_avatar || '', parseInt(c.other_id) || null);
            });
        }, 400);
    }
})();
</script>
<script src="/lostfound_relink/assets/js/main.js"></script>
</body>
</html>
