<?php
require_once "../config/database.php";
require_once "../includes/auth.php";
require_once "../includes/lang.php";
require_once "../includes/csrf.php";

requirePageAuth();
$user = getAuthUser();
$csrf = csrfToken();
?>
<!DOCTYPE HTML>
<html lang="<?= htmlspecialchars(currentLang()) ?>">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title><?= htmlspecialchars(t("support")) ?> - Konzona Hub</title>
<link rel="stylesheet" href="assets/css/bootstrap.min.css" type="text/css">
<link rel="stylesheet" href="assets/css/style.css" type="text/css">
<link rel="stylesheet" href="assets/css/dashboard.css" type="text/css">
<link rel="stylesheet" href="assets/css/owl.carousel.min.css" type="text/css">
<link href="assets/css/font-awesome.min.css" rel="stylesheet">
</head>
<body>
<div class="dashboard_container">
<header id="header">
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<div class="logo"><a href="dashboard.php"><img src="assets/images/logo.png" alt="logo"/></a></div>
<div id="dashboard-responsive-nav-trigger"><i class="fa fa-reorder"></i></div>
</div>
</div>
</nav>
</header>

<div id="dashboard">
<div id="dashboard-nav" class="dashboard-nav">
<ul>
<li><a href="dashboard.php"><i class="fa fa-cogs"></i> <?= htmlspecialchars(t("dashboard")) ?></a></li>
<li class="active"><a href="chat.php"><i class="fa fa-comments"></i> <?= htmlspecialchars(t("support")) ?></a></li>
<li><a href="profile.php"><i class="fa fa-user-o"></i> <?= htmlspecialchars(t("my_profile")) ?></a></li>
<li><a href="logout.php"><i class="fa fa-power-off"></i> <?= htmlspecialchars(t("logout")) ?></a></li>
</ul>
</div>

<div class="dashboard-content">
<div id="titlebar"><div class="row"><div class="col-md-12"><h2><?= htmlspecialchars(t("support")) ?></h2></div></div></div>
<?php $isAdminLike = ((int)($user["role_id"] ?? 0) === 1 || (int)($user["role_id"] ?? 0) === 5); ?>

<?php if ($isAdminLike): ?>
<div class="dashboard-section-card" style="margin-bottom:20px;">
  <div class="section-header">
    <h4>Admin Conversations</h4>
  </div>
  <div id="adminConversationsPreview" style="padding:10px 20px;color:#555;">Loading conversations...</div>
</div>
<?php endif; ?>

<div class="row">
<?php if ($isAdminLike): ?>
<div class="col-md-3">
<div class="dashboard-list-box">
<h4><?= htmlspecialchars(t("conversation_user_id")) ?></h4>
<div class="padding-20">
<select id="conversationUserId" class="form-control"></select>
<button id="loadConvBtn" class="btn btn-block" style="margin-top:10px;"><?= htmlspecialchars(t("load_chat")) ?></button>
</div>
</div>
<div class="dashboard-list-box" style="margin-top:20px;">
<h4><?= htmlspecialchars(t("notifications")) ?></h4>
<ul id="notifList"></ul>
</div>
</div>

<div class="col-md-9">
<?php else: ?>
<div class="col-md-12">
<?php endif; ?>
<div class="dashboard-list-box">
<h4><?= htmlspecialchars(t("messages")) ?></h4>
<div class="padding-20" id="chatBox" style="height:350px;overflow:auto;background:#fafafa;border:1px solid #eee;"></div>
<div class="padding-20">
<?php if (!$isAdminLike): ?>
<div style="margin-bottom:8px;color:#666;">Send Message (to all admins and moderators)</div>
<?php endif; ?>
<input type="text" id="chatInput" class="form-control" placeholder="<?= htmlspecialchars(t("type_message")) ?>">
<button id="sendBtn" class="btn" style="margin-top:10px;"><?= htmlspecialchars(t("send")) ?></button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>

