<?php
// ============================================================
// FILE: chat.php — Halaman Chat Pelanggan ke Admin
// Akses via: /chat.php?kode=BJ-20250628-0001
// Tidak perlu login — verifikasi via kode pesanan
// ============================================================
require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/auth.php';

$pdo  = db();
$kode = trim($_GET['kode'] ?? '');

// Cari pesanan
$pesanan = null;
if ($kode) {
    $s = $pdo->prepare("SELECT * FROM pesanan WHERE kode_pesanan=? LIMIT 1");
    $s->execute([$kode]);
    $pesanan = $s->fetch();
}

// Jika tidak ada kode, tampilkan form pencarian
$pageTitle  = 'Chat dengan Admin';
$activePage = '';
include __DIR__ . '/includes/header.php';
?>

<div class="container py-4" style="max-width:800px">

  <?php if (!$pesanan): ?>
  <!-- ── Form cari pesanan ──────────────────────────────── -->
  <div class="row justify-content-center">
    <div class="col-md-7">
      <div class="chat-find-card">
        <div class="chat-find-icon"><i class="bi bi-chat-dots-fill"></i></div>
        <h4 class="fw-bold mb-2">Chat dengan Admin</h4>
        <p class="text-muted mb-4">Masukkan kode pesanan untuk memulai chat.</p>
        <form method="GET">
          <div class="mb-3">
            <input type="text" name="kode" class="form-control ck-input text-center"
                   placeholder="Contoh: BJ-20250628-0001" autofocus
                   style="font-size:1.1rem;letter-spacing:.05em">
          </div>
          <button type="submit" class="btn btn-primary-brand w-100">
            <i class="bi bi-search me-2"></i>Cari Pesanan
          </button>
        </form>
        <p class="text-muted small mt-3 mb-0">
          <i class="bi bi-info-circle me-1"></i>
          Kode pesanan ada di email konfirmasi atau halaman
          <a href="<?= BASE_URL ?>/tracking.php">Cek Pesanan</a>.
        </p>
      </div>
    </div>
  </div>

  <?php else: ?>
  <!-- ── Halaman Chat ──────────────────────────────────── -->

  <!-- Header info pesanan -->
  <div class="chat-header-bar mb-3">
    <div class="chat-header-avatar">
      <i class="bi bi-headset"></i>
    </div>
    <div class="flex-grow-1">
      <div class="fw-bold">Admin Budi Jaya</div>
      <div class="small text-muted d-flex align-items-center gap-1">
        <span class="chat-online-dot"></span> Online
        · Pesanan <span class="font-monospace"><?= e($pesanan['kode_pesanan']) ?></span>
      </div>
    </div>
    <div class="text-end">
      <a href="<?= BASE_URL ?>/tracking.php?kode=<?= urlencode($kode) ?>"
         class="btn btn-sm btn-outline-secondary">
        <i class="bi bi-arrow-left me-1"></i>Kembali
      </a>
    </div>
  </div>

  <!-- Info pesanan mini -->
  <div class="chat-pesanan-info mb-3">
    <i class="bi bi-receipt me-2 text-primary"></i>
    <strong><?= e($pesanan['nama_pembeli']) ?></strong>
    · <?= statusBadge($pesanan['status']) ?>
    · <span class="text-muted small"><?= formatRupiah($pesanan['total_harga']) ?></span>
  </div>

  <!-- Chat window -->
  <div class="chat-window" id="chatWindow">
    <div class="chat-loading" id="chatLoading">
      <span class="spinner-border spinner-border-sm me-2"></span>Memuat percakapan...
    </div>
    <div id="chatMessages"></div>
    <div class="chat-typing d-none" id="chatTyping">
      <span class="chat-bubble chat-bubble--admin chat-bubble--typing">
        <span></span><span></span><span></span>
      </span>
    </div>
  </div>

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

  <p class="text-muted text-center mt-2 mb-0" style="font-size:.75rem">
    <i class="bi bi-shield-check me-1 text-success"></i>
    Pesan ini dikirim langsung ke admin toko. Biasanya dibalas dalam jam kerja.
  </p>
  <?php endif; ?>

</div>

