<?php
// ============================================================
// FILE: admin/chat.php — Panel Chat Admin
// Kiri: daftar percakapan + badge unread
// Kanan: window chat real-time
// ============================================================
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/auth.php';
requireAdmin();

$pdo = db();

// Daftar semua pesanan yang punya chat
$percakapan = $pdo->query("
    SELECT p.id, p.kode_pesanan, p.nama_pembeli, p.status,
           MAX(c.created_at) AS last_msg_at,
           SUM(CASE WHEN c.pengirim='pelanggan' AND c.dibaca=0 THEN 1 ELSE 0 END) AS unread,
           (SELECT pesan FROM chat_pesan WHERE pesanan_id=p.id ORDER BY id DESC LIMIT 1) AS last_msg
    FROM pesanan p
    LEFT JOIN chat_pesan c ON c.pesanan_id = p.id
    GROUP BY p.id
    HAVING last_msg_at IS NOT NULL OR unread > 0
    ORDER BY last_msg_at DESC
")->fetchAll();

// Juga tampilkan pesanan yang belum pernah chat tapi ada di param
$activePesananId = (int)($_GET['pesanan_id'] ?? 0);
$activePesanan   = null;
if ($activePesananId) {
    $s = $pdo->prepare("SELECT * FROM pesanan WHERE id=? LIMIT 1");
    $s->execute([$activePesananId]);
    $activePesanan = $s->fetch();
}

// Total unread
$totalUnread = (int)$pdo->query("
    SELECT COUNT(*) FROM chat_pesan WHERE pengirim='pelanggan' AND dibaca=0
")->fetchColumn();

$pageTitle = 'Chat Pelanggan';
include __DIR__ . '/admin_layout.php';
?>

<div class="adm-page-header mb-3">
  <div>
    <h4 class="adm-page-title">
      <i class="bi bi-chat-dots-fill me-2"></i>Chat Pelanggan
      <?php if ($totalUnread > 0): ?>
        <span class="badge bg-danger ms-2"><?= $totalUnread ?> baru</span>
      <?php endif; ?>
    </h4>
    <p class="adm-page-sub mb-0">Balas pesan dari pelanggan secara real-time</p>
  </div>
</div>

<div class="adm-chat-layout">

  <!-- ── KIRI: Daftar percakapan ─────────────────────────── -->
  <div class="adm-chat-sidebar" id="chatSidebar">
    <div class="adm-chat-search">
      <i class="bi bi-search adm-chat-search-icon"></i>
      <input type="text" id="chatSearch" placeholder="Cari pesanan atau nama..."
             oninput="filterPercakapan(this.value)" class="adm-chat-search-input">
    </div>

    <div class="adm-chat-list" id="chatList">
      <?php if (empty($percakapan) && !$activePesanan): ?>
        <div class="adm-chat-empty">
          <i class="bi bi-chat-square-dots fs-2 d-block mb-2 text-muted"></i>
          <span class="text-muted small">Belum ada percakapan</span>
        </div>
      <?php endif; ?>

      <?php
      // Jika pesanan aktif belum ada di list, tambahkan ke atas
      $ids = array_column($percakapan, 'id');
      if ($activePesanan && !in_array($activePesananId, $ids)) {
          array_unshift($percakapan, array_merge($activePesanan, ['unread'=>0,'last_msg'=>null,'last_msg_at'=>null]));
      }
      foreach ($percakapan as $pc):
        $isActive = $pc['id'] == $activePesananId;
      ?>
        <a href="?pesanan_id=<?= $pc['id'] ?>"
           class="adm-chat-item <?= $isActive ? 'adm-chat-item--active' : '' ?>"
           data-nama="<?= e(strtolower($pc['nama_pembeli'])) ?>"
           data-kode="<?= e(strtolower($pc['kode_pesanan'])) ?>">
          <div class="adm-chat-avatar">
            <?= strtoupper(mb_substr($pc['nama_pembeli'], 0, 1)) ?>
          </div>
          <div class="adm-chat-item-info">
            <div class="adm-chat-item-top">
              <span class="adm-chat-nama"><?= e($pc['nama_pembeli']) ?></span>
              <?php if ($pc['last_msg_at']): ?>
                <span class="adm-chat-time">
                  <?= date('H:i', strtotime($pc['last_msg_at'])) ?>
                </span>
              <?php endif; ?>
            </div>
            <div class="adm-chat-item-bottom">
              <span class="adm-chat-preview">
                <?= $pc['last_msg'] ? e(mb_substr($pc['last_msg'], 0, 40)) . '...' : e($pc['kode_pesanan']) ?>
              </span>
              <?php if ($pc['unread'] > 0): ?>
                <span class="adm-chat-badge"><?= $pc['unread'] ?></span>
              <?php endif; ?>
            </div>
          </div>
        </a>
      <?php endforeach; ?>
    </div>
  </div>

  <!-- ── KANAN: Window Chat ──────────────────────────────── -->
  <div class="adm-chat-main">
    <?php if (!$activePesanan): ?>
      <!-- Placeholder -->
      <div class="adm-chat-placeholder">
        <i class="bi bi-chat-dots" style="font-size:3rem;color:#D4A853;margin-bottom:1rem;display:block"></i>
        <h5 class="text-muted">Pilih percakapan</h5>
        <p class="text-muted small">Klik salah satu pesanan di kiri untuk mulai chat</p>
      </div>

    <?php else: ?>
      <!-- Chat Header -->
      <div class="adm-chat-topbar">
        <div class="adm-chat-avatar adm-chat-avatar--lg">
          <?= strtoupper(mb_substr($activePesanan['nama_pembeli'], 0, 1)) ?>
        </div>
        <div class="flex-grow-1">
          <div class="fw-bold"><?= e($activePesanan['nama_pembeli']) ?></div>
          <div class="small text-muted d-flex align-items-center gap-2">
            <span class="font-monospace"><?= e($activePesanan['kode_pesanan']) ?></span>
            · <?= statusBadge($activePesanan['status']) ?>
            · <?= formatRupiah($activePesanan['total_harga']) ?>
          </div>
        </div>
        <div class="d-flex gap-2">
          <a href="<?= BASE_URL ?>/admin/pesanan_detail.php?id=<?= $activePesanan['id'] ?>"
             class="btn btn-sm btn-outline-primary" title="Lihat detail pesanan">
            <i class="bi bi-receipt"></i>
          </a>
        </div>
      </div>

      <!-- Chat Window -->
      <div class="adm-chat-window" id="chatWindow">
        <div class="adm-chat-loading" id="chatLoading">
          <span class="spinner-border spinner-border-sm me-2"></span>Memuat percakapan...
        </div>
        <div id="chatMessages"></div>
      </div>

      <!-- Input -->
      <div class="adm-chat-input-bar">
        <textarea id="chatInput" class="adm-chat-input" rows="1"
                  placeholder="Tulis balasan..."
                  onkeydown="handleKey(event)"
                  oninput="autoResize(this)"></textarea>
        <button class="adm-chat-send" id="chatSendBtn" onclick="kirimPesan()">
          <i class="bi bi-send-fill"></i>
        </button>
      </div>
    <?php endif; ?>
  </div>

</div>

<style>
/* ── Admin Chat Layout ──────────────────────────────────── */
.adm-chat-layout {
  display:flex;height:calc(100vh - 160px);
  border:1.5px solid #E2E8F0;border-radius:16px;overflow:hidden;
  background:#fff;
}
.adm-chat-sidebar {
  width:300px;flex-shrink:0;border-right:1.5px solid #E2E8F0;
  display:flex;flex-direction:column;background:#FAFBFC;
}
.adm-chat-search {
  padding:.75rem;border-bottom:1px solid #E2E8F0;position:relative;
}
.adm-chat-search-icon {
  position:absolute;left:1.25rem;top:50%;transform:translateY(-50%);color:#94A3B8;
}
.adm-chat-search-input {
  width:100%;border:1.5px solid #E2E8F0;border-radius:10px;
  padding:.5rem .75rem .5rem 2.25rem;font-size:.85rem;
  font-family:'Nunito',sans-serif;outline:none;
}
.adm-chat-search-input:focus { border-color:#8B5E3C; }
.adm-chat-list { flex:1;overflow-y:auto; }
.adm-chat-empty { padding:2rem;text-align:center; }
.adm-chat-item {
  display:flex;align-items:center;gap:.75rem;
  padding:.85rem 1rem;border-bottom:1px solid #F1F5F9;
  text-decoration:none;color:inherit;cursor:pointer;
  transition:background .15s;
}
.adm-chat-item:hover    { background:#F0F9FF; }
.adm-chat-item--active  { background:#FBF7F2;border-left:3px solid #8B5E3C; }
.adm-chat-avatar {
  width:42px;height:42px;background:linear-gradient(135deg,#8B5E3C,#6B4526);
  border-radius:50%;display:flex;align-items:center;justify-content:center;
  font-size:1.1rem;font-weight:800;color:#fff;flex-shrink:0;
}
.adm-chat-avatar--lg { width:44px;height:44px;font-size:1.2rem; }
.adm-chat-item-info { flex:1;min-width:0; }
.adm-chat-item-top  { display:flex;justify-content:space-between;align-items:center;margin-bottom:.15rem; }
.adm-chat-nama      { font-weight:700;font-size:.9rem;color:#1E293B; }
.adm-chat-time      { font-size:.7rem;color:#94A3B8;flex-shrink:0; }
.adm-chat-item-bottom { display:flex;justify-content:space-between;align-items:center; }
.adm-chat-preview   { font-size:.78rem;color:#64748B;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;flex:1; }
.adm-chat-badge     { background:#EF4444;color:#fff;font-size:.65rem;font-weight:800;
                       padding:.1rem .4rem;border-radius:10px;flex-shrink:0;margin-left:.5rem; }
.adm-chat-main      { flex:1;display:flex;flex-direction:column;min-width:0; }
.adm-chat-placeholder { flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center; }
.adm-chat-topbar    { padding:.85rem 1.1rem;border-bottom:1.5px solid #E2E8F0;display:flex;align-items:center;gap:.75rem;flex-shrink:0; }
.adm-chat-window    { flex:1;overflow-y:auto;padding:1rem;display:flex;flex-direction:column;gap:.5rem;background:#F8F4F0;scroll-behavior:smooth; }
.adm-chat-loading   { display:flex;align-items:center;justify-content:center;height:80px;color:#64748B;font-size:.85rem; }
.adm-chat-input-bar { display:flex;align-items:flex-end;gap:.75rem;padding:.75rem 1rem;border-top:1.5px solid #E2E8F0;flex-shrink:0; }
.adm-chat-input     { flex:1;border:1.5px solid #E2E8F0;border-radius:12px;padding:.6rem .9rem;
                       resize:none;outline:none;font-family:'Nunito',sans-serif;font-size:.95rem;
                       max-height:120px;transition:border-color .18s; }
.adm-chat-input:focus { border-color:#8B5E3C; }
.adm-chat-send      { width:42px;height:42px;background:linear-gradient(135deg,#8B5E3C,#6B4526);
                       color:#fff;border:none;border-radius:12px;
                       display:flex;align-items:center;justify-content:center;
                       font-size:1rem;cursor:pointer;flex-shrink:0;transition:all .18s; }
.adm-chat-send:hover { transform:scale(1.08); }
.adm-chat-send:disabled { opacity:.5;cursor:not-allowed;transform:none; }

/* Bubble sama dengan chat.php */
.chat-msg-wrap { display:flex;flex-direction:column;animation:fadeUp .2s ease; }
.chat-msg-wrap--pelanggan { align-items:flex-start; }
.chat-msg-wrap--admin     { align-items:flex-end; }
.chat-bubble { max-width:75%;padding:.6rem .9rem;border-radius:16px;font-size:.9rem;line-height:1.5;word-break:break-word; }
.chat-bubble--pelanggan { background:#fff;border:1px solid #E8D9CC;color:#2D1B0E;border-bottom-left-radius:4px; }
.chat-bubble--admin { background:linear-gradient(135deg,#8B5E3C,#6B4526);color:#fff;border-bottom-right-radius:4px; }
.chat-meta { font-size:.68rem;color:#94A3B8;margin-top:.2rem;display:flex;align-items:center;gap:.3rem; }
.chat-meta--admin { justify-content:flex-end; }
.chat-date-divider { text-align:center;font-size:.72rem;color:#94A3B8;padding:.25rem 0;position:relative; }
.chat-date-divider::before { content:'';position:absolute;top:50%;left:0;right:0;height:1px;background:#E8D9CC;z-index:0; }
.chat-date-divider span { position:relative;z-index:1;background:#F8F4F0;padding:0 .75rem; }
@keyframes fadeUp { from{opacity:0;transform:translateY(6px)} to{opacity:1;transform:translateY(0)} }

@media(max-width:640px) {
  .adm-chat-layout { flex-direction:column;height:auto; }
  .adm-chat-sidebar { width:100%;max-height:200px; }
}
</style>

<?php if ($activePesanan): ?>
<script>
const API    = '<?= BASE_URL ?>/chat_api.php';
const PES_ID = <?= $activePesanan['id'] ?>;
let lastId   = 0;
let lastDate = '';
let isPolling = false;

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

function renderPesan(list) {
  const container = document.getElementById('chatMessages');
  const loading   = document.getElementById('chatLoading');
  if (loading) loading.remove();

  list.forEach(p => {
    if (p.tgl !== lastDate) {
      lastDate = p.tgl;
      const div = document.createElement('div');
      div.className = 'chat-date-divider';
      div.innerHTML = `<span>${p.tgl}</span>`;
      container.appendChild(div);
    }
    const wrap = document.createElement('div');
    // Admin melihat: pelanggan = kiri, admin = kanan
    const side = p.pengirim === 'admin' ? 'admin' : 'pelanggan';
    wrap.className = `chat-msg-wrap chat-msg-wrap--${side}`;
    wrap.innerHTML = `
      <div class="chat-bubble chat-bubble--${side}">
        ${escHtml(p.pesan).replace(/\n/g,'<br>')}
      </div>
      <div class="chat-meta chat-meta--${side}">
        <span>${p.pengirim === 'pelanggan' ? 'Pelanggan' : 'Admin'} · ${p.jam}</span>
      </div>`;
    container.appendChild(wrap);
    lastId = Math.max(lastId, parseInt(p.id));
  });
  scrollBottom();
  // Update badge di sidebar jadi 0 untuk pesanan ini
  const item = document.querySelector(`.adm-chat-item--active .adm-chat-badge`);
  if (item) item.remove();
}

function scrollBottom() {
  const w = document.getElementById('chatWindow');
  w.scrollTop = w.scrollHeight;
}

async function init() {
  try {
    const r   = await fetch(`${API}?action=riwayat&pesanan_id=${PES_ID}`);
    const res = await r.json();
    if (res.ok) renderPesan(res.pesan);
    else document.getElementById('chatLoading').textContent = 'Gagal memuat.';
  } catch(e) { document.getElementById('chatLoading').textContent = 'Error koneksi.'; }
  poll();
}

async function poll() {
  if (isPolling) return;
  isPolling = true;
  try {
    const r   = await fetch(`${API}?action=poll&pesanan_id=${PES_ID}&last_id=${lastId}`);
    const res = await r.json();
    if (res.ok && res.pesan.length) renderPesan(res.pesan);
  } catch(e) {}
  isPolling = false;
  setTimeout(poll, 500);
}

async function kirimPesan() {
  const input = document.getElementById('chatInput');
  const btn   = document.getElementById('chatSendBtn');
  const teks  = input.value.trim();
  if (!teks) return;
  btn.disabled = true; input.value = ''; input.style.height = 'auto';
  const fd = new FormData();
  fd.append('action','kirim'); fd.append('pesanan_id', PES_ID); fd.append('pesan', teks);
  try {
    const r   = await fetch(API, {method:'POST',body:fd});
    const res = await r.json();
    if (res.ok) renderPesan([res.pesan]);
    else alert('Gagal kirim: ' + (res.error||'Error'));
  } catch(e) { alert('Gagal mengirim.'); }
  btn.disabled = false; input.focus();
}

function handleKey(e) { if(e.key==='Enter'&&!e.shiftKey){e.preventDefault();kirimPesan();} }
function autoResize(el) { el.style.height='auto'; el.style.height=Math.min(el.scrollHeight,120)+'px'; }
function filterPercakapan(q) {
  q = q.toLowerCase();
  document.querySelectorAll('.adm-chat-item').forEach(el => {
    const match = el.dataset.nama?.includes(q) || el.dataset.kode?.includes(q);
    el.style.display = match ? '' : 'none';
  });
}

init();
</script>
<?php endif; ?>

<?php include __DIR__ . '/admin_footer.php'; ?>