<?php
require_once __DIR__.'/../includes/db.php';
require_once __DIR__.'/../includes/auth.php';
include __DIR__.'/../includes/header.php';

$act = $_GET['a'] ?? 'list';

if (!function_exists('esc')) {
  function esc($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
}

/* ================= ACTION: REPLY ================= */

if ($act === 'reply' && $_SERVER['REQUEST_METHOD'] === 'POST') {

$session_id = trim($_POST['session_id'] ?? '');
$message    = trim($_POST['message'] ?? '');

if ($session_id !== '' && $message !== '') {

$stmt = $mysqli->prepare("SELECT nama, hp FROM pengaduan_chat WHERE session_id=? ORDER BY id DESC LIMIT 1");
$stmt->bind_param('s', $session_id);
$stmt->execute();
$row = $stmt->get_result()->fetch_assoc();

$nama = $row['nama'] ?? '-';
$hp   = $row['hp'] ?? '-';

$sender = 'admin';

$msg = mb_substr($message, 0, 2000, 'UTF-8');

$ins = $mysqli->prepare("INSERT INTO pengaduan_chat(session_id,nama,hp,sender,message,status) VALUES (?,?,?,?,?,'open')");
$ins->bind_param('sssss', $session_id, $nama, $hp, $sender, $msg);
$ins->execute();

}

header('Location: pengaduan_chat.php?a=view&sid='.urlencode($session_id));
exit;

}


/* ================= ACTION STATUS ================= */

if ($act === 'set_status') {

$session_id = trim($_GET['sid'] ?? '');
$status     = trim($_GET['status'] ?? 'open');

if (!in_array($status, ['open','closed'], true)) $status='open';

if ($session_id !== '') {

$stmt = $mysqli->prepare("UPDATE pengaduan_chat SET status=? WHERE session_id=?");
$stmt->bind_param('ss', $status, $session_id);
$stmt->execute();

}

header('Location: pengaduan_chat.php?a=view&sid='.urlencode($session_id));
exit;

}


/* ================= FETCH AJAX ================= */

if ($act === 'fetch') {

header('Content-Type: application/json; charset=utf-8');

$session_id = trim($_GET['sid'] ?? '');
$after_id   = (int)($_GET['after_id'] ?? 0);

$stmt = $mysqli->prepare("
SELECT id,sender,message,created_at
FROM pengaduan_chat
WHERE session_id=? AND id>?
ORDER BY id ASC
LIMIT 200
");

$stmt->bind_param('si',$session_id,$after_id);
$stmt->execute();

$res=$stmt->get_result();

$items=[];

while($r=$res->fetch_assoc()){
$items[]=$r;
}

echo json_encode(['ok'=>true,'items'=>$items]);
exit;

}


/* ================= LIST SESSION ================= */

if ($act === 'list') {

$q = trim($_GET['q'] ?? '');

$where = "";
$params = [];
$types = "";

if ($q !== '') {

$where = "WHERE nama LIKE ? OR hp LIKE ? OR message LIKE ?";
$like = "%$q%";
$params = [$like,$like,$like];
$types="sss";

}

$sql="

SELECT t.session_id,t.nama,t.hp,t.status,t.created_at,
t.sender AS last_sender,
t.message AS last_message
FROM pengaduan_chat t
INNER JOIN(
SELECT session_id,MAX(id) id
FROM pengaduan_chat
GROUP BY session_id
) x ON t.session_id=x.session_id AND t.id=x.id

$where

ORDER BY t.created_at DESC

";

$stmt=$mysqli->prepare($sql);

if($params) $stmt->bind_param($types,...$params);

$stmt->execute();

$sessions=$stmt->get_result();

}


/* ================= VIEW CHAT ================= */

if ($act === 'view') {

$sid = trim($_GET['sid'] ?? '');

$info=null;

$stmt=$mysqli->prepare("
SELECT session_id,nama,hp,status
FROM pengaduan_chat
WHERE session_id=?
LIMIT 1
");

$stmt->bind_param('s',$sid);
$stmt->execute();
$info=$stmt->get_result()->fetch_assoc();

$messages=[];

$stmt=$mysqli->prepare("
SELECT id,sender,message,created_at
FROM pengaduan_chat
WHERE session_id=?
ORDER BY id ASC
");

$stmt->bind_param('s',$sid);
$stmt->execute();

$res=$stmt->get_result();

while($r=$res->fetch_assoc()){
$messages[]=$r;
}

}

?>


<style>

/* CARD */

.card{
background:#fff;
padding:22px;
border-radius:14px;
box-shadow:0 8px 30px rgba(0,0,0,.08);
}

/* INPUT */

.input{
width:100%;
padding:10px;
border-radius:6px;
border:1px solid #d1d5db;
}

/* BUTTON */

.btn{
padding:8px 14px;
border-radius:6px;
border:none;
cursor:pointer;
}

.btn.primary{
background:#ef4444;
color:#fff;
}

.btn.small{
font-size:12px;
padding:6px 10px;
background:#0f172a;
color:#fff;
}

/* TABLE */

.table{
width:100%;
border-collapse:separate;
border-spacing:0;
margin-top:15px;
font-size:14px;
}

.table thead{
background:#f1f5f9;
}

.table th{
padding:12px;
text-align:left;
color:#475569;
border-bottom:2px solid #e5e7eb;
}

.table td{
padding:14px 12px;
border-bottom:1px solid #f1f5f9;
}

.table tr:hover{
background:#f9fafb;
}

/* BADGE */

.badge{
padding:4px 8px;
border-radius:6px;
font-size:12px;
}

.badge.open{
background:#dcfce7;
color:#166534;
}

.badge.closed{
background:#fee2e2;
color:#991b1b;
}

/* CHAT */

.chat-box{
background:#fff;
border-radius:14px;
padding:15px;
height:420px;
overflow:auto;
border:1px solid #e5e7eb;
}

.bubble{
max-width:75%;
padding:10px 12px;
border-radius:14px;
margin:10px 0;
font-size:14px;
}

.bubble.admin{
background:#ecfdf5;
margin-left:auto;
}

.bubble.warga{
background:#fef2f2;
}

.time{
font-size:11px;
opacity:.6;
margin-top:5px;
}

</style>



<div class="card">

<div style="display:flex;justify-content:space-between;align-items:center">

<h2 style="color:#b91c1c">💬 Pengaduan Warga</h2>

<?php if($act==='view'): ?>

<a class="btn primary" href="pengaduan_chat.php">← Kembali</a>

<?php endif; ?>

</div>



<?php if($act==='list'): ?>

<table class="table">

<thead>
<tr>
<th>Nama</th>
<th>HP</th>
<th>Status</th>
<th>Pesan Terakhir</th>
<th>Waktu</th>
<th>Aksi</th>
</tr>
</thead>

<tbody>

<?php if(!$sessions || $sessions->num_rows==0): ?>

<tr>
<td colspan="6">Belum ada pengaduan.</td>
</tr>

<?php endif; ?>

<?php while($s=$sessions->fetch_assoc()): ?>

<tr>

<td><?php echo esc($s['nama']); ?></td>

<td><?php echo esc($s['hp']); ?></td>

<td>

<?php if($s['status']=='open'): ?>

<span class="badge open">OPEN</span>

<?php else: ?>

<span class="badge closed">CLOSED</span>

<?php endif; ?>

</td>

<td><?php echo esc($s['last_message']); ?></td>

<td><?php echo esc($s['created_at']); ?></td>

<td>

<a class="btn small primary"
href="pengaduan_chat.php?a=view&sid=<?php echo esc($s['session_id']); ?>">
Buka
</a>

</td>

</tr>

<?php endwhile; ?>

</tbody>

</table>



<?php elseif($act==='view'): ?>

<div class="chat-box" id="chatBox">

<?php foreach($messages as $m): ?>

<div class="bubble <?php echo $m['sender']=='admin'?'admin':'warga'; ?>">

<div><?php echo nl2br(esc($m['message'])); ?></div>

<div class="time"><?php echo esc($m['created_at']); ?></div>

</div>

<?php endforeach; ?>

</div>



<form method="post" action="pengaduan_chat.php?a=reply" style="margin-top:10px">

<input type="hidden" name="session_id" value="<?php echo esc($sid); ?>">

<textarea class="input" name="message" rows="3" placeholder="Balas pesan..." required></textarea>

<div style="text-align:right;margin-top:8px">

<button class="btn primary">Kirim</button>

</div>

</form>

<?php endif; ?>

</div>


<script>

const box=document.getElementById('chatBox');

if(box){
box.scrollTop=box.scrollHeight;
}

</script>

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