<?php

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Allow-Methods: DELETE, 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);
}

$checkSql = "
    SELECT id, bukti_url
    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);
}

$data = $checkResult->fetch_assoc();

$query = "DELETE FROM pengaduan WHERE id = ?";

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

if ($stmt->execute()) {
    if (!empty($data["bukti_url"])) {
        $filename = basename($data["bukti_url"]);
        $filePath = "../../uploads/pengaduan/" . $filename;

        if (file_exists($filePath)) {
            @unlink($filePath);
        }
    }

    response(true, "Pengaduan berhasil dihapus", [
        "id" => $id
    ]);
}

response(false, "Gagal menghapus pengaduan", null);

?>