<?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";

$sppg_id = isset($_POST["sppg_id"]) ? intval($_POST["sppg_id"]) : 0;
$nama = trim($_POST["nama"] ?? "");
$kontak = trim($_POST["kontak"] ?? "");
$kategori = trim($_POST["kategori"] ?? "");
$isi = trim($_POST["isi"] ?? "");

if ($sppg_id <= 0) {
    response(false, "SPPG yang diadukan wajib dipilih", null);
}

if ($nama === "") {
    response(false, "Nama wajib diisi", null);
}

if ($kategori === "") {
    response(false, "Kategori wajib diisi", null);
}

if ($isi === "") {
    response(false, "Isi pengaduan wajib diisi", null);
}

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)
    ";

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

    if (!$stmtNotif) {
        return [
            "success" => false,
            "role" => $role_tujuan,
            "error" => "Prepare notif gagal: " . $conn->error
        ];
    }

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

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

    if (!$stmtNotif->execute()) {
        return [
            "success" => false,
            "role" => $role_tujuan,
            "error" => "Execute notif gagal: " . $stmtNotif->error
        ];
    }

    return [
        "success" => true,
        "id" => $stmtNotif->insert_id,
        "role" => $role_tujuan,
        "error" => null
    ];
}

$cek = $conn->prepare("
    SELECT 
        id,
        nama,
        kabupaten,
        provinsi
    FROM sppg
    WHERE id = ?
    LIMIT 1
");

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

$cek->bind_param("i", $sppg_id);
$cek->execute();

$cekResult = $cek->get_result();

if ($cekResult->num_rows === 0) {
    response(false, "SPPG yang dipilih tidak ditemukan", null);
}

$sppgData = $cekResult->fetch_assoc();

$sppgNama = $sppgData["nama"] ?? "SPPG terkait";
$sppgKabupaten = $sppgData["kabupaten"] ?? "-";
$sppgProvinsi = $sppgData["provinsi"] ?? "-";

if (!isset($_FILES["foto"]) || $_FILES["foto"]["error"] !== UPLOAD_ERR_OK) {
    response(false, "Foto bukti pengaduan wajib diupload", null);
}

$allowed = ["jpg", "jpeg", "png", "webp"];
$filename = $_FILES["foto"]["name"];
$tmp = $_FILES["foto"]["tmp_name"];
$size = $_FILES["foto"]["size"];

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

if (!in_array($ext, $allowed)) {
    response(false, "Format foto harus JPG, JPEG, PNG, atau WEBP", null);
}

if ($size > 5 * 1024 * 1024) {
    response(false, "Ukuran foto maksimal 5MB", null);
}

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

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

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

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

$bukti_url = "http://localhost/backend/uploads/pengaduan/" . $newName;

$query = "
    INSERT INTO pengaduan
    (
        sppg_id,
        nama,
        kontak,
        kategori,
        isi,
        bukti_url,
        status,
        status_alur
    )
    VALUES (?, ?, ?, ?, ?, ?, 'Baru', 'Menunggu Validasi')
";

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

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

$stmt->bind_param(
    "isssss",
    $sppg_id,
    $nama,
    $kontak,
    $kategori,
    $isi,
    $bukti_url
);

if ($stmt->execute()) {
    $pengaduan_id = $stmt->insert_id;

    $judulNotif = "Pengaduan Baru Masuk";
    $pesanNotif = "Pengaduan baru kategori {$kategori} terhadap {$sppgNama} ({$sppgKabupaten}, {$sppgProvinsi}) telah dikirim masyarakat dan menunggu validasi.";

    $notifAdmin = buatNotifikasi(
        $conn,
        "admin",
        $sppg_id,
        $judulNotif,
        $pesanNotif,
        "/admin/pengaduan"
    );

    $notifValidator = buatNotifikasi(
        $conn,
        "validator",
        $sppg_id,
        $judulNotif,
        $pesanNotif,
        "/validator/pengaduan"
    );

    response(true, "Pengaduan berhasil dikirim", [
        "id" => $pengaduan_id,
        "sppg_id" => $sppg_id,
        "status" => "Baru",
        "status_alur" => "Menunggu Validasi",
        "bukti_url" => $bukti_url,
        "notifikasi" => [
            "admin" => $notifAdmin,
            "validator" => $notifValidator
        ]
    ]);
}

response(false, "Gagal mengirim pengaduan: " . $stmt->error, null);

?>