<?php
require_once __DIR__ . '/../config/auth.php';
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/functions.php';
requireAdmin();
$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 Admin</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="<?= BASE_URL ?>/assets/css/style.css">
</head>
<body>
<div class="layout">
<?php include __DIR__ . '/../includes/admin_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;">

  <!-- Sidebar -->
  <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">New</button>
    </div>
    <div class="msg-tabs">
      <button class="msg-tab active" data-tab="inbox">Inbox</button>
      <button class="msg-tab" data-tab="reported">Reported</button>
    </div>
    <div class="msg-tab-content" id="tab-inbox">
      <div class="msg-search-wrap">
        <input type="text" class="form-control" id="convSearch" placeholder="Search...">
      </div>
      <div class="msg-conv-list" id="convList">
        <div class="msg-empty-state">Loading...</div>
      </div>
    </div>
    <div class="msg-tab-content" id="tab-reported" style="display:none;">
      <div class="msg-conv-list" id="reportedList">
        <div class="msg-empty-state">Loading...</div>
      </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">Admin Messaging</div>
      <div class="msg-chat-empty-sub">Select a conversation to view messages, assist users, or moderate reported chats.</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" id="msgInputBar">
        <textarea class="msg-input" id="msgInput" placeholder="Type a message..." rows="1"></textarea>
        <button class="msg-send-btn" id="sendBtn">&#10148;</button>
      </div>
    </div>
  </div>

</div>
</div>
</div>

<!-- Report Decision Modal -->
<div class="modal-overlay" id="reportDecisionModal">
  <div class="modal" style="max-width:440px;" onclick="event.stopPropagation()">
    <div class="modal-header">
      <h3>🚨 Handle Report</h3>
      <button class="modal-close" id="closeDecisionModal">×</button>
    </div>
    <div id="reportDecisionInfo" style="background:var(--bg-secondary);border-radius:8px;padding:12px 14px;margin-bottom:18px;font-size:13px;"></div>
    <input type="hidden" id="decisionReportId">
    <div style="display:flex;flex-direction:column;gap:10px;">
      <div style="border:1.5px solid var(--border);border-radius:10px;padding:14px;">
        <div style="font-weight:700;font-size:13px;margin-bottom:8px;color:var(--danger)">✅ Approve Report — Take Action</div>
        <div style="display:flex;gap:8px;flex-wrap:wrap;">
          <button class="btn btn-sm btn-warning" id="btnSuspend">⏸ Suspend User</button>
          <button class="btn btn-sm btn-danger" id="btnBan">🚫 Ban User</button>
        </div>
      </div>
      <div style="border:1.5px solid var(--border);border-radius:10px;padding:14px;">
        <div style="font-weight:700;font-size:13px;margin-bottom:8px;color:var(--warning)">⚠️ Warn User — Minor Violation</div>
        <button class="btn btn-sm btn-secondary" id="btnWarn">📢 Send Warning</button>
      </div>
      <div style="border:1.5px solid var(--border);border-radius:10px;padding:14px;">
        <div style="font-weight:700;font-size:13px;margin-bottom:8px;color:var(--text-muted)">❌ Reject Report — No Action</div>
        <button class="btn btn-sm btn-light" id="btnReject">Close Case</button>
      </div>
    </div>
  </div>
</div>

<!-- Profile Modal -->
<div class="modal-overlay" id="profileModal">
  <div class="modal" style="max-width:360px;" onclick="event.stopPropagation()">
    <div class="modal-header">
      <h3>👤 User 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>

<!-- New Chat Modal -->
<div class="modal-overlay" id="newChatModal">
  <div class="modal" style="max-width:420px;" onclick="event.stopPropagation()">
    <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>

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

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="<?= BASE_URL ?>/${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>`;
}
function escHtml(s) {
  return s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/\n/g,'<br>');
}

// ── Decision modal buttons ─────────────────────────────────────────────────
document.getElementById('closeDecisionModal').addEventListener('click', () => closeModal('reportDecisionModal'));
document.getElementById('btnSuspend').addEventListener('click', () => submitDecision('approve', 'suspend'));
document.getElementById('btnBan').addEventListener('click',     () => submitDecision('approve', 'ban'));
document.getElementById('btnWarn').addEventListener('click',    () => submitDecision('warn', ''));
document.getElementById('btnReject').addEventListener('click',  () => submitDecision('reject', ''));

