<?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";

/*
    API: List Pengaduan

    Digunakan untuk:
    - Halaman Pengaduan masyarakat/admin/pemerintah/SPPG
    - Halaman Validasi Pengaduan validator
    - Menampilkan status_alur agar filter frontend tidak kosong
*/

$query = "
    SELECT
        p.id,
        p.sppg_id,
        p.sekolah_id,

        s.nama AS sppg_nama,
        s.provinsi AS sppg_provinsi,
        s.kabupaten AS sppg_kabupaten,

        sk.nama_sekolah,
        sk.alamat AS alamat_sekolah,

        p.nama,
        p.kontak,
        p.kategori,
        p.isi,
        p.bukti_url,

        p.status,
        p.status_alur,

        p.validasi_status,
        p.validasi_catatan,
        p.validasi_oleh,
        p.validasi_at,

        p.created_at
    FROM pengaduan p
    LEFT JOIN sppg s ON s.id = p.sppg_id
    LEFT JOIN sekolah sk ON sk.id = p.sekolah_id
    ORDER BY p.id DESC
";

$result = $conn->query($query);

if (!$result) {
    response(false, "Gagal mengambil data pengaduan: " . $conn->error, []);
}

$data = [];

while ($row = $result->fetch_assoc()) {
    /*
        Normalisasi data lama:
        Kalau status_alur kosong, anggap masih menunggu validasi.
        Ini membantu data lama tetap muncul di halaman validator.
    */
    if ($row["status_alur"] === null || trim($row["status_alur"]) === "") {
        $row["status_alur"] = "Menunggu Validasi";
    }

    if ($row["status"] === null || trim($row["status"]) === "") {
        $row["status"] = "Baru";
    }

    /*
        Normalisasi data SPPG lama:
        Kalau data lama belum punya sppg_id, frontend tetap bisa tampil rapi.
    */
    if ($row["sppg_nama"] === null || trim($row["sppg_nama"]) === "") {
        $row["sppg_nama"] = "SPPG belum dipilih";
    }

    if ($row["sppg_kabupaten"] === null || trim($row["sppg_kabupaten"]) === "") {
        $row["sppg_kabupaten"] = "-";
    }

    if ($row["sppg_provinsi"] === null || trim($row["sppg_provinsi"]) === "") {
        $row["sppg_provinsi"] = "-";
    }

    if ($row["nama_sekolah"] === null || trim($row["nama_sekolah"]) === "") {
        $row["nama_sekolah"] = null;
    }

    if ($row["alamat_sekolah"] === null || trim($row["alamat_sekolah"]) === "") {
        $row["alamat_sekolah"] = null;
    }

    $data[] = $row;
}

response(true, "Data pengaduan berhasil diambil", $data);

?>