<?php
header('Content-Type: application/json');
header("Access-Control-Allow-Origin: *"); // bisa diganti domain tertentu untuk keamanan

// include koneksi
include "connection.php";

// ambil input JSON dari Android
$data = json_decode(file_get_contents("php://input"), true);
$idUser  = isset($data["idUser"]) ? intval($data["idUser"]) : 0;
$detailPertanyaan = isset($data["pertanyaan"]) ? trim($data["pertanyaan"]) : "";

// validasi input
if (empty($detailPertanyaan)) {
    echo json_encode(["status" => "error", "message" => "Pertanyaan kosong"]);
    exit;
}

// ---------------------------
// simpan pertanyaan ke tblPertanyaan
// ---------------------------
$stmt = $con->prepare("INSERT INTO tblPertanyaan (idUser, detailPertanyaan) VALUES (?, ?)");
$stmt->bind_param("is", $idUser, $detailPertanyaan);
$stmt->execute();
$idPertanyaan = $con->insert_id; // ambil id auto_increment
$stmt->close();

// ---------------------------
// cari jawaban di tblPengetahuan berdasarkan polaPertanyaan
// ---------------------------
// gunakan ORDER BY LENGTH(polaPertanyaan) DESC agar pola lebih spesifik dicari dulu
$sql = "SELECT detailJawaban 
        FROM tblPengetahuan 
        WHERE LOWER(?) LIKE CONCAT('%', LOWER(polaPertanyaan), '%') 
        ORDER BY LENGTH(polaPertanyaan) DESC
        LIMIT 1";

$stmt = $con->prepare($sql);
$stmt->bind_param("s", $detailPertanyaan);
$stmt->execute();
$result = $stmt->get_result();

if ($row = $result->fetch_assoc()) {
    $detailJawaban = $row["detailJawaban"];
} else {
    $detailJawaban = "Maaf, saya belum punya jawaban untuk pertanyaan ini.";
}
$stmt->close();

// Rapikan jawaban biar mirip ChatGPT
// ---------------------------
function formatJawaban($text) {
    // Tambahkan baris baru setelah titik
    $text = preg_replace('/\.\s*/', ".<br><br>", $text);

    // Tambah emoji otomatis (opsional)
    $text = str_replace("Jangan", "⚡ Jangan", $text);
    $text = str_replace("Setiap", "🌱 Setiap", $text);

    return $text;
}
$detailJawaban = formatJawaban($detailJawaban);


// ---------------------------
// simpan jawaban ke tblJawaban
// ---------------------------
$stmt = $con->prepare("INSERT INTO tblJawaban (idPertanyaan, detailJawaban) VALUES (?, ?)");
$stmt->bind_param("is", $idPertanyaan, $detailJawaban);
$stmt->execute();
$stmt->close();

// ---------------------------
// kirim response ke Android
// ---------------------------
echo json_encode([
    "status" => "success",
    "idPertanyaan" => $idPertanyaan,
    "detailPertanyaan" => $detailPertanyaan,
    "detailJawaban" => $detailJawaban
], JSON_UNESCAPED_UNICODE);

$con->close();
?>
