<?php
    
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Allow-Methods: GET, OPTIONS");
header("Content-Type: application/json");

if ($_SERVER["REQUEST_METHOD"] === "OPTIONS") {
    exit;
}

require "../../config/database.php";
require "../../helpers/response.php";

$role = trim($_GET["role"] ?? "");
$sppg_id = isset($_GET["sppg_id"]) ? (int) $_GET["sppg_id"] : 0;

if ($role === "") {
    response(false, "Role tidak valid", []);
}

if ($role === "publik" || $role === "masyarakat") {
    response(true, "Tidak ada notifikasi untuk publik", []);
}

if ($role === "sppg") {
    if ($sppg_id > 0) {
        $query = "
            SELECT
                id,
                role_tujuan,
                user_id,
                sppg_id,
                judul,
                pesan,
                link,
                is_read,
                created_at
            FROM notifikasi
            WHERE role_tujuan = 'sppg'
            AND sppg_id = ?
            ORDER BY id DESC
            LIMIT 30
        ";

        $stmt = $conn->prepare($query);

        if (!$stmt) {
            response(false, "Prepare notifikasi SPPG gagal: " . $conn->error, []);
        }

        $stmt->bind_param("i", $sppg_id);
    } else {
        $query = "
            SELECT
                id,
                role_tujuan,
                user_id,
                sppg_id,
                judul,
                pesan,
                link,
                is_read,
                created_at
            FROM notifikasi
            WHERE role_tujuan = 'sppg'
            ORDER BY id DESC
            LIMIT 30
        ";

        $stmt = $conn->prepare($query);

        if (!$stmt) {
            response(false, "Prepare notifikasi SPPG gagal: " . $conn->error, []);
        }
    }
} else {
    $query = "
        SELECT
            id,
            role_tujuan,
            user_id,
            sppg_id,
            judul,
            pesan,
            link,
            is_read,
            created_at
        FROM notifikasi
        WHERE role_tujuan = ?
        ORDER BY id DESC
        LIMIT 30
    ";

    $stmt = $conn->prepare($query);

    if (!$stmt) {
        response(false, "Prepare notifikasi gagal: " . $conn->error, []);
    }

    $stmt->bind_param("s", $role);
}

$stmt->execute();

$result = $stmt->get_result();

$data = [];

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

response(true, "Notifikasi berhasil diambil", $data);

?>