function openDecision(rid) {
  const r = reportsData[rid];
  if (!r) return;
  document.getElementById('decisionReportId').value = rid;
  document.getElementById('reportDecisionInfo').innerHTML =
    `<div style="margin-bottom:6px;">🚨 <strong>${escHtml(r.reporter_name)}</strong> reported <strong>${escHtml(r.reported_name)}</strong></div>
     <div style="color:var(--text-muted);font-size:12px;">Reason: ${escHtml(r.reason)}</div>`;
  openModal('reportDecisionModal');
}

function submitDecision(decision, subAction) {
  const rid = document.getElementById('decisionReportId').value;
  if (!rid) return;
  post({ action: 'report_action', report_id: rid, decision: decision, sub_action: subAction })
    .then(data => {
      if (data.error) { alert('Error: ' + data.error); return; }
      closeModal('reportDecisionModal');
      const labels = { suspended: 'User suspended.', banned: 'User banned.', warned: 'Warning sent.', rejected: 'Report closed.' };
      alert(labels[data.result] || 'Done.');
      loadReported();
    })
    .catch(() => alert('Request failed. Please try again.'));
}

// ── Tabs ───────────────────────────────────────────────────────────────────
document.querySelectorAll('.msg-tab').forEach(tab => {
  tab.addEventListener('click', function() {
    document.querySelectorAll('.msg-tab').forEach(t => t.classList.remove('active'));
    document.querySelectorAll('.msg-tab-content').forEach(t => t.style.display = 'none');
    this.classList.add('active');
    document.getElementById('tab-' + this.dataset.tab).style.display = 'block';
    if (this.dataset.tab === 'reported') loadReported();
  });
});

