<?php

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

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

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

/*
    Bisa menerima:
    1. JSON:
       {
         "pengaduan_id": 6,
         "hasil": "selesai",
         "catatan": "Perbaikan sudah sesuai.",
         "validasi_oleh": "Validator Sekolah"
       }

    2. GET untuk tes:
       validasi_perbaikan.php?pengaduan_id=6&hasil=masih_bermasalah&catatan=belum%20sesuai&validasi_oleh=Validator
*/

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

if (!is_array($json)) {
    $json = [];
}

$data = array_merge($_GET, $_POST, $json);

$pengaduan_id = 0;

if (isset($data["pengaduan_id"])) {
    $pengaduan_id = (int) $data["pengaduan_id"];
} elseif (isset($data["id"])) {
    $pengaduan_id = (int) $data["id"];
}

$hasil = trim($data["hasil"] ?? "");
$catatan = trim($data["catatan"] ?? "");
$validasi_oleh = trim($data["validasi_oleh"] ?? "Validator Sekolah");

$allowedHasil = ["selesai", "masih_bermasalah"];

if ($pengaduan_id <= 0) {
    response(false, "ID pengaduan tidak valid", [
        "method" => $_SERVER["REQUEST_METHOD"],
        "data_diterima" => $data,
        "raw_body" => $raw
    ]);
}

if (!in_array($hasil, $allowedHasil)) {
    response(false, "Hasil validasi perbaikan harus selesai atau masih_bermasalah", [
        "hasil_diterima" => $hasil
    ]);
}

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

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

$checkStmt = $conn->prepare($checkSql);

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

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

$checkResult = $checkStmt->get_result();

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

$pengaduan = $checkResult->fetch_assoc();

if ($pengaduan["status_alur"] !== "Menunggu Validasi Perbaikan") {
    response(false, "Pengaduan belum berada pada tahap validasi perbaikan", [
        "status_alur" => $pengaduan["status_alur"]
    ]);
}

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

$putaranStmt = $conn->prepare($putaranSql);

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

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

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

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

if ($putaran_ke <= 0) {
    $putaran_ke = 1;
}

if ($hasil === "selesai") {
    $status = "Selesai";
    $status_alur = "Selesai";
    $hasil_validasi = "selesai";
} else {
    $status = "Diproses";
    $status_alur = "Masih Bermasalah";
    $hasil_validasi = "masih_bermasalah";
}

$insertSql = "
    INSERT INTO pengaduan_tindak_lanjut
    (
        pengaduan_id,
        putaran_ke,
        role_pengirim,
        tahap,
        catatan,
        hasil_validasi
    )
    VALUES (?, ?, 'validator', 'validasi_perbaikan', ?, ?)
";

$insertStmt = $conn->prepare($insertSql);

if (!$insertStmt) {
    response(false, "Prepare insert validasi perbaikan gagal: " . $conn->error, null);
}

$insertStmt->bind_param(
    "iiss",
    $pengaduan_id,
    $putaran_ke,
    $catatan,
    $hasil_validasi
);

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

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

$updateStmt = $conn->prepare($updateSql);

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

$updateStmt->bind_param("ssi", $status, $status_alur, $pengaduan_id);

if (!$updateStmt->execute()) {
    response(false, "Gagal update status pengaduan: " . $updateStmt->error, null);
}

response(true, "Validasi perbaikan berhasil disimpan", [
    "pengaduan_id" => $pengaduan_id,
    "putaran_ke" => $putaran_ke,
    "hasil" => $hasil,
    "status" => $status,
    "status_alur" => $status_alur,
    "catatan" => $catatan,
    "validasi_oleh" => $validasi_oleh
]);

?>