<script>
window.APP = { userId: <?= (int)$user["id"] ?>, roleId: <?= (int)$user["role_id"] ?>, csrf: "<?= htmlspecialchars($csrf) ?>" };
window.APP.isAdminLike = (window.APP.roleId === 1 || window.APP.roleId === 5);
let currentOtherUserId = null;
const participants = new Map();

function escapeHtml(value) {
  return String(value || "")
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#039;");
}


async function buildParticipantList() {
  const select = document.getElementById("conversationUserId");
  if (!select) {
    if (!window.APP.isAdminLike) {
      currentOtherUserId = 1;
    }
    return;
  }
  select.innerHTML = '<option value="">Select user</option>';
  participants.clear();

  const roleMap = {
    1: [2, 3, 4, 5], // admin -> all
    5: [1, 2, 3, 4], // moderator -> all
    2: [1, 5],       // worker -> admin/moderator
    3: [1, 5],       // agency -> admin/moderator
    4: [1, 5]        // company -> admin/moderator
  };
  const allowedRoles = roleMap[window.APP.roleId] || [];

  const r = await fetch("../api/users.php", { credentials: "same-origin" });
  const j = await r.json().catch(() => ({ success: false }));
  if (j.success && Array.isArray(j.data)) {
    j.data.forEach(u => {
      const id = parseInt(u.id, 10);
      const roleId = parseInt(u.role_id, 10);
      if (!id || id === window.APP.userId) return;
      if (window.APP.roleId !== 1 && !allowedRoles.includes(roleId)) return;
      const label = (u.email || ("User #" + id)) + " [" + (u.role_name || ("role " + roleId)) + "]";
      participants.set(id, label);
    });
  }

  if (participants.size === 0) {
    const rr = await fetch("../api/message_fetch.php" + ((window.APP.roleId === 1 || window.APP.roleId === 5) ? "" : "?user_id=1"), { credentials: "same-origin" });
    const jj = await rr.json().catch(() => ({ success: false }));
    if (jj.success && Array.isArray(jj.data)) {
      jj.data.forEach(m => {
        const senderId = parseInt(m.sender_id, 10);
        const receiverId = parseInt(m.receiver_id, 10);
        if (senderId !== window.APP.userId) participants.set(senderId, m.sender_email || ("User #" + senderId));
        if (receiverId !== window.APP.userId) participants.set(receiverId, m.receiver_email || ("User #" + receiverId));
      });
    }
  }

  participants.forEach((name, id) => {
    const opt = document.createElement("option");
    opt.value = id;
    opt.textContent = name + " (ID: " + id + ")";
    select.appendChild(opt);
  });

  if (!currentOtherUserId && participants.size > 0) {
    currentOtherUserId = parseInt([...participants.keys()][0], 10);
    select.value = String(currentOtherUserId);
  }
}

async function loadMessages() {
  if (!currentOtherUserId) return;
  const r = await fetch("../api/message_fetch.php?user_id=" + encodeURIComponent(currentOtherUserId), { credentials: "same-origin" });
  const j = await r.json().catch(() => ({ success: false, data: [] }));
  const box = document.getElementById("chatBox");
  box.innerHTML = "";
  if (!j.success || !Array.isArray(j.data)) return;

  j.data.forEach(m => {
    const mine = parseInt(m.sender_id, 10) === window.APP.userId;
    const senderLabel = mine ? "You" : (participants.get(parseInt(m.sender_id, 10)) || ("User #" + m.sender_id));
    const div = document.createElement("div");
    div.style.margin = "8px 0";
    div.style.textAlign = mine ? "right" : "left";
    div.innerHTML =
      '<div style="font-size:11px;color:#777;margin-bottom:3px;">' + escapeHtml(senderLabel) + '</div>' +
      '<span style="display:inline-block;padding:8px 12px;border-radius:12px;background:' + (mine ? '#d1c4e9' : '#e0e0e0') + ';">' +
      escapeHtml(m.text || "") + '</span>';
    box.appendChild(div);
  });
  box.scrollTop = box.scrollHeight;
}

