<?php

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

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

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

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

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

if ($role === "sppg" && $sppg_id > 0) {
    $query = "
        UPDATE notifikasi
        SET is_read = 1
        WHERE role_tujuan = 'sppg'
        AND sppg_id = ?
    ";

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

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

    $stmt->bind_param("i", $sppg_id);
} else {
    $query = "
        UPDATE notifikasi
        SET is_read = 1
        WHERE role_tujuan = ?
    ";

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

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

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

if ($stmt->execute()) {
    response(true, "Semua notifikasi berhasil ditandai dibaca", [
        "role" => $role,
        "sppg_id" => $sppg_id
    ]);
}

response(false, "Gagal menandai semua notifikasi", null);

?>