<?php
// admin/i18n_lib.php
// Central language engine for the whole admin project.
// It supports:
// - ui_lang from app_settings/session/GET
// - exact server-side t() translations
// - broad smart phrase replacement for dynamic messages
// - JSON payload for the global DOM translator

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

if (!function_exists('ua_i18n_sanitize_lang')) {
  function ua_i18n_sanitize_lang($v): string {
    return ((string)$v === 'en') ? 'en' : 'ar';
  }
}

if (!function_exists('ua_i18n_setting_get')) {
  function ua_i18n_setting_get(string $key, $default = null) {
    $conn = $GLOBALS['conn'] ?? null;
    if (!($conn instanceof mysqli)) return $default;
    try {
      if (function_exists('setting_get')) return setting_get($conn, $key, $default);
      if (function_exists('get_app_setting')) return get_app_setting($conn, $key, (string)$default);
      $k = $conn->real_escape_string($key);
      $res = @$conn->query("SHOW TABLES LIKE 'app_settings'");
      if (!$res || !$res->num_rows) return $default;
      $cols = [];
      $cr = @$conn->query("SHOW COLUMNS FROM `app_settings`");
      if ($cr) { while ($r = $cr->fetch_assoc()) $cols[(string)($r['Field'] ?? '')] = true; }
      $keyCol = isset($cols['setting_key']) ? 'setting_key' : (isset($cols['key']) ? 'key' : '');
      $valCol = isset($cols['setting_value']) ? 'setting_value' : (isset($cols['value']) ? 'value' : '');
      if ($keyCol === '' || $valCol === '') return $default;
      $q = @$conn->query("SELECT `$valCol` AS v FROM `app_settings` WHERE `$keyCol`='$k' LIMIT 1");
      if ($q && $q->num_rows) return $q->fetch_assoc()['v'] ?? $default;
    } catch (Throwable $e) {}
    return $default;
  }
}

if (!function_exists('ua_i18n_setting_set')) {
  function ua_i18n_setting_set(string $key, $value): void {
    $conn = $GLOBALS['conn'] ?? null;
    if (!($conn instanceof mysqli)) return;
    try {
      if (function_exists('setting_set')) { @setting_set($conn, $key, $value); return; }
      if (function_exists('set_app_setting')) { @set_app_setting($conn, $key, (string)$value); return; }
    } catch (Throwable $e) {}
  }
}

if (!function_exists('ua_i18n_current_lang')) {
  function ua_i18n_current_lang(): string {
    if (session_status() === PHP_SESSION_NONE) { @session_start(); }

    if (isset($_GET['set_lang'])) {
      $v = ua_i18n_sanitize_lang($_GET['set_lang']);
      $_SESSION['ui_lang'] = $v;
      ua_i18n_setting_set('ui_lang', $v);

      // Keep the old behavior: apply language then remove set_lang from URL.
      $uri = $_SERVER['REQUEST_URI'] ?? '';
      if ($uri && !headers_sent()) {
        $u = parse_url($uri);
        $path = $u['path'] ?? $uri;
        $query = [];
        if (!empty($u['query'])) {
          parse_str($u['query'], $query);
          unset($query['set_lang']);
        }
        $new = $path . (count($query) ? ('?' . http_build_query($query)) : '');
        header('Location: ' . $new);
        exit;
      }
      return $v;
    }

    if (isset($_POST['ui_lang'])) {
      $v = ua_i18n_sanitize_lang($_POST['ui_lang']);
      $_SESSION['ui_lang'] = $v;
      return $v;
    }

    if (!empty($_SESSION['ui_lang'])) {
      return ua_i18n_sanitize_lang($_SESSION['ui_lang']);
    }

    $dbLang = ua_i18n_setting_get('ui_lang', 'ar');
    $dbLang = ua_i18n_sanitize_lang($dbLang);
    $_SESSION['ui_lang'] = $dbLang;
    return $dbLang;
  }
}

if (!function_exists('ua_i18n_load_flat_file')) {
  function ua_i18n_load_flat_file(string $lang): array {
    $file = __DIR__ . '/lang/' . basename($lang) . '.php';
    if (!is_file($file)) return [];
    try {
      $arr = include $file;
      return is_array($arr) ? $arr : [];
    } catch (Throwable $e) { return []; }
  }
}

