<?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;
$hasil = trim($_POST["hasil"] ?? "");
$catatan = trim($_POST["catatan"] ?? "");
$validasi_oleh = trim($_POST["validasi_oleh"] ?? "Validator Sekolah");

$allowedHasil = ["valid", "tidak_valid"];

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

if (!in_array($hasil, $allowedHasil)) {
    response(false, "Hasil validasi harus valid atau tidak_valid", null);
}

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

function uploadBuktiPengaduan($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;
}

function buatNotifikasi($conn, $role_tujuan, $sppg_id, $judul, $pesan, $link) {
    $sql = "
        INSERT INTO notifikasi
        (
            role_tujuan,
            sppg_id,
            judul,
            pesan,
            link,
            is_read
        )
        VALUES (?, ?, ?, ?, ?, 0)
    ";

    $stmt = $conn->prepare($sql);

    if (!$stmt) {
        return false;
    }

    if ($sppg_id === null) {
        $sppg_id = 0;
    }

    $stmt->bind_param(
        "sisss",
        $role_tujuan,
        $sppg_id,
        $judul,
        $pesan,
        $link
    );

    return $stmt->execute();
}

$foto_url = uploadBuktiPengaduan(
    "foto",
    ["jpg", "jpeg", "png", "webp"],
    5 * 1024 * 1024,
    "validasi_awal",
    "foto_validasi_awal"
);

$file_url = uploadBuktiPengaduan(
    "file",
    ["pdf", "doc", "docx", "jpg", "jpeg", "png", "webp"],
    10 * 1024 * 1024,
    "validasi_awal",
    "file_validasi_awal"
);

$checkSql = "
    SELECT 
        p.id,
        p.sppg_id,
        p.status,
        p.status_alur,
        p.kategori,
        s.nama AS sppg_nama
    FROM pengaduan p
    LEFT JOIN sppg s ON s.id = p.sppg_id
    WHERE p.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", null);
}

$pengaduan = $checkResult->fetch_assoc();

$allowedStatusAlur = ["Menunggu Validasi", "Baru"];

if (
    !in_array($pengaduan["status_alur"], $allowedStatusAlur) &&
    !empty($pengaduan["status_alur"])
) {
    response(false, "Pengaduan ini tidak berada pada tahap validasi awal", [
        "status_alur" => $pengaduan["status_alur"]
    ]);
}

if ($hasil === "valid") {
    $status = "Diproses";
    $status_alur = "Valid";
    $validasi_status = "valid";
    $hasil_validasi = "valid";
} else {
    $status = "Selesai";
    $status_alur = "Tidak Valid";
    $validasi_status = "tidak_valid";
    $hasil_validasi = "tidak_valid";
}

$updateSql = "
    UPDATE pengaduan
    SET
        status = ?,
        status_alur = ?,
        validasi_status = ?,
        validasi_catatan = ?,
        validasi_oleh = ?,
        validasi_at = NOW()
    WHERE id = ?
";

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

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

$updateStmt->bind_param(
    "sssssi",
    $status,
    $status_alur,
    $validasi_status,
    $catatan,
    $validasi_oleh,
    $pengaduan_id
);

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

$putaran_ke = 1;

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

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

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

$insertStmt->bind_param(
    "iissss",
    $pengaduan_id,
    $putaran_ke,
    $catatan,
    $foto_url,
    $file_url,
    $hasil_validasi
);

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

/*
    NOTIFIKASI OTOMATIS SETELAH VALIDASI AWAL
    - Admin selalu dapat notif
    - Pemerintah selalu dapat notif
    - SPPG terkait dapat notif jika pengaduan valid
*/

$sppg_id_notif = isset($pengaduan["sppg_id"]) ? (int) $pengaduan["sppg_id"] : 0;
$sppg_nama = $pengaduan["sppg_nama"] ?? "SPPG terkait";
$kategori_pengaduan = $pengaduan["kategori"] ?? "-";

if ($hasil === "valid") {
    $judulNotif = "Pengaduan Valid Perlu Ditindaklanjuti";
    $pesanNotif = "Pengaduan kategori {$kategori_pengaduan} terhadap {$sppg_nama} telah divalidasi benar oleh validator. Pemerintah dan SPPG perlu menindaklanjuti dengan bukti.";
} else {
    $judulNotif = "Pengaduan Tidak Valid";
    $pesanNotif = "Pengaduan kategori {$kategori_pengaduan} terhadap {$sppg_nama} dinyatakan tidak valid oleh validator.";
}

buatNotifikasi(
    $conn,
    "admin",
    $sppg_id_notif,
    $judulNotif,
    $pesanNotif,
    "/admin/pengaduan"
);

buatNotifikasi(
    $conn,
    "pemerintah",
    $sppg_id_notif,
    $judulNotif,
    $pesanNotif,
    "/pengaduan"
);

if ($hasil === "valid" && $sppg_id_notif > 0) {
    buatNotifikasi(
        $conn,
        "sppg",
        $sppg_id_notif,
        $judulNotif,
        $pesanNotif,
        "/pengaduan"
    );
}

response(true, "Validasi awal pengaduan berhasil disimpan dengan bukti", [
    "pengaduan_id" => $pengaduan_id,
    "hasil" => $hasil,
    "status" => $status,
    "status_alur" => $status_alur,
    "validasi_status" => $validasi_status,
    "foto_url" => $foto_url,
    "file_url" => $file_url,
    "notifikasi" => [
        "admin" => true,
        "pemerintah" => true,
        "sppg" => ($hasil === "valid" && $sppg_id_notif > 0)
    ]
]);

?>