<?php

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

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

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

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

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

$input = json_decode(file_get_contents("php://input"), true);

$status = trim($input["status"] ?? "");

$allowedStatus = ["Baru", "Diproses", "Selesai"];

if ($status === "") {
    response(false, "Status wajib diisi", null);
}

if (!in_array($status, $allowedStatus)) {
    response(false, "Status tidak valid", null);
}

$checkSql = "SELECT id FROM pengaduan WHERE id = ? LIMIT 1";
$checkStmt = $conn->prepare($checkSql);
$checkStmt->bind_param("i", $id);
$checkStmt->execute();

$checkResult = $checkStmt->get_result();

if ($checkResult->num_rows === 0) {
    response(false, "Data pengaduan tidak ditemukan", null);
}

$query = "
    UPDATE pengaduan
    SET status = ?
    WHERE id = ?
";

$stmt = $conn->prepare($query);
$stmt->bind_param("si", $status, $id);

if ($stmt->execute()) {
    response(true, "Status pengaduan berhasil diperbarui", [
        "id" => $id,
        "status" => $status
    ]);
}

response(false, "Gagal memperbarui status pengaduan", null);

?>