<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

function getSinonim($kata) {
    $url = "https://www.sinonimkata.com/search.php";
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, "q=" . urlencode($kata));
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    $html = curl_exec($ch);
    curl_close($ch);
    
    if (!$html) return [];
    
    // Coba ambil bagian sinonim sampai antonim (kalau ada antonim)
    if (preg_match("/sinonim<\/td>(.*?)antonim/s", $html, $bagian)) {
        // Ada antonim, ambil sinonim saja
        $bagianSinonim = $bagian[1];
    } else if (preg_match("/sinonim<\/td>(.*?)<\/table>/s", $html, $bagian)) {
        // Tidak ada antonim, ambil sampai akhir tabel
        $bagianSinonim = $bagian[1];
    } else {
        // Kata tidak ditemukan
        return [$kata];
    }
    
    // Ambil semua kata dari tag <a>
    preg_match_all("/>([^<]+)<\/a>/", $bagianSinonim, $matches);
    
    $sinonim = [];
    foreach ($matches[1] as $s) {
        $bersih = strtolower(trim($s));
        if (!empty($bersih)) {
            $sinonim[] = $bersih;
        }
    }
    
    // Tambahkan kata itu sendiri
    $sinonim[] = strtolower($kata);
    
    return array_unique($sinonim);
}

// Test kata dengan antonim
echo "<b>Sinonim 'pintar':</b>";
echo "<pre>"; print_r(getSinonim("pintar")); echo "</pre>";

// Test kata tanpa antonim
echo "<b>Sinonim 'fakta':</b>";
echo "<pre>"; print_r(getSinonim("narasumber")); echo "</pre>";
?>