<?php
// File: API_KONEKSI/notifikasi/list_notifikasi.php

header('Content-Type: application/json');
include '../config/koneksi.php';

if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    $user_id = $_GET['user_id'] ?? '';

    if (empty($user_id)) {
        echo json_encode(["status" => "gagal", "pesan" => "User ID tidak valid", "data" => []]);
        exit;
    }

    // Ambil data notifikasi berdasarkan user_id, diurutkan dari yang terbaru (tambahkan user_id = 0 untuk notif global)
    $stmt = $conn->prepare("
        SELECT notif_id, tipe_notif, target_id, judul_tx, pesan_tx, is_read, created_at 
        FROM dat_notifikasi 
        WHERE (user_id = ? OR user_id = 0) AND deleted_st = 0 
        ORDER BY created_at DESC
    ");
    $stmt->bind_param("s", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();

    $data = [];
    while ($row = $result->fetch_assoc()) {
        $data[] = $row;
    }

    if (count($data) > 0) {
        echo json_encode(["status" => "sukses", "pesan" => "Data notifikasi ditemukan", "data" => $data]);
    } else {
        echo json_encode(["status" => "kosong", "pesan" => "Belum ada notifikasi", "data" => []]);
    }
    
    $stmt->close();
} else {
    echo json_encode(["status" => "gagal", "pesan" => "Metode tidak valid", "data" => []]);
}

$conn->close();
?>