<?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", []);
}

/*
    Notifikasi dari tabel notifikasi:
    - admin lihat role_tujuan admin
    - pemerintah lihat role_tujuan pemerintah
    - validator lihat role_tujuan validator
    - sppg lihat role_tujuan sppg sesuai sppg_id
*/

if ($role === "sppg") {
    if ($sppg_id > 0) {
        $sql = "
            SELECT 
                id,
                role_tujuan,
                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($sql);

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

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

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

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

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

    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;
}

/*
    Tambahan notifikasi sistem khusus admin.
    Ini tetap mempertahankan notif lama seperti pengaduan baru, stok rendah, dll.
    Tapi dibuat formatnya sama seperti tabel notifikasi.
*/

if ($role === "admin") {
    $sqlPengaduan = "
        SELECT COUNT(*) AS total
        FROM pengaduan
        WHERE status = 'Baru'
    ";

    $resultPengaduan = $conn->query($sqlPengaduan);

    if ($resultPengaduan && $row = $resultPengaduan->fetch_assoc()) {
        $total = (int) $row["total"];

        if ($total > 0) {
            $data[] = [
                "id" => "pengaduan-baru",
                "role_tujuan" => "admin",
                "sppg_id" => null,
                "judul" => "Pengaduan Baru",
                "pesan" => "Terdapat " . $total . " pengaduan baru yang perlu ditinjau.",
                "link" => "/admin/pengaduan",
                "is_read" => 0,
                "created_at" => date("Y-m-d H:i:s")
            ];
        }
    }

    $cekBahan = $conn->query("SHOW TABLES LIKE 'bahan_makanan'");

    if ($cekBahan && $cekBahan->num_rows > 0) {
        $sqlBahan = "
            SELECT COUNT(*) AS total
            FROM bahan_makanan
            WHERE stok > 0 AND stok <= 10
        ";

        $resultBahan = $conn->query($sqlBahan);

        if ($resultBahan && $row = $resultBahan->fetch_assoc()) {
            $total = (int) $row["total"];

            if ($total > 0) {
                $data[] = [
                    "id" => "stok-bahan-rendah",
                    "role_tujuan" => "admin",
                    "sppg_id" => null,
                    "judul" => "Stok Bahan Rendah",
                    "pesan" => "Terdapat " . $total . " bahan makanan dengan stok rendah.",
                    "link" => "/admin/sppg",
                    "is_read" => 0,
                    "created_at" => date("Y-m-d H:i:s")
                ];
            }
        }
    }

    $cekOmprengan = $conn->query("SHOW TABLES LIKE 'omprengan'");

    if ($cekOmprengan && $cekOmprengan->num_rows > 0) {
        $sqlOmprengan = "
            SELECT COALESCE(SUM(jumlah), 0) AS total
            FROM omprengan
            WHERE kondisi IN ('Rusak Ringan', 'Rusak Berat', 'Hilang')
        ";

        $resultOmprengan = $conn->query($sqlOmprengan);

        if ($resultOmprengan && $row = $resultOmprengan->fetch_assoc()) {
            $total = (int) $row["total"];

            if ($total > 0) {
                $data[] = [
                    "id" => "omprengan-bermasalah",
                    "role_tujuan" => "admin",
                    "sppg_id" => null,
                    "judul" => "Omprengan Bermasalah",
                    "pesan" => "Terdapat " . $total . " unit omprengan/peralatan yang bermasalah.",
                    "link" => "/admin/sppg",
                    "is_read" => 0,
                    "created_at" => date("Y-m-d H:i:s")
                ];
            }
        }
    }
}

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

?>