<?php
require_once __DIR__ . '/auth.php';
$filter = $_GET['filter'] ?? 'all';
$where  = match($filter) { 'open'=>"WHERE t.status IN('Open','In Progress')", 'resolved'=>"WHERE t.status='Resolved'", default=>"" };
$tickets = $pdo->query("SELECT t.*,u.number FROM tickets t LEFT JOIN users u ON t.user_id=u.id $where ORDER BY t.id DESC")->fetchAll();
$viewId = (int)($_GET['id']??0);
$viewTicket = null; $replies = [];
if ($viewId) {
    $st=$pdo->prepare("SELECT t.*,u.number FROM tickets t LEFT JOIN users u ON t.user_id=u.id WHERE t.id=?"); $st->execute([$viewId]); $viewTicket=$st->fetch();
    if($viewTicket){ $st2=$pdo->prepare("SELECT * FROM ticket_replies WHERE ticket_id=? ORDER BY id ASC"); $st2->execute([$viewId]); $replies=$st2->fetchAll(); }
}
?><!DOCTYPE html>
<html lang="en"><head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Support Tickets — PakClub Admin</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
*{box-sizing:border-box;margin:0;padding:0}
body{background:#0b0e18;color:#e8eaf0;font-family:'Segoe UI',sans-serif;display:flex;min-height:100vh}
.main{flex:1;overflow-x:hidden}
.topbar{background:#111827;border-bottom:1px solid rgba(255,255,255,.07);padding:16px 28px;display:flex;align-items:center;justify-content:space-between}
.topbar h2{font-size:20px;font-weight:700;color:#fff}
.content{padding:24px 28px;display:grid;grid-template-columns:1fr 480px;gap:20px;height:calc(100vh - 61px)}
.left-col{overflow-y:auto}
.right-col{overflow-y:auto}
.filter-row{display:flex;gap:6px;margin-bottom:16px}
.fbtn{padding:8px 16px;border-radius:8px;border:none;cursor:pointer;font-size:12px;font-weight:600;color:#9ca3af;background:#111827;transition:all .2s;text-decoration:none;display:inline-block}
.fbtn.active{background:#f26d0f;color:#fff}
.ticket-card{background:#1e2130;border:1px solid rgba(255,255,255,.07);border-radius:12px;padding:14px 16px;margin-bottom:10px;cursor:pointer;transition:all .2s;text-decoration:none;display:block}
.ticket-card:hover,.ticket-card.active{border-color:#f26d0f;background:rgba(242,109,15,.06)}
.tc-head{display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:6px}
.tc-subj{font-size:14px;font-weight:600;color:#fff}
.tc-meta{font-size:11px;color:#6b7280;margin-top:4px}
.pill{padding:3px 10px;border-radius:20px;font-size:11px;font-weight:600}
.pill-Open{background:rgba(245,158,11,.15);color:#f59e0b}
.pill-In.Progress{background:rgba(59,130,246,.15);color:#3b82f6}
.pill-Resolved{background:rgba(34,197,94,.15);color:#22c55e}
/* Chat panel */
.chat-panel{background:#1e2130;border:1px solid rgba(255,255,255,.07);border-radius:14px;height:100%;display:flex;flex-direction:column;overflow:hidden}
.chat-head{padding:16px 20px;border-bottom:1px solid rgba(255,255,255,.07)}
.chat-head h3{font-size:15px;font-weight:700;color:#fff}
.chat-head p{font-size:12px;color:#6b7280;margin-top:3px}
.chat-body{flex:1;overflow-y:auto;padding:16px;display:flex;flex-direction:column;gap:12px}
.bubble{max-width:85%;padding:10px 14px;border-radius:12px;font-size:13px;line-height:1.5;word-break:break-word}
.bubble-user{align-self:flex-start;background:#2d3748;color:#e8eaf0;border-bottom-left-radius:3px}
.bubble-admin{align-self:flex-end;background:#f26d0f;color:#fff;border-bottom-right-radius:3px}
.bubble-time{font-size:10px;opacity:.6;margin-top:4px;text-align:right}
.chat-footer{padding:14px 16px;border-top:1px solid rgba(255,255,255,.07);display:flex;gap:10px;align-items:flex-end}
.chat-footer textarea{flex:1;background:#0f1117;border:1px solid rgba(255,255,255,.1);border-radius:10px;padding:10px 14px;color:#fff;font-size:13px;outline:none;resize:none;max-height:100px}
.chat-footer textarea:focus{border-color:#f26d0f}
.btn{padding:10px 16px;border-radius:10px;border:none;cursor:pointer;font-size:13px;font-weight:600;display:inline-flex;align-items:center;gap:6px;transition:opacity .2s}
.btn:hover{opacity:.85}
.btn-orange{background:#f26d0f;color:#fff}
.btn-gray{background:#374151;color:#e5e7eb}
.empty-chat{flex:1;display:flex;align-items:center;justify-content:center;color:#4b5563;font-size:14px;flex-direction:column;gap:10px}
.no-ticket{background:#1e2130;border:1px solid rgba(255,255,255,.07);border-radius:14px;height:100%;display:flex;align-items:center;justify-content:center;color:#4b5563;font-size:14px;flex-direction:column;gap:8px}
@media(max-width:900px){.content{grid-template-columns:1fr}}
</style>
</head><body>
<?php include 'sidebar.php'; ?>
<div class="main">
  <div class="topbar">
    <h2><i class="fa-solid fa-headset" style="color:#f26d0f;margin-right:10px"></i>Support Tickets</h2>
  </div>
  <div class="content">
    <div class="left-col">
      <div class="filter-row">
        <a href="?filter=all<?= $viewId?"&id=$viewId":'' ?>" class="fbtn <?= $filter==='all'?'active':'' ?>">All</a>
        <a href="?filter=open<?= $viewId?"&id=$viewId":'' ?>" class="fbtn <?= $filter==='open'?'active':'' ?>">Open</a>
        <a href="?filter=resolved<?= $viewId?"&id=$viewId":'' ?>" class="fbtn <?= $filter==='resolved'?'active':'' ?>">Resolved</a>
      </div>
      <?php foreach($tickets as $t): ?>
      <a href="?filter=<?= $filter ?>&id=<?= $t['id'] ?>" class="ticket-card <?= $t['id']===$viewId?'active':'' ?>">
        <div class="tc-head">
          <div class="tc-subj">#<?= $t['id'] ?> — <?= htmlspecialchars($t['subject']) ?></div>
          <span class="pill pill-<?= str_replace(' ','.',$t['status']) ?>"><?= $t['status'] ?></span>
        </div>
        <div class="tc-meta">
          <?= htmlspecialchars($t['number']??'Guest') ?> · UID: <?= $t['uid']??'—' ?> · <?= date('M d H:i',strtotime($t['created_at'])) ?>
        </div>
      </a>
      <?php endforeach; ?>
      <?php if(!$tickets): ?><div style="text-align:center;color:#4b5563;padding:40px">No tickets found</div><?php endif; ?>
    </div>
    <div class="right-col">
      <?php if($viewTicket): $t=$viewTicket; ?>
      <div class="chat-panel">
        <div class="chat-head">
          <h3>#<?= $t['id'] ?> — <?= htmlspecialchars($t['subject']) ?></h3>
          <p><?= htmlspecialchars($t['number']??'Guest') ?> · UID <?= $t['uid'] ?> · <?= $t['status'] ?></p>
          <?php if($t['status']!=='Resolved'): ?>
          <button class="btn btn-gray" style="margin-top:8px;font-size:11px;padding:6px 12px" onclick="closeTicket(<?= $t['id'] ?>)"><i class="fa-solid fa-check-circle"></i> Mark Resolved</button>
          <?php endif; ?>
        </div>
        <div class="chat-body" id="chatBody">
          <!-- Original message -->
          <div class="bubble bubble-user">
            <strong><?= htmlspecialchars($t['subject']) ?></strong><br><?= nl2br(htmlspecialchars($t['message'])) ?>
            <div class="bubble-time"><?= date('M d H:i',strtotime($t['created_at'])) ?></div>
          </div>
          <?php foreach($replies as $r): ?>
          <div class="bubble bubble-<?= strtolower($r['sender_type']) ?>">
            <?= nl2br(htmlspecialchars($r['message'])) ?>
            <div class="bubble-time"><?= $r['sender_type'] ?> · <?= date('M d H:i',strtotime($r['created_at'])) ?></div>
          </div>
          <?php endforeach; ?>
        </div>
        <?php if($t['status']!=='Resolved'): ?>
        <div class="chat-footer">
          <textarea id="replyMsg" placeholder="Type your reply…" rows="2"></textarea>
          <button class="btn btn-orange" onclick="sendReply(<?= $t['id'] ?>)"><i class="fa-solid fa-paper-plane"></i></button>
        </div>
        <?php else: ?>
        <div style="padding:14px 16px;text-align:center;color:#4b5563;font-size:13px;border-top:1px solid rgba(255,255,255,.07)"><i class="fa-solid fa-check-circle" style="color:#22c55e"></i> Ticket resolved — closed</div>
        <?php endif; ?>
      </div>
      <?php else: ?>
      <div class="no-ticket"><i class="fa-solid fa-inbox" style="font-size:32px;color:#374151"></i>Select a ticket to view</div>
      <?php endif; ?>
    </div>
  </div>
</div>
<div id="toast" style="position:fixed;bottom:30px;left:50%;transform:translateX(-50%);background:rgba(20,20,20,.9);backdrop-filter:blur(10px);color:#fff;padding:12px 24px;border-radius:30px;font-size:13px;display:none;z-index:9999"></div>
<script>
document.addEventListener('DOMContentLoaded',()=>{const b=document.getElementById('chatBody');if(b)b.scrollTop=b.scrollHeight;});
function toast(m,ok=true){const t=document.getElementById('toast');t.style.display='block';t.style.borderLeft='3px solid '+(ok?'#22c55e':'#ef4444');t.innerText=m;setTimeout(()=>t.style.display='none',2500);}
function api(data,cb){const fd=new FormData();for(const[k,v]of Object.entries(data))fd.append(k,v);fetch('actions.php',{method:'POST',body:fd}).then(r=>r.json()).then(cb).catch(()=>toast('Network error',false));}
function sendReply(tid){const msg=document.getElementById('replyMsg').value.trim();if(!msg){toast('Enter a message',false);return;}api({action:'reply_ticket',ticket_id:tid,message:msg},r=>{if(r.ok)location.reload();else toast(r.msg,false);});}
function closeTicket(tid){if(!confirm('Mark this ticket as Resolved?'))return;api({action:'close_ticket',ticket_id:tid},r=>{if(r.ok)location.reload();else toast(r.msg,false);});}
</script>
</body></html>
