<?php
// core/i18n.php
// - lang=tr/en -> session + cookie + users.lang update + PRG redirect
// - global translate helper: t('key')
// - dictionary: $GLOBALS['I18N_DICT']

if (session_status() === PHP_SESSION_NONE) { session_start(); }

function nl_allowed_lang($l){
  return in_array($l, ['tr','en'], true) ? $l : 'tr';
}

function nl_db_update_user_lang(int $uid, string $lang){
  // PDO
  if (isset($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof PDO) {
    $pdo = $GLOBALS['pdo'];
    $st = $pdo->prepare("UPDATE users SET lang=? WHERE id=?");
    $st->execute([$lang, $uid]);
    return;
  }
  // mysqli
  if (isset($GLOBALS['db']) && $GLOBALS['db'] instanceof mysqli) {
    $db = $GLOBALS['db'];
    $st = $db->prepare("UPDATE users SET lang=? WHERE id=?");
    $st->bind_param("si", $lang, $uid);
    $st->execute();
    $st->close();
    return;
  }
}

// ---- dictionary (tek kaynak) ----
$GLOBALS['I18N_DICT'] = $GLOBALS['I18N_DICT'] ?? [
  'tr' => [
    'lang_tr' => 'Türkçe',
    'lang_en' => 'English',
    'change_pass' => 'Şifre Değiştir',
    'logout' => 'Güvenli Çıkış',
    'current_pass' => 'Mevcut Şifre',
    'new_pass' => 'Yeni Şifre',
    'new_pass2' => 'Yeni Şifre (Tekrar)',
    'save' => 'Kaydet',
    'cancel' => 'Vazgeç',
  ],
  'en' => [
    'lang_tr' => 'Turkish',
    'lang_en' => 'English',
    'change_pass' => 'Change Password',
    'logout' => 'Secure Logout',
    'current_pass' => 'Current Password',
    'new_pass' => 'New Password',
    'new_pass2' => 'New Password (Again)',
    'save' => 'Save',
    'cancel' => 'Cancel',
  ],
];

// ---- translate helper (GLOBAL) ----
if (!function_exists('t')) {
  function t(string $key, array $repl = []) : string {
    $lang = $_SESSION['lang'] ?? ($_COOKIE['lang'] ?? 'tr');
    $lang = in_array($lang, ['tr','en'], true) ? $lang : 'tr';

    $D = $GLOBALS['I18N_DICT'] ?? [];
    $text = $D[$lang][$key] ?? ($D['tr'][$key] ?? $key);

    foreach ($repl as $k => $v) {
      $text = str_replace('{'.$k.'}', (string)$v, $text);
    }
    return $text;
  }
}

// ---- handle lang switch ----
if (isset($_GET['lang'])) {
  $l = nl_allowed_lang($_GET['lang']);

  $_SESSION['lang'] = $l;
  setcookie('lang', $l, time() + 60*60*24*365, '/');

  $uid = (int)($_SESSION['user_id'] ?? 0);
  if ($uid > 0) {
    nl_db_update_user_lang($uid, $l);
  }

  // PRG: URL'den lang temizle
  $q = $_GET;
  unset($q['lang']);
  $base = strtok($_SERVER['REQUEST_URI'], '?');
  $to = $base . (count($q) ? ('?' . http_build_query($q)) : '');
  header("Location: $to");
  exit;
}

// current lang
$lang = nl_allowed_lang($_SESSION['lang'] ?? ($_COOKIE['lang'] ?? 'tr'));
$_SESSION['lang'] = $lang;