// ── Load conversations ─────────────────────────────────────────────────────
function loadConversations() {
  get({ action:'list' }).then(data => {
    const list = document.getElementById('convList');
    if (!data.conversations || data.conversations.length === 0) {
      list.innerHTML = '<div class="msg-empty-state">No conversations yet.</div>';
      return;
    }
    const q = (document.getElementById('convSearch').value || '').toLowerCase();
    const filtered = data.conversations.filter(c => !q || (c.participants||'').toLowerCase().includes(q));
    list.innerHTML = filtered.map(c => `
      <div class="msg-conv-item ${c.id == activeConvId ? 'active' : ''}" data-id="${c.id}" data-name="${c.participants||'Users'}" data-avatar="${c.other_avatar||''}" data-other="${c.other_id||''}" style="position:relative;">
        <div class="msg-conv-avatar">${avatarHtml(c.participants, c.other_avatar, 40)}</div>
        <div class="msg-conv-info">
          <div class="msg-conv-name">${c.participants||'Conversation'} <span class="badge badge-${c.type==='user_admin'?'admin':'user'}" style="font-size:10px;">${c.type.replace('_',' ')}</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, false));
      const deleteBtn = el.querySelector('.msg-conv-delete-btn');
      if (deleteBtn) {
        deleteBtn.addEventListener('click', (e) => {
          e.stopPropagation();
          deleteConversation(parseInt(deleteBtn.dataset.id));
        });
      }
    });
  });
}

// ── Load reported ──────────────────────────────────────────────────────────
function loadReported() {
  get({ action:'reported_list' }).then(data => {
    const list = document.getElementById('reportedList');
    if (!data.reports || data.reports.length === 0) {
      list.innerHTML = '<div class="msg-empty-state">No reported conversations.</div>';
      return;
    }
    reportsData = {};
    data.reports.forEach(r => { reportsData[r.id] = r; });
    list.innerHTML = data.reports.map(r => `
      <div class="msg-conv-item" style="flex-direction:column;align-items:flex-start;gap:6px;padding:14px 16px;">
        <div style="display:flex;align-items:center;gap:8px;width:100%;">
          <span style="font-size:18px;">🚨</span>
          <div style="flex:1;min-width:0;">
            <div class="msg-conv-name" style="font-size:13px;">
              <strong>${escHtml(r.reporter_name)}</strong> reported <strong>${escHtml(r.reported_name)}</strong>
            </div>
            <div class="msg-conv-last">${escHtml(r.reason.substring(0,55))}${r.reason.length>55?'…':''}</div>
          </div>
          <span class="badge badge-${r.status==='pending'?'pending':r.admin_decision==='banned'?'rejected':r.admin_decision==='suspended'?'pending':r.admin_decision==='warned'?'matched':'approved'}" style="font-size:10px;white-space:nowrap;">
            ${r.admin_decision ? r.admin_decision : r.status}
          </span>
        </div>
        <div style="display:flex;gap:8px;padding-left:26px;flex-wrap:wrap;">
          <button class="btn btn-sm btn-primary" data-conv="${r.conversation_id}">View Chat</button>
          ${r.status==='pending' ? `<button class="btn btn-sm btn-danger" data-rid="${r.id}">⚖️ Decide</button>` : ''}
        </div>
      </div>
    `).join('');
    list.querySelectorAll('[data-conv]').forEach(btn => {
      btn.addEventListener('click', () => openConversation(parseInt(btn.dataset.conv), 'Reported Chat', '', null, true));
    });
    list.querySelectorAll('[data-rid]').forEach(btn => {
      btn.addEventListener('click', () => openDecision(btn.dataset.rid));
    });
  });
}

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

  document.getElementById('chatEmpty').style.display = 'none';
  document.getElementById('chatInner').style.display = 'flex';
  document.getElementById('msgInputBar').style.display = readOnly ? 'none' : 'flex';

  const headerAvatar = otherId ? avatarHtml(name, avatar, 38) : `<div class="msg-avatar-fallback" style="width:38px;height:38px;font-size:16px;">💬</div>`;
  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})"`:''}>
      ${headerAvatar}
      <div>
        <div style="font-weight:700;font-size:15px;">${escHtml(name)}</div>
        <div style="font-size:12px;color:var(--text-muted);">${readOnly ? '🔍 Read-only — Reported conversation' : (otherId ? 'Click to view profile' : 'Admin view')}</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>
    ${readOnly ? '<span class="badge badge-rejected" style="font-size:11px;">🚨 Reported</span>' : '<span class="badge badge-admin">Admin</span>'}
  `;

  document.getElementById('msgMessages').innerHTML = '';
  fetchMessages(readOnly);
  if (!readOnly) pollTimer = setInterval(() => fetchMessages(false), 3000);
  loadConversations();

  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() {
  if (document.getElementById('msgChat').classList.contains('msg-slide-in')) backToList();
});

// ── Fetch messages ─────────────────────────────────────────────────────────
function fetchMessages(readOnly) {
  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 = !readOnly && m.sender_id == ME;
      const div = document.createElement('div');
      div.className = 'msg-bubble-wrap ' + (isMine ? 'mine' : 'theirs');
      div.dataset.msgId = m.id;
      div.innerHTML = `
        <div class="msg-bubble-avatar">${avatarHtml(m.sender_name, m.sender_avatar, 28)}</div>
        <div style="position:relative;">
          <div class="msg-bubble-name">${escHtml(m.sender_name)}</div>
          <div class="msg-bubble" style="${readOnly?'background:var(--white);border:1px solid var(--border);color:var(--text);':''}">${escHtml(m.message)}</div>
          <div class="msg-bubble-time">${timeAgo(m.created_at)} ${isMine ? (m.seen_status==='seen'?'&#10003;&#10003;':'&#10003;') : ''}</div>
          <button class="msg-delete-btn" data-id="${m.id}" title="Delete message">&#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(false);
    } else {
      alert('Could not clear messages.');
    }
  });
}

// ── 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(false));
}
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;">${escHtml(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), false);
          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="<?= BASE_URL ?>/${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;">${escHtml(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;">📧 ${escHtml(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');
  });
}

// ── Search + modal overlay close ───────────────────────────────────────────
document.getElementById('convSearch').addEventListener('input', loadConversations);
document.querySelectorAll('.modal-overlay').forEach(el => {
  el.addEventListener('click', e => { if (e.target === el) el.classList.remove('open'); });
});

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

(function() {
  const params = new URLSearchParams(window.location.search);
  const convId = params.get('conv');
  if (convId) {
    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.participants || 'Conversation', c.other_avatar || '', parseInt(c.other_id)||null, false);
      });
    }, 400);
  }
})();
</script>
<script src="<?= BASE_URL ?>/assets/js/main.js"></script>
</body>
</html>
