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

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

// Hitung notifikasi belum dibaca
$query_notif = mysqli_query($koneksi, "SELECT COUNT(*) as total FROM notifications WHERE is_read = 0");
$total_notif = 0;
if($query_notif && mysqli_num_rows($query_notif) > 0){
    $row = mysqli_fetch_assoc($query_notif);
    $total_notif = $row['total'];
}

// Ambil 5 notifikasi terbaru
$query_list = mysqli_query($koneksi, "
    SELECT * FROM notifications 
    ORDER BY created_at DESC 
    LIMIT 5
");

$notifications = [];
if($query_list && mysqli_num_rows($query_list) > 0){
    while($row = mysqli_fetch_array($query_list)){
        $notifications[] = [
            'id' => $row['id'],
            'jenis' => $row['jenis'],
            'pesan' => $row['pesan'],
            'link' => $row['link'],
            'is_read' => $row['is_read'],
            'waktu' => date('d/m/Y H:i', strtotime($row['created_at']))
        ];
    }
}

echo json_encode([
    'total' => $total_notif,
    'list' => $notifications
]);
?>