<?php
// SHARK CRM fixed bilingual system (English / Arabic only)
// All translations are loaded from DB. No auto-capture, no duplicated output.

if (!function_exists('crmLangNormalize')) {
    function crmLangNormalize($code) {
        $code = strtolower(trim((string)$code));
        return in_array($code, ['en','ar'], true) ? $code : 'en';
    }

    function crmCurrentLang($conn = null) {
        static $cached = null;
        if ($cached !== null) return $cached;

        if (session_status() !== PHP_SESSION_ACTIVE) { @session_start(); }
        $lang = $_SESSION['crm_language'] ?? '';

        if (!$lang && $conn instanceof mysqli) {
            $account_id = (int)($_SESSION['account_id'] ?? 0);
            $user_id = (int)($_SESSION['user_id'] ?? 0);

            if ($user_id && function_exists('columnExists') && columnExists($conn, 'users', 'language_code')) {
                $q = @$conn->query("SELECT language_code FROM users WHERE id=$user_id LIMIT 1");
                if ($q && $q->num_rows) $lang = (string)($q->fetch_assoc()['language_code'] ?? '');
            }
            if (!$lang && $account_id && function_exists('columnExists')) {
                if (columnExists($conn, 'accounts', 'language_code')) {
                    $q = @$conn->query("SELECT language_code FROM accounts WHERE id=$account_id LIMIT 1");
                    if ($q && $q->num_rows) $lang = (string)($q->fetch_assoc()['language_code'] ?? '');
                } elseif (columnExists($conn, 'accounts', 'default_language_code')) {
                    $q = @$conn->query("SELECT default_language_code FROM accounts WHERE id=$account_id LIMIT 1");
                    if ($q && $q->num_rows) $lang = (string)($q->fetch_assoc()['default_language_code'] ?? '');
                }
            }
        }

        $cached = crmLangNormalize($lang ?: 'en');
        $_SESSION['crm_language'] = $cached;
        return $cached;
    }

    function crmLangDir($conn = null) {
        return crmCurrentLang($conn) === 'ar' ? 'rtl' : 'ltr';
    }

    function crmI18nNormalizeText($text) {
        $text = html_entity_decode((string)$text, ENT_QUOTES | ENT_HTML5, 'UTF-8');
        $text = preg_replace('/\s+/u', ' ', trim($text));
        return $text;
    }

    function crmTranslationLookup($conn, $key, $fallback = '') {
        static $cache = [];
        if (!($conn instanceof mysqli)) return $fallback !== '' ? $fallback : $key;
        $lang = crmCurrentLang($conn);
        $ck = $lang . '|' . $key;
        if (array_key_exists($ck, $cache)) return $cache[$ck];

        $keyEsc = $conn->real_escape_string($key);
        $langEsc = $conn->real_escape_string($lang);
        $sql = "SELECT tr.value
                FROM translation_keys tk
                JOIN translations tr ON tr.key_id=tk.id
                JOIN languages l ON l.id=tr.language_id
                WHERE tk.`key`='$keyEsc' AND l.code='$langEsc'
                LIMIT 1";
        $q = @$conn->query($sql);
        if ($q && $q->num_rows) {
            $v = (string)$q->fetch_assoc()['value'];
            return $cache[$ck] = ($v !== '' ? $v : ($fallback !== '' ? $fallback : $key));
        }

        // English fallback from DB
        if ($lang !== 'en') {
            $sql = "SELECT tr.value
                    FROM translation_keys tk
                    JOIN translations tr ON tr.key_id=tk.id
                    JOIN languages l ON l.id=tr.language_id
                    WHERE tk.`key`='$keyEsc' AND l.code='en'
                    LIMIT 1";
            $q = @$conn->query($sql);
            if ($q && $q->num_rows) {
                $v = (string)$q->fetch_assoc()['value'];
                return $cache[$ck] = ($v !== '' ? $v : ($fallback !== '' ? $fallback : $key));
            }
        }

        return $cache[$ck] = ($fallback !== '' ? $fallback : $key);
    }

    function __($key, $fallback = '') {
        global $conn;
        return crmTranslationLookup($conn ?? null, (string)$key, (string)$fallback);
    }

    function _e($key, $fallback = '') {
        echo htmlspecialchars(__($key, $fallback), ENT_QUOTES, 'UTF-8');
    }

    function crmTextKey($text) {
        $clean = crmI18nNormalizeText($text);
        return 'text.' . sha1($clean);
    }

    function crmTText($text) {
        global $conn;
        $original = (string)$text;
        $clean = crmI18nNormalizeText($original);
        if ($clean === '') return $original;
        if (!preg_match('/[A-Za-z\x{0600}-\x{06FF}]/u', $clean)) return $original;
        $translated = crmTranslationLookup($conn ?? null, crmTextKey($clean), $clean);
        return $translated;
    }

    function crmTranslateHtmlChunk($html) {
        global $conn;
        if (!($conn instanceof mysqli)) return $html;
        if (crmCurrentLang($conn) === 'en') return $html;

        // translate safe attributes
        $html = preg_replace_callback('/\s(title|placeholder|aria-label|data-confirm)=("|\')([^"\']+)(\2)/iu', function($m) {
            $translated = crmTText($m[3]);
            return ' ' . $m[1] . '=' . $m[2] . htmlspecialchars($translated, ENT_QUOTES, 'UTF-8') . $m[4];
        }, $html);

        // Keep script/style/textarea/pre untouched
        $protected = [];
        $html = preg_replace_callback('/<(script|style|textarea|pre)\b[^>]*>.*?<\/\1>/isu', function($m) use (&$protected) {
            $token = '%%CRM_I18N_BLOCK_' . count($protected) . '%%';
            $protected[$token] = $m[0];
            return $token;
        }, $html);

        $html = preg_replace_callback('/>([^<>]+)</u', function($m) {
            $text = $m[1];
            $clean = crmI18nNormalizeText($text);
            if ($clean === '' || !preg_match('/[A-Za-z\x{0600}-\x{06FF}]/u', $clean)) return $m[0];
            $leading = preg_match('/^\s+/u', $text, $lm) ? $lm[0] : '';
            $trailing = preg_match('/\s+$/u', $text, $rm) ? $rm[0] : '';
            $translated = crmTText($clean);
            return '>' . $leading . htmlspecialchars($translated, ENT_QUOTES, 'UTF-8') . $trailing . '<';
        }, $html);

        if ($protected) $html = strtr($html, $protected);
        return $html;
    }

    function crmStartI18nBuffer($conn = null) {
        static $started = false;
        if ($started) return;
        $started = true;
        ob_start(function($html) {
            return crmTranslateHtmlChunk($html);
        });
    }

    function crmJson($data) {
        if (is_array($data)) {
            foreach ($data as $k => $v) {
                if ($k === 'message' && is_string($v) && $v !== '') $data[$k] = crmTText($v);
                elseif (is_array($v)) $data[$k] = crmJson($v);
            }
        }
        return $data;
    }
}