async function sendMessage() {
  if (!currentOtherUserId) return;
  const text = document.getElementById("chatInput").value.trim();
  if (!text) return;

  const r = await fetch("../api/message_send.php", {
    method: "POST",
    headers: {"Content-Type":"application/json"},
    credentials: "same-origin",
    body: JSON.stringify({
      csrf: window.APP.csrf,
      receiver_id: currentOtherUserId,
      text
    })
  });

  const j = await r.json().catch(() => ({ success: false, error: "invalid_response" }));
  if (j.success) {
    document.getElementById("chatInput").value = "";
    await buildParticipantList();
    await loadMessages();
    await loadNotifications();
  } else {
    alert(j.error || "message_send_failed");
  }
}

async function loadAdminConversationPreview() {
  const wrap = document.getElementById("adminConversationsPreview");
  if (!wrap) return;
  const r = await fetch("../api/message_fetch.php", { credentials: "same-origin" });
  const j = await r.json().catch(() => ({ success: false, data: [] }));
  if (!j.success || !Array.isArray(j.data) || j.data.length === 0) {
    wrap.textContent = "No conversations yet.";
    return;
  }

  const uniquePairs = new Map();
  j.data.forEach(m => {
    const s = parseInt(m.sender_id, 10);
    const rcv = parseInt(m.receiver_id, 10);
    if (!s || !rcv) return;
    const a = Math.min(s, rcv);
    const b = Math.max(s, rcv);
    const key = a + ":" + b;
    if (!uniquePairs.has(key)) {
      const labelA = m.sender_email || ("User #" + s);
      const labelB = m.receiver_email || ("User #" + rcv);
      uniquePairs.set(key, labelA + " ↔ " + labelB);
    }
  });

  if (uniquePairs.size === 0) {
    wrap.textContent = "No conversations yet.";
    return;
  }

  wrap.innerHTML = "";
  Array.from(uniquePairs.values()).slice(0, 10).forEach(line => {
    const div = document.createElement("div");
    div.style.padding = "6px 0";
    div.textContent = line;
    wrap.appendChild(div);
  });
}

async function loadNotifications() {
  const r = await fetch("../api/notifications.php", { credentials: "same-origin" });
  const j = await r.json().catch(() => ({ success: false }));
  const ul = document.getElementById("notifList");
  ul.innerHTML = "";
  if (!j.success || !j.data) return;

  (j.data.notifications || []).forEach(n => {
    const li = document.createElement("li");
    const sender = n.sender_email ? (" from " + n.sender_email) : "";
    li.innerHTML = escapeHtml((n.message || "") + sender) + (parseInt(n.is_read,10) ? "" : " <strong>(new)</strong>");
    li.style.cursor = "pointer";
    li.onclick = async () => {
      await fetch("../api/notifications.php", {
        method: "POST",
        headers: {"Content-Type":"application/json"},
        credentials: "same-origin",
        body: JSON.stringify({ csrf: window.APP.csrf, notification_id: n.id })
      });
      loadNotifications();
    };
    ul.appendChild(li);
  });
}

var loadConvBtn = document.getElementById("loadConvBtn");
if (loadConvBtn) {
  loadConvBtn.addEventListener("click", () => {
    const sel = document.getElementById("conversationUserId");
    const v = sel ? parseInt(sel.value, 10) : 0;
    if (!v || v === window.APP.userId) return;
    currentOtherUserId = v;
    loadMessages();
  });
}

document.getElementById("sendBtn").addEventListener("click", sendMessage);

(async function initChat(){
  await buildParticipantList();

  if (window.APP.isAdminLike) {
    await loadNotifications();
    await loadAdminConversationPreview();
  }

  if (currentOtherUserId) {
    await loadMessages();
  }
})();

setInterval(() => {
  loadMessages();
  if (window.APP.isAdminLike) {
    loadNotifications();
    loadAdminConversationPreview();
  }
}, 5000);
</script>
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/bootstrap.min.js"></script>
<script src="assets/js/owl.carousel.min.js"></script>
<script src="assets/js/interface.js"></script>
</div>
</body>
</html>
