<?php
// Anza session moja tu
if (session_status() === PHP_SESSION_NONE) session_start();

require_once __DIR__ . '/db.php';

// Angalia login
if (!isset($_SESSION['user_id'])) {
    if ($_SERVER['REQUEST_METHOD'] === 'POST' || isset($_GET['poll'])) {
        header('Content-Type: application/json');
        echo json_encode(['success'=>false,'error'=>'not logged in']);
    } else {
        header('Location: login.php');
    }
    exit;
}

$uid = (int)$_SESSION['user_id'];
$SUPPORT_DISPLAY = '+44 8523 879 323';

// ── AJAX: tuma message ────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');
    $raw = file_get_contents('php://input');
    $json = json_decode($raw, true);
    $msg = trim($json['message'] ?? $_POST['message'] ?? '');

    if ($msg === '') {
        echo json_encode(['success'=>false,'error'=>'empty','uid'=>$uid,'raw'=>$raw,'post'=>$_POST]);
        exit;
    }

    $stmt = $conn->prepare("INSERT INTO support_messages (user_id, sender, message) VALUES (?, 'user', ?)");
    if (!$stmt) {
        echo json_encode(['success'=>false,'error'=>'prepare: '.$conn->error]);
        exit;
    }
    $stmt->bind_param('is', $uid, $msg);
    if (!$stmt->execute()) {
        echo json_encode(['success'=>false,'error'=>'execute: '.$stmt->error]);
        exit;
    }
    echo json_encode(['success'=>true,'id'=>$conn->insert_id,'time'=>date('H:i')]);
    exit;
}

// ── AJAX: poll messages mpya ──────────────────────────────
if (isset($_GET['poll'])) {
    header('Content-Type: application/json');
    $after = (int)($_GET['after'] ?? 0);
    $conn->query("UPDATE support_messages SET is_read=1 WHERE user_id=$uid AND sender='admin' AND is_read=0");
    $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;
}