if (!function_exists('ua_i18n_dictionary')) {
  function ua_i18n_dictionary(?string $lang = null): array {
    static $cache = [];
    $lang = ua_i18n_sanitize_lang($lang ?? ua_i18n_current_lang());
    if (isset($cache[$lang])) return $cache[$lang];

    $exact = [];
    $phrases = [];
    $flat = ua_i18n_load_flat_file($lang);
    foreach ($flat as $k => $v) {
      if (is_string($k) && is_string($v) && $k !== '_lang') $exact[$k] = $v;
    }

    if ($lang === 'en') {
      $autoFile = __DIR__ . '/lang/en_auto.php';
      if (is_file($autoFile)) {
        try {
          $auto = include $autoFile;
          if (is_array($auto)) {
            if (isset($auto['exact']) && is_array($auto['exact'])) {
              foreach ($auto['exact'] as $k => $v) if (is_string($k) && is_string($v)) $exact[$k] = $v;
            }
            if (isset($auto['phrases']) && is_array($auto['phrases'])) {
              foreach ($auto['phrases'] as $k => $v) if (is_string($k) && is_string($v)) $phrases[$k] = $v;
            }
          }
        } catch (Throwable $e) {}
      }
      $patchFile = __DIR__ . '/lang/en_patch.php';
      if (is_file($patchFile)) {
        try {
          $patch = include $patchFile;
          if (is_array($patch)) {
            if (isset($patch['exact']) && is_array($patch['exact'])) {
              foreach ($patch['exact'] as $k => $v) if (is_string($k) && is_string($v)) $exact[$k] = $v;
            }
            if (isset($patch['phrases']) && is_array($patch['phrases'])) {
              foreach ($patch['phrases'] as $k => $v) if (is_string($k) && is_string($v)) $phrases[$k] = $v;
            }
          }
        } catch (Throwable $e) {}
      }

      // Longest Arabic phrases first to prevent partial replacement conflicts.
      uksort($phrases, function($a, $b){ return strlen($b) <=> strlen($a); });
    }

    $cache[$lang] = ['exact' => $exact, 'phrases' => $phrases];
    return $cache[$lang];
  }
}

if (!function_exists('ua_i18n_normalize_text')) {
  function ua_i18n_normalize_text(string $s): string {
    $s = str_replace(["\xE2\x80\x8E", "\xE2\x80\x8F", "\xEF\xBB\xBF"], '', $s);
    $s = preg_replace('/\s+/u', ' ', $s);
    return trim((string)$s);
  }
}

if (!function_exists('ua_i18n_translate_text')) {
  function ua_i18n_translate_text(string $text, ?string $fallback = null): string {
    $lang = ua_i18n_current_lang();
    if ($lang !== 'en') return (string)($fallback ?? $text);

    $source = (string)($fallback ?? $text);
    if ($source === '') return '';
    if (!preg_match('/[\x{0600}-\x{06FF}]/u', $source)) return $source;

    $dict = ua_i18n_dictionary($lang);
    $exact = $dict['exact'];
    $phrases = $dict['phrases'];

    if (isset($exact[$source])) return $exact[$source];
    $norm = ua_i18n_normalize_text($source);
    if (isset($exact[$norm])) return $exact[$norm];

    $out = $source;
    foreach ($phrases as $ar => $en) {
      if ($ar === '') continue;
      // Single Arabic words must be replaced as tokens only, so customer names/words are not corrupted.
      if (preg_match('/^[\x{0600}-\x{06FF}]+$/u', $ar)) {
        $rx = '/(^|[^\x{0600}-\x{06FF}])' . preg_quote($ar, '/') . '(?=$|[^\x{0600}-\x{06FF}])/u';
        $out = preg_replace($rx, '$1' . str_replace('$', '\\$', $en), $out);
      } else {
        $out = str_replace($ar, $en, $out);
      }
    }
    $out = preg_replace('/\s+/u', ' ', $out);
    $out = trim((string)$out);

    // Safety rule: never show broken hybrid labels like "Subscribers قائمة".
    // Exact entries provide full translations; phrase fallback is accepted only
    // when it fully removes Arabic UI words. Unknown strings remain Arabic.
    if (preg_match('/[\x{0600}-\x{06FF}]/u', $out)) {
      return $source;
    }
    return $out;
  }
}

if (!function_exists('ua_i18n_translate_array')) {
  function ua_i18n_translate_array(array $arr): array {
    foreach ($arr as $k => $v) {
      if (is_string($v)) $arr[$k] = ua_i18n_translate_text($v);
      elseif (is_array($v)) $arr[$k] = ua_i18n_translate_array($v);
    }
    return $arr;
  }
}

if (!function_exists('ua_i18n_json_payload')) {
  function ua_i18n_json_payload(): string {
    $lang = ua_i18n_current_lang();
    $dict = ua_i18n_dictionary($lang);
    $payload = [
      'lang' => $lang,
      'dir' => 'rtl',
      'exact' => ($lang === 'en' ? $dict['exact'] : []),
      'phrases' => ($lang === 'en' ? $dict['phrases'] : []),
    ];
    return json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT);
  }
}
