<?php
session_start();
require_once 'db.php';
if (!isset($_SESSION['admin_id'])) { header("Location: admin_login.php"); exit; }
$admin_id = $_SESSION['admin_id'];

// ── AJAX: send message as admin ───────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');
    $uid = (int)($_POST['user_id'] ?? 0);
    $msg = trim($_POST['message'] ?? '');
    if (!$uid || $msg === '') { echo json_encode(['success'=>false]); exit; }
    $stmt = $conn->prepare("INSERT INTO support_messages (user_id, sender, message) VALUES (?, 'admin', ?)");
    $stmt->bind_param('is', $uid, $msg);
    $stmt->execute();
    // Mark all user messages as read
    $conn->query("UPDATE support_messages SET is_read=1 WHERE user_id=$uid AND sender='user'");
    echo json_encode(['success'=>true,'id'=>$conn->insert_id,'time'=>date('H:i')]);
    exit;
}

// ── AJAX: poll new messages for a user ────────────────────
if (isset($_GET['poll'])) {
    header('Content-Type: application/json');
    $uid   = (int)($_GET['user_id'] ?? 0);
    $after = (int)($_GET['after'] ?? 0);
    $conn->query("UPDATE support_messages SET is_read=1 WHERE user_id=$uid AND sender='user'");
    $res = $conn->query("SELECT id,sender,message,created_at FROM support_messages WHERE user_id=$uid AND id>$after ORDER BY id ASC");
    $rows = [];
    while ($r = $res->fetch_assoc()) $rows[] = $r;
    echo json_encode($rows);
    exit;
}

// ── AJAX: unread counts for sidebar badge ─────────────────
if (isset($_GET['unread_counts'])) {
    header('Content-Type: application/json');
    $res = $conn->query("SELECT user_id, COUNT(*) as cnt FROM support_messages WHERE sender='user' AND is_read=0 GROUP BY user_id");
    $counts = [];
    while ($r = $res->fetch_assoc()) $counts[$r['user_id']] = (int)$r['cnt'];
    echo json_encode($counts);
    exit;
}