// ── Load page ya chat ─────────────────────────────────────
$conn->query("UPDATE support_messages SET is_read=1 WHERE user_id=$uid AND sender='admin' AND is_read=0");
$res = $conn->query("SELECT id,sender,message,created_at FROM support_messages WHERE user_id=$uid ORDER BY id ASC LIMIT 200");
$messages = [];
while ($r = $res->fetch_assoc()) $messages[] = $r;
$last_id = empty($messages) ? 0 : (int)end($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>WFM - Message</title>
<style>
*{margin:0;padding:0;box-sizing:border-box}
body{font-family:'Segoe UI',sans-serif;background:#e5ddd5;height:100dvh;display:flex;flex-direction:column;overflow:hidden}
.chat-header{background:linear-gradient(135deg,#1a6b3c,#25913f);padding:10px 14px;display:flex;align-items:center;gap:12px;flex-shrink:0;box-shadow:0 2px 8px rgba(0,0,0,.25)}
.back-btn{width:34px;height:34px;display:flex;align-items:center;justify-content:center;text-decoration:none;flex-shrink:0}
.back-btn svg{width:22px;height:22px;fill:#fff}
.agent-avatar{width:42px;height:42px;border-radius:50%;background:linear-gradient(135deg,#25d366,#128c7e);display:flex;align-items:center;justify-content:center;flex-shrink:0;font-size:20px;box-shadow:0 0 0 2px rgba(255,255,255,.3)}
.agent-info{flex:1;min-width:0}
.agent-name{font-size:15px;font-weight:700;color:#fff;line-height:1.2}
.agent-status{font-size:11px;color:rgba(255,255,255,.8);margin-top:2px;display:flex;align-items:center;gap:4px}
.status-dot{width:7px;height:7px;border-radius:50%;background:#4cff82;display:inline-block}
.chat-bg{flex:1;overflow-y:auto;padding:12px 10px 8px;background:#e5ddd5;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='%23c5b9ae' fill-opacity='0.15'%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");-webkit-overflow-scrolling:touch}
.date-divider{text-align:center;margin:8px 0}
.date-divider span{background:rgba(225,245,254,.85);color:#555;font-size:11px;font-weight:600;padding:4px 12px;border-radius:10px;box-shadow:0 1px 2px rgba(0,0,0,.1)}
.bubble-row{display:flex;margin-bottom:4px;align-items:flex-end;gap:6px}
.bubble-row.user{flex-direction:row-reverse}
.bubble-row.admin{flex-direction:row}
.bubble-avatar{width:28px;height:28px;border-radius:50%;background:linear-gradient(135deg,#25d366,#128c7e);display:flex;align-items:center;justify-content:center;font-size:13px;flex-shrink:0;margin-bottom:2px}
.bubble{max-width:72%;padding:7px 10px 18px;border-radius:8px;font-size:14px;line-height:1.45;color:#111;position:relative;word-break:break-word;box-shadow:0 1px 2px rgba(0,0,0,.13)}
.bubble.user{background:#dcf8c6;border-bottom-right-radius:2px}
.bubble.admin{background:#fff;border-bottom-left-radius:2px}
.bubble.user::after{content:'';position:absolute;bottom:0;right:-7px;width:0;height:0;border-left:8px solid #dcf8c6;border-bottom:8px solid transparent}
.bubble.admin::after{content:'';position:absolute;bottom:0;left:-7px;width:0;height:0;border-right:8px solid #fff;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:#888;white-space:nowrap}
.tick{width:14px;height:10px}
.typing-indicator{display:none;padding:8px 12px 18px;background:#fff;border-radius:8px;border-bottom-left-radius:2px;max-width:70px;box-shadow:0 1px 2px rgba(0,0,0,.13);margin-bottom:4px}
.typing-indicator.show{display:inline-block}
.typing-dots{display:flex;gap:4px;align-items:center;height:14px}
.typing-dots span{width:7px;height:7px;border-radius:50%;background:#999;animation:bounce 1.2s infinite;display:inline-block}
.typing-dots span:nth-child(2){animation-delay:.2s}
.typing-dots span:nth-child(3){animation-delay:.4s}
@keyframes bounce{0%,60%,100%{transform:translateY(0)}30%{transform:translateY(-5px)}}
.input-bar{background:#f0f0f0;padding:8px 10px;display:flex;align-items:flex-end;gap:8px;flex-shrink:0;border-top:1px solid #ddd}
.input-wrap{flex:1;background:#fff;border-radius:22px;padding:9px 14px;display:flex;align-items:flex-end;box-shadow:0 1px 2px rgba(0,0,0,.08)}
#msgInput{flex:1;border:none;outline:none;font-size:15px;font-family:inherit;color:#111;resize:none;max-height:100px;background:transparent;line-height:1.4}
#msgInput::placeholder{color:#8696a0}
.send-btn{width:46px;height:46px;border-radius:50%;background:linear-gradient(135deg,#1a6b3c,#25913f);border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;flex-shrink:0;box-shadow:0 2px 6px rgba(0,0,0,.2);transition:transform .1s}
.send-btn:active{transform:scale(.93)}
.send-btn svg{width:22px;height:22px;fill:#fff}
.empty-chat{display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%;gap:12px;padding:40px 20px}
.empty-chat .lock-icon{font-size:32px}
.empty-chat p{font-size:12px;color:#888;text-align:center;background:rgba(225,245,254,.85);padding:8px 16px;border-radius:10px;max-width:260px;line-height:1.5}
</style>
</head>
<body>

<div class="chat-header">
  <a href="account.php" class="back-btn">
    <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="agent-avatar">🎧</div>
  <div class="agent-info">
    <div class="agent-name"><?= htmlspecialchars($SUPPORT_DISPLAY) ?></div>
    <div class="agent-status"><span class="status-dot"></span> Online</div>
  </div>
</div>

<div class="chat-bg" id="chatBody">
  <?php if (empty($messages)): ?>
    <div class="empty-chat" id="emptyState">
      <span class="lock-icon">🔒</span>
      <p>Messages are end-to-end encrypted. Send a message to start chatting with support.</p>
    </div>
  <?php else: ?>
    <?php
    $prev_date = '';
    foreach ($messages as $m):
      $d = date('Y-m-d', strtotime($m['created_at']));
      $today = date('Y-m-d');
      $yesterday = date('Y-m-d', strtotime('-1 day'));
      if ($d !== $prev_date):
        $label = ($d===$today)?'Today':(($d===$yesterday)?'Yesterday':date('d M Y',strtotime($d)));
    ?>
      <div class="date-divider"><span><?= $label ?></span></div>
    <?php $prev_date=$d; endif; ?>
      <div class="bubble-row <?= $m['sender'] ?>" data-id="<?= $m['id'] ?>">
        <?php if ($m['sender']==='admin'): ?>
          <div class="bubble-avatar">🎧</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']==='user'): ?>
              <svg class="tick" viewBox="0 0 18 11" fill="none">
                <path d="M1 5.5L5.5 10L17 1" stroke="#4fc3f7" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
                <path d="M5 5.5L9.5 10L17 1" stroke="#4fc3f7" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
            <?php endif; ?>
          </div>
        </div>
      </div>
    <?php endforeach; ?>
  <?php endif; ?>

  <div class="bubble-row admin" id="typingRow" style="display:none">
    <div class="bubble-avatar">🎧</div>
    <div class="typing-indicator show">
      <div class="typing-dots"><span></span><span></span><span></span></div>
    </div>
  </div>
</div>

<div class="input-bar">
  <div class="input-wrap">
    <textarea id="msgInput" 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>

<script>
let lastId = <?= $last_id ?>;
const chatBody = document.getElementById('chatBody');
const input = document.getElementById('msgInput');

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){
  if(m.id && chatBody.querySelector(`[data-id="${m.id}"]`)) return;
  const empty=document.getElementById('emptyState');
  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==='user'?`<svg class="tick" viewBox="0 0 18 11" fill="none"><path d="M1 5.5L5.5 10L17 1" stroke="#4fc3f7" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/><path d="M5 5.5L9.5 10L17 1" stroke="#4fc3f7" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></svg>`:'';
  const avatar=m.sender==='admin'?`<div class="bubble-avatar">🎧</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');
  tr ? chatBody.insertBefore(row,tr) : chatBody.appendChild(row);
  scrollBottom(true);
}

async function sendMessage(){
  const msg=input.value.trim();
  if(!msg) return;
  const now=new Date().toTimeString().slice(0,5);
  appendBubble({sender:'user',message:msg,time:now});
  input.value='';
  input.style.height='auto';
  try{
    const res=await fetch('message.php',{
      method:'POST',
      headers:{'Content-Type':'application/json'},
      body:JSON.stringify({message:msg})
    });
    const ct=res.headers.get('content-type')||'';
    if(!ct.includes('application/json')){
      console.error('Non-JSON:',await res.text());
      return;
    }
    const data=await res.json();
    if(data.success){
      lastId=Math.max(lastId,parseInt(data.id));
    } else {
      console.error('Imeshindwa:',data);
    }
  }catch(e){
    console.error('Kosa:',e);
  }
}

async function poll(){
  try{
    const res=await fetch(`message.php?poll=1&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==='admin'){
        hideTyping();
        appendBubble(m);
      }
      lastId=Math.max(lastId,parseInt(m.id));
    });
  }catch(e){}
}
setInterval(poll,3000);

function hideTyping(){
  const t=document.getElementById('typingRow');
  if(t) t.style.display='none';
}
</script>
</body>
</html>