<?php
ob_start();
require("includes/check_auth_user.php");
require("includes/dbconnect.php");
include('includes/function.php');

$admin = $_SESSION["admin_" . $dbname];
$zdb = $_SESSION["zdbyear_" . $dbname];
$myyear = $_SESSION[$myyear];
mysqli_select_db($conn, $zdb);
$zroot = $_SESSION["zdbroot"];

mysqli_set_charset($conn, "utf8mb4");

// Fetch records
$result = mysqli_query($conn, "SELECT `srl`,`name`,`surname`,`midname`,`lastname` FROM `visaform` WHERE `name_urdu` IS NULL OR `name_urdu`=''");

// Transliteration function
function transliterate($text){
    $url = "https://inputtools.google.com/request?text=".urlencode($text)."&itc=ur-t-i0-und&num=1";

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

    return $data[1][0][1][0] ?? $text;
}

while($row = mysqli_fetch_assoc($result)){

    $name = $row['name'];
    $surname = $row['surname'];
    $midname = $row['midname'];
    $lastname = $row['lastname'];

    // Convert to Urdu
    $name_urdu = transliterate($name);
    $surname_urdu = transliterate($surname);
    $midname_urdu = transliterate($midname);
    $lastname_urdu = transliterate($lastname);
    
    $stmt = $conn->prepare("
    UPDATE visaform 
    SET name_urdu=?, surname_urdu=?, midname_urdu=?, lastname_urdu=? 
    WHERE srl=?
");

$stmt->bind_param("ssssi", $name_urdu, $surname_urdu, $midname_urdu, $lastname_urdu, $row['srl']);
$stmt->execute();

echo "✔ Updated SRL: ".$row['srl']."<br>";
}
?>