<?php
// translate.php: Automatic translation endpoint with file cache

define('TONSUI_LOADED', true);
header('Content-Type: application/json');
header('Cache-Control: no-cache, no-store, must-revalidate');
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if (!empty($origin)) {
  header('Access-Control-Allow-Origin: ' . $origin);
} else {
  $scheme = $_SERVER['REQUEST_SCHEME'] ?? 'https';
  $host = $_SERVER['HTTP_HOST'] ?? '';
  if (!empty($host)) header('Access-Control-Allow-Origin', $scheme . '://' . $host);
}
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
header('Access-Control-Allow-Credentials: true');
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
  http_response_code(200);
  echo json_encode(['ok' => true]);
  exit;
}

require_once __DIR__ . '/config.php'; // loads TonEnv
require_once __DIR__ . '/includes/Env.php';

function send_json($data, $status=200){ http_response_code($status); echo json_encode($data); exit; }

try {
  $raw = file_get_contents('php://input');
  $in = json_decode($raw, true);
  $text = isset($in['text']) ? trim((string)$in['text']) : '';
  $target = isset($in['targetLang']) ? strtolower(trim((string)$in['targetLang'])) : '';
  if ($text === '' || $target === '') {
    send_json(['translated' => $text, 'note' => 'missing text or targetLang'], 200);
  }
  if ($target === 'en') {
    send_json(['translated' => $text], 200);
  }

  $cacheDir = __DIR__ . '/cache/translations/' . preg_replace('/[^a-z\-]/i','', $target);
  if (!is_dir($cacheDir)) @mkdir($cacheDir, 0775, true);
  $hash = hash('sha256', $target . '|' . $text);
  $cacheFile = $cacheDir . '/' . $hash . '.txt';
  if (is_file($cacheFile)) {
    $cached = @file_get_contents($cacheFile);
    if ($cached !== false && $cached !== '') {
      send_json(['translated' => $cached, 'cached' => true], 200);
    }
  }

  $provider = TonEnv::get('TRANSLATION_PROVIDER', 'google');
  $translated = '';

  if ($provider === 'deepl') {
    $apiKey = TonEnv::get('DEEPL_API_KEY', '');
    if (!$apiKey) { $provider = 'google'; }
    else {
      $host = TonEnv::get('DEEPL_API_HOST', 'api-free.deepl.com');
      $targetCode = strtoupper($target);
      if ($targetCode === 'PT') $targetCode = 'PT-PT'; // avoid BR default
      $ch = curl_init('https://' . $host . '/v2/translate');
      $payload = http_build_query([
        'auth_key' => $apiKey,
        'text' => $text,
        'target_lang' => $targetCode,
      ]);
      curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $payload,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 10,
      ]);
      $resp = curl_exec($ch);
      $err = curl_error($ch);
      $code = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
      curl_close($ch);
      if ($err) { /* fall through to google */ }
      else if ($code >= 200 && $code < 300 && $resp) {
        $j = json_decode($resp, true);
        if (isset($j['translations'][0]['text'])) {
          $translated = (string)$j['translations'][0]['text'];
        }
      }
    }
  }

  if ($translated === '') {
    // Google Translate v2
    $apiKey = TonEnv::get('GOOGLE_TRANSLATE_API_KEY', '');
    if ($apiKey) {
      $url = 'https://translation.googleapis.com/language/translate/v2?key=' . urlencode($apiKey);
      $body = json_encode(['q' => $text, 'target' => $target]);
      $ch = curl_init($url);
      curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
        CURLOPT_POSTFIELDS => $body,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 10,
      ]);
      $resp = curl_exec($ch);
      $err = curl_error($ch);
      $code = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
      curl_close($ch);
      if (!$err && $code >= 200 && $code < 300 && $resp) {
        $j = json_decode($resp, true);
        if (isset($j['data']['translations'][0]['translatedText'])) {
          $translated = (string)$j['data']['translations'][0]['translatedText'];
        }
      }
    }
  }

  if ($translated === '') {
    // fallback to original text
    send_json(['translated' => $text, 'fallback' => true], 200);
  }

  // write cache
  @file_put_contents($cacheFile, $translated);
  send_json(['translated' => $translated, 'cached' => false], 200);

} catch (Throwable $e) {
  send_json(['translated' => isset($text) ? $text : '', 'error' => true], 200);
}
