<?php
session_start();
include '../koneksi.php';

header('Content-Type: application/json');

if(!isset($_SESSION['admin'])){
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
    exit();
}

// Ambil 5 pengaduan terbaru
$query = mysqli_query($koneksi, "
    SELECT id, nama, judul, kategori, status, created_at 
    FROM pengaduan 
    ORDER BY created_at DESC 
    LIMIT 5
");

$notifications = [];
while($row = mysqli_fetch_assoc($query)){
    // Format waktu
    $waktu = date('d/m/Y H:i', strtotime($row['created_at']));
    
    // Cek apakah pengaduan masih baru (belum dibaca)
    $isNew = ($row['status'] == 'baru');
    
    $notifications[] = [
        'id' => $row['id'],
        'nama' => $row['nama'],
        'judul' => $row['judul'],
        'kategori' => $row['kategori'],
        'status' => $row['status'],
        'waktu' => $waktu,
        'is_new' => $isNew
    ];
}

// Hitung total pengaduan baru
$countNew = mysqli_fetch_assoc(mysqli_query($koneksi, "
    SELECT COUNT(*) as total FROM pengaduan WHERE status = 'baru'
"))['total'];

echo json_encode([
    'status' => 'success',
    'notifications' => $notifications,
    'total_new' => $countNew
]);
?>