<?php

function translateToUrdu($text)
{
    global $conn;

    $check = mysqli_query($conn,"SELECT urdu FROM translation_cache WHERE english='$text'");
    $row = mysqli_fetch_assoc($check);

    if($row){
        return $row['urdu'];
    }

    $encoded = urlencode($text);
    $url = "https://api.mymemory.translated.net/get?q={$encoded}&langpair=en|ur";

    $response = file_get_contents($url);
    $data = json_decode($response,true);

    $urdu = $data['responseData']['translatedText'] ?? $text;
    mysqli_query($conn,"INSERT INTO translation_cache(english,urdu) VALUES('$text','$urdu')");
    return $urdu;
}
?>