<?php

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

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

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

$pengaduan_id = isset($_POST["pengaduan_id"]) ? (int) $_POST["pengaduan_id"] : 0;
$catatan = trim($_POST["catatan"] ?? "");
$pengirim = trim($_POST["pengirim"] ?? "Pemerintah");

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

if ($catatan === "") {
    response(false, "Catatan tindak lanjut wajib diisi", null);
}

function uploadBukti($fieldName, $allowedExt, $maxSize, $folder, $prefix) {
    if (!isset($_FILES[$fieldName]) || $_FILES[$fieldName]["error"] !== UPLOAD_ERR_OK) {
        response(false, ucfirst($fieldName) . " bukti wajib diupload", null);
    }

    $filename = $_FILES[$fieldName]["name"];
    $tmp = $_FILES[$fieldName]["tmp_name"];
    $size = $_FILES[$fieldName]["size"];

    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));

    if (!in_array($ext, $allowedExt)) {
        response(false, "Format " . $fieldName . " tidak valid", null);
    }

    if ($size > $maxSize) {
        response(false, "Ukuran " . $fieldName . " terlalu besar", null);
    }

    $uploadDir = "../../uploads/pengaduan/" . $folder . "/";

    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0777, true);
    }

    $newName = $prefix . "_" . time() . "_" . rand(1000, 9999) . "." . $ext;
    $targetPath = $uploadDir . $newName;

    if (!move_uploaded_file($tmp, $targetPath)) {
        response(false, "Gagal mengupload " . $fieldName, null);
    }

    return "http://localhost/backend/uploads/pengaduan/" . $folder . "/" . $newName;
}

$foto_url = uploadBukti(
    "foto",
    ["jpg", "jpeg", "png", "webp"],
    5 * 1024 * 1024,
    "tindak_lanjut",
    "foto_tindak_lanjut"
);

$file_url = uploadBukti(
    "file",
    ["pdf", "doc", "docx", "jpg", "jpeg", "png", "webp"],
    10 * 1024 * 1024,
    "tindak_lanjut",
    "file_tindak_lanjut"
);

$checkSql = "
    SELECT id, status_alur
    FROM pengaduan
    WHERE id = ?
    LIMIT 1
";

$checkStmt = $conn->prepare($checkSql);
$checkStmt->bind_param("i", $pengaduan_id);
$checkStmt->execute();

$checkResult = $checkStmt->get_result();

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

$pengaduan = $checkResult->fetch_assoc();

$allowedStatusAlur = ["Valid", "Masih Bermasalah", "Tindak Lanjut Ulang"];

if (!in_array($pengaduan["status_alur"], $allowedStatusAlur)) {
    response(false, "Pengaduan belum bisa ditindaklanjuti pemerintah", [
        "status_alur" => $pengaduan["status_alur"]
    ]);
}

$putaranSql = "
    SELECT COALESCE(MAX(putaran_ke), 0) AS putaran_terakhir
    FROM pengaduan_tindak_lanjut
    WHERE pengaduan_id = ?
";

$putaranStmt = $conn->prepare($putaranSql);
$putaranStmt->bind_param("i", $pengaduan_id);
$putaranStmt->execute();

$putaranResult = $putaranStmt->get_result();
$putaranData = $putaranResult->fetch_assoc();

$putaran_ke = ((int) $putaranData["putaran_terakhir"]) + 1;

$insertSql = "
    INSERT INTO pengaduan_tindak_lanjut
    (
        pengaduan_id,
        putaran_ke,
        role_pengirim,
        tahap,
        catatan,
        foto_url,
        file_url
    )
    VALUES (?, ?, 'pemerintah', 'tindak_lanjut_pemerintah', ?, ?, ?)
";

$insertStmt = $conn->prepare($insertSql);
$insertStmt->bind_param(
    "iisss",
    $pengaduan_id,
    $putaran_ke,
    $catatan,
    $foto_url,
    $file_url
);

if (!$insertStmt->execute()) {
    response(false, "Gagal menyimpan tindak lanjut pemerintah: " . $insertStmt->error, null);
}

$updateSql = "
    UPDATE pengaduan
    SET
        status = 'Diproses',
        status_alur = 'Diproses Pemerintah'
    WHERE id = ?
";

$updateStmt = $conn->prepare($updateSql);
$updateStmt->bind_param("i", $pengaduan_id);
$updateStmt->execute();

response(true, "Tindak lanjut pemerintah berhasil disimpan dengan bukti", [
    "pengaduan_id" => $pengaduan_id,
    "putaran_ke" => $putaran_ke,
    "pengirim" => $pengirim,
    "foto_url" => $foto_url,
    "file_url" => $file_url,
    "status" => "Diproses",
    "status_alur" => "Diproses Pemerintah"
]);

?>