// ── Load user list with latest message ───────────────────
$users_res = $conn->query("
    SELECT u.id, u.phone, u.avatar,
           sm.message as last_msg,
           sm.created_at as last_time,
           sm.sender as last_sender,
           (SELECT COUNT(*) FROM support_messages WHERE user_id=u.id AND sender='user' AND is_read=0) as unread
    FROM users u
    INNER JOIN support_messages sm ON sm.id = (
        SELECT id FROM support_messages WHERE user_id=u.id ORDER BY id DESC LIMIT 1
    )
    ORDER BY sm.created_at DESC
");
$user_list = [];
while ($r = $users_res->fetch_assoc()) $user_list[] = $r;

// ── Active chat user ──────────────────────────────────────
$active_uid = (int)($_GET['uid'] ?? ($user_list[0]['id'] ?? 0));
$active_user = null;
$chat_messages = [];
$last_id = 0;

if ($active_uid) {
    $active_user = $conn->query("SELECT * FROM users WHERE id=$active_uid")->fetch_assoc();
    $conn->query("UPDATE support_messages SET is_read=1 WHERE user_id=$active_uid AND sender='user'");
    $res = $conn->query("SELECT id,sender,message,created_at FROM support_messages WHERE user_id=$active_uid ORDER BY id ASC LIMIT 300");
    while ($r = $res->fetch_assoc()) $chat_messages[] = $r;
    $last_id = empty($chat_messages) ? 0 : (int)end($chat_messages)['id'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
<title>Admin – Support Messages</title>
<style>
*{margin:0;padding:0;box-sizing:border-box}
html,body{height:100%;overflow:hidden;font-family:'Segoe UI',sans-serif}

/* ── Layout ── */
.app{display:flex;height:100dvh;background:#111b21}

/* ── Sidebar ── */
.sidebar{
  width:340px;flex-shrink:0;
  display:flex;flex-direction:column;
  background:#111b21;
  border-right:1px solid #2a3942
}
@media(max-width:700px){
  .sidebar{width:100%;display:<?= $active_uid ? 'none' : 'flex' ?>}
  .chat-area{display:<?= $active_uid ? 'flex' : 'none' ?>}
}

.sidebar-header{
  background:#202c33;
  padding:14px 16px;
  display:flex;align-items:center;justify-content:space-between
}
.sidebar-title{font-size:20px;font-weight:700;color:#e9edef}
.sidebar-icon svg{width:22px;height:22px;fill:#aebac1}

.search-bar{
  padding:8px 12px;
  background:#111b21
}
.search-bar input{
  width:100%;background:#202c33;
  border:none;outline:none;
  border-radius:8px;padding:9px 14px;
  font-size:13px;color:#d1d7db;
  font-family:inherit
}
.search-bar input::placeholder{color:#8696a0}

.user-list{flex:1;overflow-y:auto}
.user-list::-webkit-scrollbar{width:4px}
.user-list::-webkit-scrollbar-thumb{background:#374045;border-radius:2px}

.user-item{
  display:flex;align-items:center;gap:12px;
  padding:12px 16px;cursor:pointer;
  border-bottom:1px solid #1f2c33;
  transition:background .15s;
  text-decoration:none
}
.user-item:hover{background:#202c33}
.user-item.active{background:#2a3942}

.u-avatar{
  width:46px;height:46px;border-radius:50%;
  background:linear-gradient(135deg,#00a884,#007d62);
  display:flex;align-items:center;justify-content:center;
  font-size:18px;flex-shrink:0;color:#fff;font-weight:700
}
.u-avatar img{width:46px;height:46px;border-radius:50%;object-fit:cover}

.u-info{flex:1;min-width:0}
.u-top{display:flex;justify-content:space-between;align-items:center;margin-bottom:3px}
.u-name{font-size:14px;font-weight:600;color:#e9edef;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.u-time{font-size:11px;color:#8696a0;white-space:nowrap;flex-shrink:0;margin-left:6px}
.u-bottom{display:flex;justify-content:space-between;align-items:center}
.u-preview{font-size:12px;color:#8696a0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;flex:1}
.u-preview.sent::before{content:'✓ '}
.unread-badge{
  background:#00a884;color:#fff;
  font-size:11px;font-weight:700;
  min-width:20px;height:20px;
  border-radius:10px;
  display:flex;align-items:center;justify-content:center;
  padding:0 5px;flex-shrink:0;margin-left:6px
}

/* ── Chat Area ── */
.chat-area{
  flex:1;display:flex;flex-direction:column;
  background:#0b141a;
  min-width:0
}

.no-chat{
  flex:1;display:flex;flex-direction:column;
  align-items:center;justify-content:center;gap:16px;
  color:#8696a0
}
.no-chat svg{width:60px;height:60px;fill:#374045}
.no-chat p{font-size:14px}

/* Chat header */
.chat-header{
  background:#202c33;
  padding:10px 14px;
  display:flex;align-items:center;gap:12px;
  flex-shrink:0
}
.chat-header .back-mob{
  display:none;
  width:32px;height:32px;align-items:center;justify-content:center;
  text-decoration:none;margin-right:2px
}
@media(max-width:700px){.chat-header .back-mob{display:flex}}
.chat-header .back-mob svg{width:22px;height:22px;fill:#aebac1}

.ch-avatar{
  width:40px;height:40px;border-radius:50%;
  background:linear-gradient(135deg,#00a884,#007d62);
  display:flex;align-items:center;justify-content:center;
  font-size:16px;color:#fff;font-weight:700;flex-shrink:0
}
.ch-info{flex:1}
.ch-name{font-size:15px;font-weight:600;color:#e9edef}
.ch-sub{font-size:12px;color:#8696a0;margin-top:1px}

/* Chat body */
.chat-bg{
  flex:1;overflow-y:auto;
  padding:12px 10px 8px;
  background:#0b141a;
  background-image:url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23ffffff' fill-opacity='0.02'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E");
}
.chat-bg::-webkit-scrollbar{width:4px}
.chat-bg::-webkit-scrollbar-thumb{background:#374045;border-radius:2px}

/* Date divider */
.date-divider{text-align:center;margin:8px 0}
.date-divider span{
  background:#182229;color:#8696a0;
  font-size:11px;font-weight:600;
  padding:4px 12px;border-radius:10px
}

/* Bubbles */
.bubble-row{display:flex;margin-bottom:3px;align-items:flex-end;gap:6px}
.bubble-row.user{flex-direction:row-reverse}
.bubble-row.admin{flex-direction:row}

.b-avatar{
  width:26px;height:26px;border-radius:50%;
  background:linear-gradient(135deg,#00a884,#007d62);
  display:flex;align-items:center;justify-content:center;
  font-size:11px;color:#fff;font-weight:700;flex-shrink:0;margin-bottom:2px
}

.bubble{
  max-width:68%;padding:7px 10px 18px;
  border-radius:8px;font-size:14px;
  line-height:1.45;position:relative;
  word-break:break-word;
}
.bubble.user{background:#005c4b;color:#e9edef;border-bottom-right-radius:2px}
.bubble.admin{background:#202c33;color:#e9edef;border-bottom-left-radius:2px}
.bubble.user::after{content:'';position:absolute;bottom:0;right:-7px;width:0;height:0;border-left:8px solid #005c4b;border-bottom:8px solid transparent}
.bubble.admin::after{content:'';position:absolute;bottom:0;left:-7px;width:0;height:0;border-right:8px solid #202c33;border-bottom:8px solid transparent}

.bubble-meta{position:absolute;bottom:4px;right:8px;display:flex;align-items:center;gap:3px}
.bubble-time{font-size:10px;color:#8696a0;white-space:nowrap}
.tick{width:14px;height:10px}

/* Typing */
.typing-row{display:none}
.typing-bubble{
  background:#202c33;border-radius:8px;border-bottom-left-radius:2px;
  padding:10px 14px 10px;display:inline-flex;gap:4px;align-items:center;
  margin-bottom:3px
}
.typing-bubble span{width:7px;height:7px;border-radius:50%;background:#8696a0;animation:bounce 1.2s infinite;display:inline-block}
.typing-bubble span:nth-child(2){animation-delay:.2s}
.typing-bubble span:nth-child(3){animation-delay:.4s}
@keyframes bounce{0%,60%,100%{transform:translateY(0)}30%{transform:translateY(-5px)}}

/* Input bar */
.input-bar{
  background:#202c33;padding:8px 12px;
  display:flex;align-items:flex-end;gap:8px;flex-shrink:0
}
.input-wrap{
  flex:1;background:#2a3942;border-radius:22px;
  padding:9px 14px;display:flex;align-items:flex-end
}
#adminInput{
  flex:1;border:none;outline:none;
  font-size:14px;font-family:inherit;
  color:#d1d7db;resize:none;max-height:100px;
  background:transparent;line-height:1.4
}
#adminInput::placeholder{color:#8696a0}
.send-btn{
  width:44px;height:44px;border-radius:50%;
  background:#00a884;border:none;cursor:pointer;
  display:flex;align-items:center;justify-content:center;
  flex-shrink:0;transition:transform .1s
}
.send-btn:active{transform:scale(.93)}
.send-btn svg{width:20px;height:20px;fill:#fff}

/* Empty state in chat */
.empty-chat{
  flex:1;display:flex;flex-direction:column;
  align-items:center;justify-content:center;gap:10px
}
.empty-chat p{font-size:13px;color:#8696a0;background:#182229;padding:8px 16px;border-radius:10px}
</style>
</head>
<body>
<div class="app">

  <!-- ── SIDEBAR ── -->
  <div class="sidebar">
    <div class="sidebar-header">
      <span class="sidebar-title">Support</span>
      <div class="sidebar-icon">
        <svg viewBox="0 0 24 24"><path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2z"/></svg>
      </div>
    </div>
    <div class="search-bar">
      <input type="text" id="searchInput" placeholder="Search or start new chat" oninput="filterUsers()">
    </div>
    <div class="user-list" id="userList">
      <?php foreach ($user_list as $u):
        $initials = strtoupper(substr($u['phone'], -2));
        $preview = mb_strimwidth($u['last_msg'], 0, 40, '...');
        $time_label = '';
        $t = strtotime($u['last_time']);
        $today = date('Y-m-d');
        $time_label = (date('Y-m-d',$t)===$today) ? date('H:i',$t) : date('d/m/y',$t);
        $is_active = ($u['id'] == $active_uid);
      ?>
      <a href="admin_messages.php?uid=<?= $u['id'] ?>"
         class="user-item <?= $is_active ? 'active' : '' ?>"
         data-phone="<?= htmlspecialchars($u['phone']) ?>"
         data-uid="<?= $u['id'] ?>">
        <div class="u-avatar">
          <?php if ($u['avatar']): ?>
            <img src="<?= htmlspecialchars($u['avatar']) ?>" alt="">
          <?php else: ?>
            <?= $initials ?>
          <?php endif; ?>
        </div>
        <div class="u-info">
          <div class="u-top">
            <span class="u-name"><?= htmlspecialchars($u['phone']) ?></span>
            <span class="u-time"><?= $time_label ?></span>
          </div>
          <div class="u-bottom">
            <span class="u-preview <?= $u['last_sender']==='admin'?'sent':'' ?>"><?= htmlspecialchars($preview) ?></span>
            <?php if ($u['unread'] > 0): ?>
              <span class="unread-badge" id="badge-<?= $u['id'] ?>"><?= $u['unread'] ?></span>
            <?php endif; ?>
          </div>
        </div>
      </a>
      <?php endforeach; ?>
      <?php if (empty($user_list)): ?>
        <div style="padding:30px;text-align:center;color:#8696a0;font-size:13px">No conversations yet</div>
      <?php endif; ?>
    </div>
  </div>

  <!-- ── CHAT AREA ── -->
  <div class="chat-area">
    <?php if (!$active_user): ?>
      <div class="no-chat">
        <svg viewBox="0 0 24 24"><path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2z"/></svg>
        <p>Select a conversation to start chatting</p>
      </div>
    <?php else: ?>
      <!-- Chat Header -->
      <div class="chat-header">
        <a href="admin_messages.php" class="back-mob">
          <svg viewBox="0 0 24 24"><path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"/></svg>
        </a>
        <div class="ch-avatar"><?= strtoupper(substr($active_user['phone'],-2)) ?></div>
        <div class="ch-info">
          <div class="ch-name"><?= htmlspecialchars($active_user['phone']) ?></div>
          <div class="ch-sub">User ID: <?= $active_user['id'] ?></div>
        </div>
      </div>

      <!-- Chat Body -->
      <div class="chat-bg" id="chatBody">
        <?php if (empty($chat_messages)): ?>
          <div class="empty-chat">
            <p>No messages yet. Say hello 👋</p>
          </div>
        <?php else:
          $prev_date = '';
          foreach ($chat_messages as $m):
            $d = date('Y-m-d', strtotime($m['created_at']));
            $today2 = date('Y-m-d');
            $yesterday2 = date('Y-m-d',strtotime('-1 day'));
            if ($d !== $prev_date):
              $lbl = ($d===$today2)?'Today':(($d===$yesterday2)?'Yesterday':date('d M Y',strtotime($d)));
        ?>
              <div class="date-divider"><span><?= $lbl ?></span></div>
        <?php $prev_date = $d; endif; ?>
          <div class="bubble-row <?= $m['sender'] ?>">
            <?php if ($m['sender']==='user'): ?>
              <div class="b-avatar"><?= strtoupper(substr($active_user['phone'],-2)) ?></div>
            <?php endif; ?>
            <div class="bubble <?= $m['sender'] ?>">
              <?= nl2br(htmlspecialchars($m['message'])) ?>
              <div class="bubble-meta">
                <span class="bubble-time"><?= date('H:i',strtotime($m['created_at'])) ?></span>
                <?php if ($m['sender']==='admin'): ?>
                  <svg class="tick" viewBox="0 0 18 11" fill="none">
                    <path d="M1 5.5L5.5 10L17 1" stroke="#53bdeb" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
                    <path d="M5 5.5L9.5 10L17 1" stroke="#53bdeb" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
                  </svg>
                <?php endif; ?>
              </div>
            </div>
          </div>
        <?php endforeach; endif; ?>

        <!-- Typing row -->
        <div class="bubble-row admin typing-row" id="typingRow">
          <div class="b-avatar">A</div>
          <div class="typing-bubble"><span></span><span></span><span></span></div>
        </div>
      </div>

      <!-- Input -->
      <div class="input-bar">
        <div class="input-wrap">
          <textarea id="adminInput" rows="1" placeholder="Type a message…"></textarea>
        </div>
        <button class="send-btn" onclick="sendMessage()">
          <svg viewBox="0 0 24 24"><path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/></svg>
        </button>
      </div>
    <?php endif; ?>
  </div>
</div>

<?php if ($active_user): ?>
<script>
const ACTIVE_UID = <?= $active_uid ?>;
let lastId = <?= $last_id ?>;
const chatBody = document.getElementById('chatBody');
const input = document.getElementById('adminInput');
const initials = '<?= strtoupper(substr($active_user['phone'],-2)) ?>';

function scrollBottom(smooth=false){
  chatBody.scrollTo({top:chatBody.scrollHeight,behavior:smooth?'smooth':'auto'});
}
scrollBottom();

input.addEventListener('input',()=>{
  input.style.height='auto';
  input.style.height=Math.min(input.scrollHeight,100)+'px';
});

input.addEventListener('keydown',e=>{
  if(e.key==='Enter'&&!e.shiftKey){
    e.preventDefault();
    e.stopPropagation();
    sendMessage();
    return false;
  }
});

function formatTime(dt){
  const d=new Date(dt.replace(' ','T'));
  return d.toTimeString().slice(0,5);
}

function appendBubble(m){
  // Prevent duplicates by checking if this message ID already exists
  if(m.id && chatBody.querySelector(`[data-id="${m.id}"]`)) return;

  const empty=chatBody.querySelector('.empty-chat');
  if(empty)empty.remove();

  const row=document.createElement('div');
  row.className=`bubble-row ${m.sender}`;
  if(m.id) row.dataset.id = m.id;

  const tick=m.sender==='admin'
    ?`<svg class="tick" viewBox="0 0 18 11" fill="none">
        <path d="M1 5.5L5.5 10L17 1" stroke="#53bdeb" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
        <path d="M5 5.5L9.5 10L17 1" stroke="#53bdeb" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
      </svg>`
    :'';

  const avatar=m.sender==='user'?`<div class="b-avatar">${initials}</div>`:'';
  const t=m.created_at?formatTime(m.created_at):(m.time||'');
  const text=(m.message||'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/\n/g,'<br>');

  row.innerHTML=`${avatar}<div class="bubble ${m.sender}">${text}<div class="bubble-meta"><span class="bubble-time">${t}</span>${tick}</div></div>`;

  const tr=document.getElementById('typingRow');
  if(tr){ chatBody.insertBefore(row,tr); }
  else { chatBody.appendChild(row); }

  scrollBottom(true);
}

async function sendMessage(){
  const msg=input.value.trim();
  if(!msg)return;

  // Show admin's own message immediately (optimistic)
  const now=new Date().toTimeString().slice(0,5);
  appendBubble({sender:'admin',message:msg,time:now});

  input.value='';
  input.style.height='auto';

  const fd=new FormData();
  fd.append('user_id',ACTIVE_UID);
  fd.append('message',msg);

  try{
    const res=await fetch('admin_messages.php',{method:'POST',body:fd});
    const ct=res.headers.get('content-type')||'';
    if(!ct.includes('application/json')){
      console.error('Non-JSON response — possible session expiry');
      return;
    }
    const data=await res.json();
    if(data.success){
      lastId=Math.max(lastId,parseInt(data.id));
    }
  }catch(e){
    console.error('Send error:',e);
  }
}

async function poll(){
  try{
    const res=await fetch(`admin_messages.php?poll=1&user_id=${ACTIVE_UID}&after=${lastId}`);
    const ct=res.headers.get('content-type')||'';
    if(!ct.includes('application/json')) return;

    const rows=await res.json();
    rows.forEach(m=>{
      if(m.sender==='user'){
        appendBubble(m);  // appendBubble now deduplicates by data-id
      }
      lastId=Math.max(lastId,parseInt(m.id));
    });
  }catch(e){}
}

setInterval(poll,3000);
    </script>
    <?php endif; ?>  
    </body>
    </html>