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

$pengaduan_id = isset($_GET["pengaduan_id"]) ? (int) $_GET["pengaduan_id"] : 0;

if ($pengaduan_id <= 0) {
    response(false, "ID pengaduan tidak valid", null);
}

$pengaduanSql = "
    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
    WHERE p.id = ?
    LIMIT 1
";

$pengaduanStmt = $conn->prepare($pengaduanSql);

if (!$pengaduanStmt) {
    response(false, "Prepare pengaduan gagal: " . $conn->error, null);
}

$pengaduanStmt->bind_param("i", $pengaduan_id);
$pengaduanStmt->execute();

$pengaduanResult = $pengaduanStmt->get_result();

if ($pengaduanResult->num_rows === 0) {
    response(false, "Pengaduan tidak ditemukan", null);
}

$pengaduan = $pengaduanResult->fetch_assoc();

$riwayatSql = "
    SELECT
        id,
        pengaduan_id,
        putaran_ke,
        role_pengirim,
        tahap,
        catatan,
        foto_url,
        file_url,
        hasil_validasi,
        created_at
    FROM pengaduan_tindak_lanjut
    WHERE pengaduan_id = ?
    ORDER BY putaran_ke ASC, id ASC
";

$riwayatStmt = $conn->prepare($riwayatSql);

if (!$riwayatStmt) {
    response(false, "Prepare riwayat gagal: " . $conn->error, null);
}

$riwayatStmt->bind_param("i", $pengaduan_id);
$riwayatStmt->execute();

$riwayatResult = $riwayatStmt->get_result();

$riwayat = [];

while ($row = $riwayatResult->fetch_assoc()) {
    $riwayat[] = $row;
}

response(true, "Riwayat pengaduan berhasil diambil", [
    "pengaduan" => $pengaduan,
    "riwayat" => $riwayat
]);

?>