<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Stichoza\GoogleTranslate\GoogleTranslate;
use Illuminate\Support\Facades\Cache;


class TransliterateController extends Controller
{
    //  public function transliterateTamil(Request $request)
    // {
    //     $request->validate([
    //         'text' => 'required|string',
    //     ]);

    //     $text = $request->input('text');

    //     // Translate English → Tamil
    //     $tr = new GoogleTranslate('ta'); // target language Tamil
    //     $translated = $tr->translate($text);

    //     return response()->json([
    //         'tamil' => $translated
    //     ]);
    // }
    public function transliterateTamil(Request $request)
{
    $request->validate([
        'text' => 'required|string',
    ]);

    $text = $request->text;

    // Create unique cache key for the text
    $cacheKey = 'trans_ta_' . md5($text);

    // If already translated → return instantly (0ms)
    if (cache()->has($cacheKey)) {
        return response()->json([
            'tamil' => cache()->get($cacheKey),
            'cached' => true
        ]);
    }

    // Translate only if not cached
    $tr = new \Stichoza\GoogleTranslate\GoogleTranslate('ta');
    $translated = $tr->translate($text);

    // Save to cache for 1 month (you can increase)
    cache()->put($cacheKey, $translated, 60 * 60 * 24 * 30);

    return response()->json([
        'tamil' => $translated,
        'cached' => false
    ]);
}

}