<style>
/* ── Chat Layout ─────────────────────────────────────────── */
.chat-find-card {
  background:#fff; border:1.5px solid #EDD9C4; border-radius:20px;
  padding:2.5rem; text-align:center;
  box-shadow:0 4px 24px rgba(139,94,60,.1);
}
.chat-find-icon {
  width:72px;height:72px;background:linear-gradient(135deg,#8B5E3C,#6B4526);
  border-radius:50%;display:inline-flex;align-items:center;justify-content:center;
  font-size:2rem;color:#fff;margin-bottom:1rem;
}
.chat-header-bar {
  display:flex;align-items:center;gap:.75rem;
  background:#fff;border:1.5px solid #EDD9C4;border-radius:14px;
  padding:.85rem 1.1rem;
}
.chat-header-avatar {
  width:46px;height:46px;background:linear-gradient(135deg,#8B5E3C,#6B4526);
  border-radius:50%;display:flex;align-items:center;justify-content:center;
  font-size:1.2rem;color:#fff;flex-shrink:0;
}
.chat-online-dot {
  width:8px;height:8px;background:#10B981;border-radius:50%;display:inline-block;
}
.chat-pesanan-info {
  background:#F0F9FF;border:1px solid #BAE6FD;border-radius:10px;
  padding:.6rem 1rem;font-size:.85rem;
  display:flex;align-items:center;flex-wrap:wrap;gap:.4rem;
}
.chat-window {
  background:#F8F4F0;border:1.5px solid #EDD9C4;border-radius:16px;
  min-height:420px;max-height:520px;overflow-y:auto;
  padding:1rem;display:flex;flex-direction:column;gap:.5rem;
  scroll-behavior:smooth;
}
.chat-loading {
  display:flex;align-items:center;justify-content:center;
  height:100px;color:#92756A;font-size:.85rem;
}
.chat-input-bar {
  display:flex;align-items:flex-end;gap:.75rem;
  background:#fff;border:1.5px solid #EDD9C4;border-radius:14px;
  padding:.6rem .75rem;margin-top:.75rem;
}
.chat-input {
  flex:1;border:none;outline:none;resize:none;
  font-family:'Nunito',sans-serif;font-size:.95rem;
  max-height:120px;background:transparent;
  padding:.25rem 0;line-height:1.5;
}
.chat-send-btn {
  width:40px;height:40px;background:linear-gradient(135deg,#8B5E3C,#6B4526);
  color:#fff;border:none;border-radius:10px;
  display:flex;align-items:center;justify-content:center;
  font-size:1rem;cursor:pointer;flex-shrink:0;
  transition:all .18s;
}
.chat-send-btn:hover { transform:scale(1.08); }
.chat-send-btn:disabled { opacity:.5;cursor:not-allowed;transform:none; }

/* ── Chat Bubbles ───────────────────────────────────────── */
.chat-msg-wrap {
  display:flex;flex-direction:column;
  animation:fadeUp .2s ease;
}
.chat-msg-wrap--pelanggan { align-items:flex-end; }
.chat-msg-wrap--admin     { align-items:flex-start; }

.chat-bubble {
  max-width:75%;padding:.6rem .9rem;border-radius:16px;
  font-size:.9rem;line-height:1.5;word-break:break-word;
  position:relative;
}
.chat-bubble--pelanggan {
  background:linear-gradient(135deg,#8B5E3C,#6B4526);
  color:#fff;border-bottom-right-radius:4px;
}
.chat-bubble--admin {
  background:#fff;border:1px solid #E8D9CC;
  color:#2D1B0E;border-bottom-left-radius:4px;
}
.chat-meta {
  font-size:.68rem;color:#94A3B8;margin-top:.2rem;
  display:flex;align-items:center;gap:.3rem;
}
.chat-meta--pelanggan { justify-content:flex-end; }

/* Typing indicator */
.chat-bubble--typing {
  padding:.7rem 1rem;display:flex;gap:4px;align-items:center;
}
.chat-bubble--typing span {
  width:7px;height:7px;background:#B8A090;border-radius:50%;
  animation:bounce .8s infinite;
}
.chat-bubble--typing span:nth-child(2) { animation-delay:.15s; }
.chat-bubble--typing span:nth-child(3) { animation-delay:.3s; }

/* Date divider */
.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;
}

/* Read tick */
.chat-read { color:rgba(255,255,255,.7);font-size:.65rem; }
.chat-read--read { color:#BAE6FD; }

@keyframes fadeUp {
  from { opacity:0;transform:translateY(6px); }
  to   { opacity:1;transform:translateY(0); }
}
@keyframes bounce {
  0%,80%,100% { transform:translateY(0); }
  40%          { transform:translateY(-6px); }
}
</style>

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

// ── Render pesan ─────────────────────────────────────────
function renderPesan(list, append = true) {
  const container = document.getElementById('chatMessages');
  const loading   = document.getElementById('chatLoading');
  if (loading) loading.remove();

  list.forEach(p => {
    // Date divider
    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');
    wrap.className = `chat-msg-wrap chat-msg-wrap--${p.pengirim}`;
    wrap.dataset.id = p.id;

    const readIcon = p.pengirim === 'pelanggan'
      ? `<span class="chat-read ${p.dibaca == 1 ? 'chat-read--read' : ''}">
           <i class="bi bi-check${p.dibaca == 1 ? '-all' : ''}"></i>
         </span>` : '';

    wrap.innerHTML = `
      <div class="chat-bubble chat-bubble--${p.pengirim}">
        ${escHtml(p.pesan).replace(/\n/g,'<br>')}
      </div>
      <div class="chat-meta chat-meta--${p.pengirim}">
        <span>${p.jam}</span>${readIcon}
      </div>`;
    container.appendChild(wrap);
    lastId = Math.max(lastId, parseInt(p.id));
  });

  scrollBottom();
}

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

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

// ── Load riwayat dulu lalu mulai polling ─────────────────
async function init() {
  try {
    const r   = await fetch(`${API}?action=riwayat&kode=${KODE}&pesanan_id=${PES_ID}`);
    const res = await r.json();
    if (res.ok) renderPesan(res.pesan);
  } catch(e) {
    document.getElementById('chatLoading').textContent = 'Gagal memuat pesan.';
  }
  poll();
}

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

// ── Kirim pesan ───────────────────────────────────────────
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('kode',       KODE);
  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 pesan. Cek koneksi internet.');
  }
  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';
}

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

<?php include __DIR__ . '/includes/footer.php'; ?>