<?php
if (session_status() === PHP_SESSION_NONE) session_start();
if (!isset($_SESSION['user_id'])) { header('Location: index.php'); exit; }
require_once 'config.php';
requireModule('communication');
$conn = getDBConnection();
$allowed = ['admin','headteacher','director','registrar','supervisor','teacher','staff'];
if (!in_array($_SESSION['role'] ?? '', $allowed, true)) {
    header('Location: dashboard.php?error=access_denied'); exit;
}
$can_manage = in_array($_SESSION['role'] ?? '', ['admin','headteacher','director','registrar'], true);
$role = $_SESSION['role'] ?? '';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Communication — EduTrack</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<style>
.msg-list-item { cursor: pointer; border-left: 3px solid transparent; transition: all .15s; }
.msg-list-item:hover { background: #f8fafc; border-left-color: #0d6efd; }
.msg-list-item.unread { border-left-color: #0d6efd; font-weight: 600; background: #f0f7ff; }
.msg-list-item.active  { background: #e8f4ff; border-left-color: #0d6efd; }
.thread-bubble { max-width: 70%; }
.thread-bubble.mine { margin-left: auto; }
.thread-bubble .bubble-body { padding: 10px 14px; border-radius: 12px; font-size: .9rem; }
.thread-bubble.mine  .bubble-body { background: #0d6efd; color: #fff; border-bottom-right-radius: 2px; }
.thread-bubble.theirs .bubble-body { background: #f1f5f9; color: #1e293b; border-bottom-left-radius: 2px; }
.bubble-meta { font-size: .72rem; color: #94a3b8; margin-top: 4px; }
.thread-bubble.mine .bubble-meta { text-align: right; }
.announcement-card { border-left: 4px solid #0d6efd; }
.announcement-card.pinned { border-left-color: #f59e0b; }
.badge-pin { background: #fef3c7; color: #92400e; }
.unread-dot { width: 8px; height: 8px; background: #0d6efd; border-radius: 50%; display: inline-block; flex-shrink: 0; }
</style>
</head>
<body>
<div class="wrapper">
  <nav id="sidebar" class="sidebar">
    <?php if (!defined('EDUTRACK_MODULES')) require_once __DIR__ . '/module_definitions.php'; echo buildSidebar('communication.php'); ?>
  </nav>
  <div class="main-content">
    <header class="header d-flex align-items-center justify-content-between">
      <div class="d-flex align-items-center gap-3">
        <button class="btn-toggle" id="sidebarToggle"><i class="fas fa-bars"></i></button>
        <div>
          <h4 class="mb-0">Communication</h4>
          <nav aria-label="breadcrumb" class="d-none d-md-block">
            <ol class="breadcrumb mb-0 small">
              <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
              <li class="breadcrumb-item active">Communication</li>
            </ol>
          </nav>
        </div>
      </div>
      <div class="d-flex gap-2">
        <?php if ($can_manage): ?>
        <button class="btn btn-primary" onclick="openAnnouncement()">
          <i class="fas fa-bullhorn me-1"></i> New Announcement
        </button>
        <?php endif; ?>
        <button class="btn btn-outline-primary" onclick="openCompose()">
          <i class="fas fa-pen me-1"></i> Compose
        </button>
      </div>
    </header>

    <main class="content">
      <ul class="nav nav-tabs mb-4" id="commTabs" role="tablist">
        <li class="nav-item">
          <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#tabAnnouncements" type="button">
            <i class="fas fa-bullhorn me-1"></i> Announcements
          </button>
        </li>
        <li class="nav-item">
          <button class="nav-link" data-bs-toggle="tab" data-bs-target="#tabInbox" type="button" id="inboxTabBtn">
            <i class="fas fa-inbox me-1"></i> Inbox
            <span class="badge bg-danger ms-1 d-none" id="unreadBadge">0</span>
          </button>
        </li>
        <li class="nav-item">
          <button class="nav-link" data-bs-toggle="tab" data-bs-target="#tabSent" type="button">
            <i class="fas fa-paper-plane me-1"></i> Sent
          </button>
        </li>
      </ul>

      <div class="tab-content">

        <!-- ══ TAB 1: ANNOUNCEMENTS ══════════════════════════════════════ -->
        <div class="tab-pane fade show active" id="tabAnnouncements">
          <div class="d-flex justify-content-between align-items-center mb-3">
            <div class="btn-group btn-group-sm">
              <button class="btn btn-outline-secondary active" onclick="loadAnnouncements('all', this)">All</button>
              <button class="btn btn-outline-secondary" onclick="loadAnnouncements('pinned', this)">
                <i class="fas fa-thumbtack me-1"></i> Pinned
              </button>
            </div>
            <span class="text-muted small" id="annCount"></span>
          </div>
          <div id="announcementsList">
            <div class="text-center text-muted py-5">
              <i class="fas fa-bullhorn fa-3x mb-3 d-block" style="opacity:.3"></i>
              Loading announcements...
            </div>
          </div>
        </div>

        <!-- ══ TAB 2: INBOX ══════════════════════════════════════════════ -->
        <div class="tab-pane fade" id="tabInbox">
          <div class="row g-0" style="min-height:500px">
            <div class="col-md-4 border-end" id="inboxList" style="max-height:600px;overflow-y:auto">
              <div class="p-3 text-center text-muted small">Loading...</div>
            </div>
            <div class="col-md-8" id="threadView">
              <div class="h-100 d-flex align-items-center justify-content-center text-muted">
                <div class="text-center">
                  <i class="fas fa-envelope-open fa-3x mb-3 d-block" style="opacity:.3"></i>
                  Select a message to read
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- ══ TAB 3: SENT ═══════════════════════════════════════════════ -->
        <div class="tab-pane fade" id="tabSent">
          <div class="row g-0" style="min-height:500px">
            <div class="col-md-4 border-end" id="sentList" style="max-height:600px;overflow-y:auto">
              <div class="p-3 text-center text-muted small">Loading...</div>
            </div>
            <div class="col-md-8" id="sentThreadView">
              <div class="h-100 d-flex align-items-center justify-content-center text-muted">
                <div class="text-center">
                  <i class="fas fa-paper-plane fa-3x mb-3 d-block" style="opacity:.3"></i>
                  Select a sent message to view
                </div>
              </div>
            </div>
          </div>
        </div>

      </div><!-- /tab-content -->
    </main>
  </div>
</div>

<!-- ══ ANNOUNCEMENT MODAL ════════════════════════════════════════════════════ -->
<div class="modal fade" id="announcementModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <form id="annForm">
        <div class="modal-header">
          <h5 class="modal-title" id="annModalTitle">New Announcement</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body">
          <input type="hidden" id="annId" name="id" value="0">
          <input type="hidden" name="action" value="save_announcement">
          <div class="mb-3">
            <label class="form-label fw-semibold">Title <span class="text-danger">*</span></label>
            <input type="text" id="annTitle" name="title" class="form-control" placeholder="Announcement title" required>
          </div>
          <div class="mb-3">
            <label class="form-label fw-semibold">Message <span class="text-danger">*</span></label>
            <textarea id="annBody" name="body" class="form-control" rows="5" required
                      placeholder="Type the announcement content here..."></textarea>
          </div>
          <div class="row g-3">
            <div class="col-md-6">
              <label class="form-label fw-semibold">Target Audience</label>
              <select id="annTarget" name="target_role" class="form-select">
                <option value="all">All Staff</option>
                <option value="teacher">Teachers Only</option>
                <option value="admin">Admins Only</option>
                <option value="registrar">Registrar</option>
                <option value="headteacher">Head Teacher</option>
              </select>
            </div>
            <div class="col-md-6 d-flex align-items-end">
              <div class="form-check mb-2">
                <input type="checkbox" id="annPinned" name="is_pinned" class="form-check-input">
                <label class="form-check-label fw-semibold" for="annPinned">
                  <i class="fas fa-thumbtack me-1 text-warning"></i> Pin this announcement
                </label>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-primary" id="annSaveBtn">
            <i class="fas fa-bullhorn me-1"></i> Publish
          </button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- ══ COMPOSE MESSAGE MODAL ═════════════════════════════════════════════════ -->
<div class="modal fade" id="composeModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <form id="composeForm">
        <div class="modal-header">
          <h5 class="modal-title" id="composeTitle">New Message</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body">
          <input type="hidden" name="action" value="send_message">
          <input type="hidden" id="msgParentId" name="parent_id" value="">
          <div class="mb-3" id="recipientWrap">
            <label class="form-label fw-semibold">To <span class="text-danger">*</span></label>
            <select id="msgRecipient" name="recipient_id" class="form-select" required>
              <option value="">— Select Recipient —</option>
            </select>
          </div>
          <div class="mb-3" id="subjectWrap">
            <label class="form-label fw-semibold">Subject</label>
            <input type="text" id="msgSubject" name="subject" class="form-control" placeholder="Optional subject">
          </div>
          <div class="mb-3">
            <label class="form-label fw-semibold">Message <span class="text-danger">*</span></label>
            <textarea id="msgBody" name="body" class="form-control" rows="5" required
                      placeholder="Type your message..."></textarea>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-primary" id="composeSendBtn">
            <i class="fas fa-paper-plane me-1"></i> Send
          </button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- ══ DELETE CONFIRM MODAL ══════════════════════════════════════════════════ -->
<div class="modal fade" id="deleteConfirmModal" tabindex="-1">
  <div class="modal-dialog modal-sm">
    <div class="modal-content">
      <div class="modal-header">
        <h6 class="modal-title text-danger"><i class="fas fa-trash me-1"></i> Confirm Delete</h6>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body"><p id="deleteConfirmText">Are you sure?</p></div>
      <div class="modal-footer">
        <button class="btn btn-sm btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
        <button class="btn btn-sm btn-danger" id="confirmDeleteBtn">Delete</button>
      </div>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
<script src="js/main.js"></script>
<script>
const esc = v => String(v ?? '').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'}[c]));
const canManage = <?= $can_manage ? 'true' : 'false' ?>;
const myUserId  = <?= (int) $_SESSION['user_id'] ?>;
let deleteCallback = null;
let allUsers = [];

function fmtDate(dt) {
    if (!dt) return '';
    const d = new Date(dt);
    return d.toLocaleDateString('en-GB', {day:'2-digit',month:'short',year:'numeric'}) + ' ' +
           d.toLocaleTimeString('en-GB', {hour:'2-digit',minute:'2-digit'});
}
function timeAgo(dt) {
    if (!dt) return '';
    const diff = (Date.now() - new Date(dt)) / 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 Math.floor(diff/86400) + 'd ago';
}

// ════════════════════════════════════════════════════════════════════════════
// ANNOUNCEMENTS
// ════════════════════════════════════════════════════════════════════════════
let announcements = [];

async function loadAnnouncements(filter = 'all', btn = null) {
    if (btn) {
        document.querySelectorAll('#tabAnnouncements .btn-group .btn').forEach(b => b.classList.remove('active'));
        btn.classList.add('active');
    }
    try {
        const res = await fetch('ajax/communication.php?action=get_announcements&filter=' + filter + '&_=' + Date.now());
        announcements = await res.json();
        renderAnnouncements();
    } catch (e) {
        document.getElementById('announcementsList').innerHTML =
            '<div class="alert alert-danger">Failed to load announcements.</div>';
    }
}

function renderAnnouncements() {
    document.getElementById('annCount').textContent = announcements.length + ' announcement(s)';
    const container = document.getElementById('announcementsList');
    if (announcements.length === 0) {
        container.innerHTML = `<div class="text-center text-muted py-5">
          <i class="fas fa-bullhorn fa-3x mb-3 d-block" style="opacity:.3"></i>
          No announcements found.${canManage ? ' Click "New Announcement" to create one.' : ''}
        </div>`;
        return;
    }
    container.innerHTML = announcements.map(a => `
      <div class="card mb-3 shadow-sm border-0 announcement-card ${parseInt(a.is_pinned) ? 'pinned' : ''}">
        <div class="card-body">
          <div class="d-flex justify-content-between align-items-start mb-2">
            <div>
              ${parseInt(a.is_pinned) ? '<span class="badge badge-pin me-2"><i class="fas fa-thumbtack me-1"></i>Pinned</span>' : ''}
              ${a.target_role !== 'all' ? `<span class="badge bg-light text-dark me-2">${esc(a.target_role)}</span>` : ''}
              <h6 class="d-inline fw-bold">${esc(a.title)}</h6>
            </div>
            ${canManage ? `<div class="btn-group btn-group-sm">
              <button class="btn btn-outline-secondary" onclick="editAnnouncement(${a.id})" title="Edit">
                <i class="fas fa-edit"></i>
              </button>
              <button class="btn btn-outline-${parseInt(a.is_pinned) ? 'warning' : 'secondary'}"
                      onclick="togglePin(${a.id})" title="${parseInt(a.is_pinned) ? 'Unpin' : 'Pin'}">
                <i class="fas fa-thumbtack"></i>
              </button>
              <button class="btn btn-outline-danger" onclick="deleteAnnouncement(${a.id}, '${esc(a.title)}')" title="Delete">
                <i class="fas fa-trash"></i>
              </button>
            </div>` : ''}
          </div>
          <p class="mb-2 text-secondary" style="white-space:pre-wrap">${esc(a.body)}</p>
          <div class="small text-muted">
            <i class="fas fa-user me-1"></i>${esc(a.author_name || 'Unknown')}
            &nbsp;·&nbsp;
            <i class="fas fa-clock me-1"></i>${fmtDate(a.created_at)}
          </div>
        </div>
      </div>`).join('');
}

function openAnnouncement() {
    document.getElementById('annModalTitle').textContent = 'New Announcement';
    document.getElementById('annForm').reset();
    document.getElementById('annId').value = '0';
    new bootstrap.Modal(document.getElementById('announcementModal')).show();
}

function editAnnouncement(id) {
    const a = announcements.find(x => parseInt(x.id) === id);
    if (!a) return;
    document.getElementById('annModalTitle').textContent = 'Edit Announcement';
    document.getElementById('annId').value     = a.id;
    document.getElementById('annTitle').value  = a.title;
    document.getElementById('annBody').value   = a.body;
    document.getElementById('annTarget').value = a.target_role;
    document.getElementById('annPinned').checked = parseInt(a.is_pinned) === 1;
    new bootstrap.Modal(document.getElementById('announcementModal')).show();
}

async function togglePin(id) {
    const res  = await fetch('ajax/communication.php', { method: 'POST', body: new URLSearchParams({ action: 'toggle_pin', id }) });
    const data = await res.json();
    if (data.success) loadAnnouncements();
    else alert(data.message);
}

function deleteAnnouncement(id, title) {
    document.getElementById('deleteConfirmText').textContent = `Delete announcement "${title}"? This cannot be undone.`;
    deleteCallback = async () => {
        const res  = await fetch('ajax/communication.php', { method: 'POST', body: new URLSearchParams({ action: 'delete_announcement', id }) });
        const data = await res.json();
        bootstrap.Modal.getInstance(document.getElementById('deleteConfirmModal'))?.hide();
        if (data.success) loadAnnouncements();
    };
    new bootstrap.Modal(document.getElementById('deleteConfirmModal')).show();
}

document.getElementById('annForm').addEventListener('submit', async e => {
    e.preventDefault();
    const btn = document.getElementById('annSaveBtn');
    btn.disabled = true; btn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Saving...';
    try {
        const res  = await fetch('ajax/communication.php', { method: 'POST', body: new URLSearchParams(new FormData(e.target)) });
        const data = await res.json();
        if (data.success) {
            bootstrap.Modal.getInstance(document.getElementById('announcementModal'))?.hide();
            loadAnnouncements();
        } else {
            alert(data.message);
        }
    } catch (e) {
        alert('An error occurred. Please try again.');
    } finally {
        btn.disabled = false; btn.innerHTML = '<i class="fas fa-bullhorn me-1"></i> Publish';
    }
});

// ════════════════════════════════════════════════════════════════════════════
// MESSAGES
// ════════════════════════════════════════════════════════════════════════════
async function loadUsers() {
    try {
        const res = await fetch('ajax/communication.php?action=get_users');
        allUsers  = await res.json();
        const sel = document.getElementById('msgRecipient');
        sel.innerHTML = '<option value="">— Select Recipient —</option>';
        allUsers.forEach(u => {
            const o = document.createElement('option');
            o.value = u.id;
            o.textContent = `${u.name} (${u.role})`;
            sel.appendChild(o);
        });
    } catch (e) { /* non-critical */ }
}

async function loadUnreadCount() {
    try {
        const res  = await fetch('ajax/communication.php?action=get_unread_count');
        const data = await res.json();
        const badge = document.getElementById('unreadBadge');
        if (data.count > 0) {
            badge.textContent = data.count;
            badge.classList.remove('d-none');
        } else {
            badge.classList.add('d-none');
        }
    } catch (e) { /* non-critical */ }
}

let inboxMessages = [];
let sentMessages  = [];

async function loadInbox() {
    try {
        const res  = await fetch('ajax/communication.php?action=get_inbox&_=' + Date.now());
        inboxMessages = await res.json();
        renderMessageList(inboxMessages, 'inboxList', 'inbox');
    } catch (e) {
        document.getElementById('inboxList').innerHTML =
            '<div class="p-3 text-danger small">Failed to load inbox.</div>';
    }
}

async function loadSent() {
    try {
        const res  = await fetch('ajax/communication.php?action=get_sent&_=' + Date.now());
        sentMessages = await res.json();
        renderMessageList(sentMessages, 'sentList', 'sent');
    } catch (e) {
        document.getElementById('sentList').innerHTML =
            '<div class="p-3 text-danger small">Failed to load sent messages.</div>';
    }
}

function renderMessageList(msgs, containerId, type) {
    const el = document.getElementById(containerId);
    if (msgs.length === 0) {
        el.innerHTML = `<div class="p-3 text-center text-muted small">
          <i class="fas fa-${type === 'inbox' ? 'inbox' : 'paper-plane'} fa-2x mb-2 d-block" style="opacity:.4"></i>
          ${type === 'inbox' ? 'Your inbox is empty.' : 'No sent messages.'}
        </div>`;
        return;
    }
    el.innerHTML = msgs.map(m => {
        // Inbox: show sender name; Sent: show recipient name
        const name = type === 'inbox' ? esc(m.sender_name) : esc(m.recipient_name);

        // A thread is unread if:
        //   Inbox: original root is unread (is_read=0) OR there are unread replies (unread_count > 0)
        //   Sent:  there are replies (reply_count > 0)
        const unreadCount = parseInt(m.unread_count ?? 0);
        const replyCount  = parseInt(m.reply_count  ?? 0);
        const isUnread    = type === 'inbox'
            ? (unreadCount > 0 || (!parseInt(m.is_read) && parseInt(m.sender_id) !== myUserId))
            : false;

        const subj = m.subject ? esc(m.subject) : esc((m.body || '').substring(0, 60)) + ((m.body||'').length > 60 ? '…' : '');
        const lastTime = m.last_activity || m.sent_at;

        return `<div class="p-3 border-bottom msg-list-item ${isUnread ? 'unread' : ''}"
                     data-id="${m.id}" data-type="${type}"
                     onclick="openThread(${m.id}, '${type}')">
          <div class="d-flex justify-content-between align-items-center mb-1">
            <strong class="small d-flex align-items-center gap-2">
              ${isUnread ? '<span class="unread-dot"></span>' : ''}
              ${name}
            </strong>
            <span class="text-muted" style="font-size:.7rem">${timeAgo(lastTime)}</span>
          </div>
          <div class="small text-muted text-truncate">${subj}</div>
          ${type === 'sent' && replyCount > 0 ? `<div class="small text-primary mt-1"><i class="fas fa-reply me-1"></i>${replyCount} repl${replyCount===1?'y':'ies'}</div>` : ''}
          ${type === 'inbox' && unreadCount > 1 ? `<div class="small text-primary mt-1"><i class="fas fa-circle me-1"></i>${unreadCount} unread</div>` : ''}
        </div>`;
    }).join('');
}

async function openThread(id, type) {
    const listId    = type === 'inbox' ? 'inboxList' : 'sentList';
    const container = type === 'inbox' ? document.getElementById('threadView') : document.getElementById('sentThreadView');

    // Highlight active item
    document.querySelectorAll(`#${listId} .msg-list-item`).forEach(el => el.classList.remove('active'));
    const clickedItem = document.querySelector(`#${listId} .msg-list-item[data-id="${id}"]`);
    if (clickedItem) {
        clickedItem.classList.add('active');
        clickedItem.classList.remove('unread');
        clickedItem.querySelector('.unread-dot')?.remove();
    }

    container.innerHTML = '<div class="p-4 text-center text-muted"><i class="fas fa-spinner fa-spin me-2"></i>Loading...</div>';

    try {
        const res  = await fetch(`ajax/communication.php?action=get_thread&id=${id}`);
        const data = await res.json();
        if (!data.success) {
            container.innerHTML = '<div class="p-3 text-danger">Could not load message.</div>';
            return;
        }

        const root    = data.root;
        const replies = data.replies;
        const allMsgs = [root, ...replies];

        // Determine the "other person" in the conversation
        const otherPersonId   = parseInt(root.sender_id) === myUserId ? root.recipient_id : root.sender_id;
        const otherPersonName = parseInt(root.sender_id) === myUserId ? root.recipient_name : root.sender_name;

        // Can the current user delete this thread? Only the original sender of the root.
        const canDelete = parseInt(root.sender_id) === myUserId;

        container.innerHTML = `
          <div class="d-flex flex-column h-100">
            <div class="p-3 border-bottom bg-light d-flex justify-content-between align-items-start">
              <div>
                <h6 class="fw-bold mb-0">${esc(root.subject || '(No subject)')}</h6>
                <div class="small text-muted">
                  Between <strong>${esc(root.sender_name)}</strong> and <strong>${esc(root.recipient_name)}</strong>
                </div>
              </div>
              ${canDelete ? `<button class="btn btn-sm btn-outline-danger" title="Delete conversation"
                onclick="deleteThread(${root.id})">
                <i class="fas fa-trash"></i>
              </button>` : ''}
            </div>
            <div class="flex-grow-1 p-3" id="threadBubbles" style="overflow-y:auto;background:#f8fafc">
              ${allMsgs.map(m => {
                const mine = parseInt(m.sender_id) === myUserId;
                return `<div class="thread-bubble ${mine ? 'mine' : 'theirs'} mb-3">
                  <div class="bubble-body">${esc(m.body).replace(/\n/g,'<br>')}</div>
                  <div class="bubble-meta">${esc(mine ? (m.recipient_name||'') : (m.sender_name||''))} · ${fmtDate(m.sent_at)}</div>
                </div>`;
              }).join('')}
            </div>
            <div class="p-3 border-top">
              <div class="input-group">
                <textarea class="form-control" id="replyBody_${id}" rows="2" placeholder="Type a reply..."></textarea>
                <button class="btn btn-primary" onclick="sendReply(${root.id}, ${otherPersonId}, '${type}')">
                  <i class="fas fa-paper-plane"></i>
                </button>
              </div>
            </div>
          </div>`;

        // Scroll bubbles to bottom
        const bubbles = document.getElementById('threadBubbles');
        if (bubbles) bubbles.scrollTop = bubbles.scrollHeight;

        // Update unread badge without reloading entire list
        loadUnreadCount();
    } catch (err) {
        container.innerHTML = '<div class="p-3 text-danger">An error occurred loading the message.</div>';
    }
}

async function sendReply(parentId, recipientId, fromType) {
    const body = document.getElementById(`replyBody_${parentId}`)?.value.trim();
    if (!body) return;

    const params = new URLSearchParams({
        action: 'send_message',
        recipient_id: recipientId,
        subject: '',
        body,
        parent_id: parentId
    });

    try {
        const res  = await fetch('ajax/communication.php', { method: 'POST', body: params });
        const data = await res.json();
        if (data.success) {
            // Reopen thread in the same panel it came from
            openThread(parentId, fromType);
            // Refresh the other list too (e.g., sent list updates when replying from inbox)
            if (fromType === 'inbox') {
                loadSent();
            } else {
                loadInbox();
            }
        } else {
            alert(data.message || 'Failed to send reply.');
        }
    } catch (e) {
        alert('An error occurred. Please try again.');
    }
}

function deleteThread(id) {
    document.getElementById('deleteConfirmText').textContent =
        'Delete this conversation and all its replies? This cannot be undone.';
    deleteCallback = async () => {
        const res  = await fetch('ajax/communication.php', {
            method: 'POST',
            body: new URLSearchParams({ action: 'delete_message', id })
        });
        const data = await res.json();
        bootstrap.Modal.getInstance(document.getElementById('deleteConfirmModal'))?.hide();
        if (data.success) {
            // Clear thread view and reload list
            document.getElementById('threadView').innerHTML = `
              <div class="h-100 d-flex align-items-center justify-content-center text-muted">
                <div class="text-center">
                  <i class="fas fa-envelope-open fa-3x mb-3 d-block" style="opacity:.3"></i>
                  Select a message to read
                </div>
              </div>`;
            loadInbox();
            loadSent();
        }
    };
    new bootstrap.Modal(document.getElementById('deleteConfirmModal')).show();
}

function openCompose(recipientId = '', subject = '', parentId = '') {
    document.getElementById('composeTitle').textContent = parentId ? 'Reply' : 'New Message';
    document.getElementById('composeForm').reset();
    document.getElementById('msgParentId').value = parentId;
    if (recipientId) document.getElementById('msgRecipient').value = recipientId;
    if (subject)     document.getElementById('msgSubject').value = 'Re: ' + subject;
    document.getElementById('recipientWrap').style.display = parentId ? 'none' : '';
    document.getElementById('subjectWrap').style.display   = parentId ? 'none' : '';
    new bootstrap.Modal(document.getElementById('composeModal')).show();
}

document.getElementById('composeForm').addEventListener('submit', async e => {
    e.preventDefault();
    const btn = document.getElementById('composeSendBtn');
    btn.disabled = true; btn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Sending...';
    try {
        const res  = await fetch('ajax/communication.php', { method: 'POST', body: new URLSearchParams(new FormData(e.target)) });
        const data = await res.json();
        if (data.success) {
            bootstrap.Modal.getInstance(document.getElementById('composeModal'))?.hide();
            loadSent();
            loadInbox();
            showToast('Message sent!', 'success');
        } else {
            alert(data.message || 'Failed to send message.');
        }
    } catch (e) {
        alert('An error occurred. Please try again.');
    } finally {
        btn.disabled = false; btn.innerHTML = '<i class="fas fa-paper-plane me-1"></i> Send';
    }
});

document.getElementById('confirmDeleteBtn').addEventListener('click', () => {
    if (deleteCallback) deleteCallback();
});

// Tab switch: lazy-load Inbox and Sent the first time they are opened
const tabLoaded = { inbox: false, sent: false };
document.querySelectorAll('#commTabs button[data-bs-toggle="tab"]').forEach(btn => {
    btn.addEventListener('shown.bs.tab', e => {
        const target = e.target.getAttribute('data-bs-target');
        if (target === '#tabInbox' && !tabLoaded.inbox) {
            tabLoaded.inbox = true;
            loadInbox();
        }
        if (target === '#tabSent' && !tabLoaded.sent) {
            tabLoaded.sent = true;
            loadSent();
        }
    });
});

function showToast(msg, type = 'success') {
    const t = document.createElement('div');
    t.className = `alert alert-${type} position-fixed bottom-0 end-0 m-3 shadow`;
    t.style.cssText = 'z-index:9999;min-width:260px';
    t.innerHTML = `<i class="fas fa-check-circle me-2"></i>${esc(msg)}`;
    document.body.appendChild(t);
    setTimeout(() => t.remove(), 3000);
}

// ── INIT ─────────────────────────────────────────────────────────────────────
loadAnnouncements();
loadUsers();
loadUnreadCount();
setInterval(loadUnreadCount, 60000);
</script>
</body>
</html>
