<?php
// admin/lang.php
// Compatibility entry point for language + legacy app_settings helpers.
// The real language engine is centralized in i18n_lib.php.

if (session_status() === PHP_SESSION_NONE) { @session_start(); }
require_once __DIR__ . '/i18n_lib.php';

if (!function_exists('current_lang')) {
  function current_lang(): string { return ua_i18n_current_lang(); }
}

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

if (!function_exists('app_settings_schema')) {
  function app_settings_schema(mysqli $conn): array {
    static $cache = [];
    $dbKey = spl_object_hash($conn);
    if (isset($cache[$dbKey])) return $cache[$dbKey];

    $schema = [
      'has_key' => false,
      'has_setting_key' => false,
      'has_value' => false,
      'has_setting_value' => false,
      'key_col' => 'setting_key',
      'val_col' => 'setting_value',
    ];

    $rs = @$conn->query("SHOW COLUMNS FROM `app_settings`");
    if ($rs) {
      while ($r = $rs->fetch_assoc()) {
        $f = (string)($r['Field'] ?? '');
        if ($f === 'key') $schema['has_key'] = true;
        if ($f === 'setting_key') $schema['has_setting_key'] = true;
        if ($f === 'value') $schema['has_value'] = true;
        if ($f === 'setting_value') $schema['has_setting_value'] = true;
      }
    }

    // الأفضلية للأسماء الصريحة setting_* لأنها الظاهر أنها المعتمدة في هذه النسخة.
    if ($schema['has_setting_key']) $schema['key_col'] = 'setting_key';
    elseif ($schema['has_key']) $schema['key_col'] = 'key';

    if ($schema['has_setting_value']) $schema['val_col'] = 'setting_value';
    elseif ($schema['has_value']) $schema['val_col'] = 'value';

    $cache[$dbKey] = $schema;
    return $schema;
  }
}

if (!function_exists('app_settings_cols')) {
  function app_settings_cols(mysqli $conn): array {
    $s = app_settings_schema($conn);
    return [$s['key_col'], $s['val_col']];
  }
}

if (!function_exists('get_app_setting')) {
  function get_app_setting(mysqli $conn, string $k, string $default=''): string {
    $s = app_settings_schema($conn);
    $k2 = $conn->real_escape_string($k);

    $where = [];
    if ($s['has_setting_key']) $where[] = "`setting_key`='{$k2}'";
    if ($s['has_key']) $where[] = "`key`='{$k2}'";
    if (!$where) return $default;

    $selectParts = [];
    if ($s['has_setting_value']) $selectParts[] = '`setting_value`';
    if ($s['has_value']) $selectParts[] = '`value`';
    if (!$selectParts) return $default;

    $sql = "SELECT COALESCE(" . implode(',', $selectParts) . ") AS v FROM `app_settings` WHERE (" . implode(' OR ', $where) . ") LIMIT 1";
    $q = @$conn->query($sql);
    if ($q && $q->num_rows) {
      $row = $q->fetch_assoc();
      return (string)($row['v'] ?? $default);
    }
    return $default;
  }
}

if (!function_exists('set_app_setting')) {
  function set_app_setting(mysqli $conn, string $k, string $v): void {
    $s = app_settings_schema($conn);
    $k2 = $conn->real_escape_string($k);
    $v2 = $conn->real_escape_string($v);

    $where = [];
    if ($s['has_setting_key']) $where[] = "`setting_key`='{$k2}'";
    if ($s['has_key']) $where[] = "`key`='{$k2}'";
    if (!$where) return;

    $set = [];
    if ($s['has_setting_key']) $set[] = "`setting_key`='{$k2}'";
    if ($s['has_key']) $set[] = "`key`='{$k2}'";
    if ($s['has_setting_value']) $set[] = "`setting_value`='{$v2}'";
    if ($s['has_value']) $set[] = "`value`='{$v2}'";

    // حاول تحديث السجل الموجود أولاً لتفادي مشاكل الأعمدة غير الافتراضية.
    $updated = false;
    if ($set) {
      $sqlUpdate = "UPDATE `app_settings` SET " . implode(', ', $set) . " WHERE (" . implode(' OR ', $where) . ") LIMIT 1";
      $ok = @$conn->query($sqlUpdate);
      if ($ok && $conn->affected_rows > 0) $updated = true;
      if ($ok && $conn->affected_rows === 0) {
        $chk = @$conn->query("SELECT 1 FROM `app_settings` WHERE (" . implode(' OR ', $where) . ") LIMIT 1");
        if ($chk && $chk->num_rows) $updated = true;
      }
    }

    if (!$updated) {
      $cols = [];
      $vals = [];
      if ($s['has_setting_key']) { $cols[] = '`setting_key`'; $vals[] = "'{$k2}'"; }
      if ($s['has_key']) { $cols[] = '`key`'; $vals[] = "'{$k2}'"; }
      if ($s['has_setting_value']) { $cols[] = '`setting_value`'; $vals[] = "'{$v2}'"; }
      if ($s['has_value']) { $cols[] = '`value`'; $vals[] = "'{$v2}'"; }
      if ($cols) {
        @$conn->query("INSERT INTO `app_settings` (" . implode(',', $cols) . ") VALUES (" . implode(',', $vals) . ")");
      }
    }

    if ($k === 'ui_lang') $_SESSION['ui_lang'] = $v;
  }
}
