<?php
// Professional "My Account" panel text builder for users.
// Safe JSON/SQL compatible helpers. No direct output happens here.

if(!function_exists('bot_account_h')){
    function bot_account_h($v){ return htmlspecialchars((string)$v, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }
}
if(!function_exists('bot_account_int')){
    function bot_account_int($v){ return (int)preg_replace('/[^0-9\-]/', '', (string)$v); }
}
if(!function_exists('bot_account_fmt')){
    function bot_account_fmt($v){ return number_format((int)$v); }
}
if(!function_exists('bot_account_panel_rank')){
    function bot_account_panel_rank($panel){
        $p = trim((string)$panel);
        if($p === 'ویژه' || stripos($p, 'vip') !== false || stripos($p, 'pro') !== false || mb_strpos($p, 'پرو') !== false) return 3;
        if($p === 'حرفه ای' || $p === 'حرفه‌ای' || mb_strpos($p, 'حرفه') !== false) return 2;
        return 1;
    }
}
if(!function_exists('bot_account_user_orders_stats')){
    function bot_account_user_orders_stats($userId){
        $out = ['total'=>0,'active'=>0,'done'=>0,'left'=>0,'received'=>0];
        $uid = preg_replace('/\D+/', '', (string)$userId);
        if($uid === '') return $out;
        $pdo = function_exists('bot_sql_pdo') ? bot_sql_pdo() : null;
        if($pdo instanceof PDO){
            try{
                $st=$pdo->prepare("SELECT COUNT(*) total, COALESCE(SUM(received_count),0) received, COALESCE(SUM(left_count),0) lefts FROM bot_orders WHERE owner_id=?");
                $st->execute([$uid]); $r=$st->fetch(PDO::FETCH_ASSOC) ?: [];
                $out['total']=(int)($r['total']??0); $out['received']=(int)($r['received']??0); $out['left']=(int)($r['lefts']??0);
            }catch(Throwable $e){}
            try{
                $st=$pdo->prepare("SELECT COUNT(*) FROM bot_orders WHERE owner_id=? AND LOWER(COALESCE(status,'')) NOT IN ('done','completed','complete','cancelled','canceled','closed','deleted') AND COALESCE(status,'') NOT LIKE '%تکمیل%' AND COALESCE(status,'') NOT LIKE '%لغو%'");
                $st->execute([$uid]); $out['active']=(int)$st->fetchColumn();
            }catch(Throwable $e){}
            $out['done'] = max(0, $out['total'] - $out['active']);
            return $out;
        }
        foreach(glob('ads/*.json') ?: [] as $file){
            $j=json_decode((string)@file_get_contents($file), true); if(!is_array($j)) continue;
            $owner = preg_replace('/\D+/', '', (string)($j['user_id'] ?? $j['owner_id'] ?? $j['from_id'] ?? $j['admin'] ?? ''));
            if($owner !== $uid) continue;
            $out['total']++;
            $status = (string)($j['status'] ?? $j['vaziyat'] ?? '');
            if($status === '' || (mb_strpos($status,'تکمیل') === false && mb_strpos($status,'لغو') === false && stripos($status,'done') === false && stripos($status,'cancel') === false)) $out['active']++;
            $out['received'] += bot_account_int($j['received_count'] ?? $j['done'] ?? $j['ok'] ?? 0);
            $left = $j['left'] ?? $j['lefts'] ?? [];
            $out['left'] += is_array($left) ? count($left) : bot_account_int($left);
        }
        $out['done'] = max(0, $out['total'] - $out['active']);
        return $out;
    }
}
if(!function_exists('bot_account_ref_stats')){
    function bot_account_ref_stats($userId, array $user=[]){
        $uid = preg_replace('/\D+/', '', (string)$userId);
        $out = [
            'total'=>bot_account_int($user['zirmjmae'] ?? 0),
            'verified'=>0,
            'commission'=>bot_account_int($user['zirmjmae-porsant'] ?? 0),
            'join_count'=>bot_account_int($user['zirmjmae-join'] ?? 0),
        ];
        if($uid === '') return $out;
        if(function_exists('bot_referral_verified_count_for_referrer')) $out['verified'] = (int)bot_referral_verified_count_for_referrer($uid);
        $pdo = function_exists('bot_sql_pdo') ? bot_sql_pdo() : null;
        if($pdo instanceof PDO){
            try{ $st=$pdo->prepare('SELECT COUNT(*) FROM bot_referrals WHERE referrer_id=?'); $st->execute([$uid]); $out['total'] = max($out['total'], (int)$st->fetchColumn()); }catch(Throwable $e){}
            try{ $st=$pdo->prepare("SELECT COALESCE(SUM(amount),0) FROM bot_referral_events WHERE referrer_id=? AND amount>0"); $st->execute([$uid]); $out['commission'] = max($out['commission'], (int)$st->fetchColumn()); }catch(Throwable $e){}
        }else{
            $total=0; $verified=0;
            foreach(glob('melat/*.json') ?: [] as $file){
                $j=json_decode((string)@file_get_contents($file), true); if(!is_array($j)) continue;
                $ref=preg_replace('/\D+/', '', (string)($j['sub'] ?? $j['referrer_id'] ?? ''));
                if($ref !== $uid) continue;
                $total++;
                if(!empty($j['ref_verified_counted']) || !empty($j['ref_forced_join_rewarded']) || !empty($j['ref_signup_rewarded'])) $verified++;
            }
            $out['total'] = max($out['total'], $total);
            $out['verified'] = max($out['verified'], $verified);
        }
        return $out;
    }
}
if(!function_exists('bot_account_next_level_info')){
    function bot_account_next_level_info($panel, $verifiedRefs){
        $settings = function_exists('bot_referral_settings') ? bot_referral_settings() : (function_exists('bot_data_get_json') ? bot_data_get_json('lib/kodam/data-zirmjmae.json', []) : []);
        $proReq = max(0, bot_account_int($settings['upgrade_professional_refs'] ?? 10));
        $vipReq = max(0, bot_account_int($settings['upgrade_vip_refs'] ?? 20));
        $rank = bot_account_panel_rank($panel);
        if($rank >= 3) return ['label'=>'بالاترین سطح فعال است','required'=>0,'remaining'=>0,'percent'=>100,'target'=>'پرو/ویژه'];
        if($rank === 2){ $req=$vipReq; $target='پرو/ویژه'; }
        else{ $req=$proReq; $target='حرفه‌ای'; }
        if($req <= 0) return ['label'=>'ارتقای بعدی غیرفعال است','required'=>0,'remaining'=>0,'percent'=>0,'target'=>$target];
        $remaining = max(0, $req - (int)$verifiedRefs);
        $percent = min(100, (int)floor(((int)$verifiedRefs / max(1,$req))*100));
        return ['label'=>($remaining>0 ? $remaining.' زیرمجموعه تا '.$target : 'آماده ارتقا به '.$target), 'required'=>$req, 'remaining'=>$remaining, 'percent'=>$percent, 'target'=>$target];
    }
}
if(!function_exists('bot_account_daily_status_text')){
    function bot_account_daily_status_text(array $user){
        $next = bot_account_int($user['time-day'] ?? 0);
        if($next <= time()) return '🎁 هدیه روزانه آماده دریافت است';
        $remain = max(0, $next - time());
        $h = intdiv($remain, 3600); $m = intdiv($remain % 3600, 60);
        return '⏳ هدیه روزانه بعدی: '.$h.' ساعت و '.$m.' دقیقه دیگر';
    }
}
if(!function_exists('bot_user_account_pro_text')){
    function bot_user_account_pro_text($userId, array $user, array $context=[]){
        $money = (string)($context['money'] ?? ($GLOBALS['money'] ?? 'الماس'));
        $uid = preg_replace('/\D+/', '', (string)$userId);
        $panel = (string)($user['type-panel'] ?? 'عادی');
        $balance = bot_account_int($user['Points'] ?? 0);
        $warn = bot_account_int($user['warn'] ?? 0);
        $date = trim((string)($user['date-start'] ?? 'ثبت نشده'));
        $validity = bot_account_panel_rank($panel) <= 1 ? 'نامحدود' : ((string)($user['time-panel'] ?? 'نامشخص').' روز');
        $orders = bot_account_user_orders_stats($uid);
        $refs = bot_account_ref_stats($uid, $user);
        $level = bot_account_next_level_info($panel, $refs['verified']);
        $refLink = '';
        $botUsername = trim((string)($context['bot_username'] ?? ($GLOBALS['boter_id'] ?? '')));
        if($botUsername !== '') $refLink = 'https://t.me/'.$botUsername.'?start='.$uid;
        $lines = [];
        $lines[] = '👤 <b>پنل حساب من</b>';
        $lines[] = '';
        $lines[] = '🆔 شماره کاربری: <code>'.bot_account_h($uid).'</code>';
        $lines[] = '📆 تاریخ عضویت: <b>'.bot_account_h($date ?: 'ثبت نشده').'</b>';
        $lines[] = '🎫 سطح حساب: <b>'.bot_account_h($panel).'</b>';
        $lines[] = '⌛️ اعتبار پنل: <b>'.bot_account_h($validity).'</b>';
        $lines[] = '💎 موجودی فعلی: <b>'.bot_account_fmt($balance).'</b> '.bot_account_h($money);
        $lines[] = '⚠️ اخطارها: <b>'.$warn.'</b> از 3';
        $lines[] = '';
        $lines[] = '📦 <b>وضعیت سفارش‌ها</b>';
        $lines[] = '• کل سفارش‌ها: <b>'.bot_account_fmt($orders['total']).'</b>';
        $lines[] = '• سفارش‌های فعال: <b>'.bot_account_fmt($orders['active']).'</b>';
        $lines[] = '• عضویت‌های دریافت‌شده: <b>'.bot_account_fmt(max($orders['received'], bot_account_int($user['ads'] ?? 0))).'</b>';
        $lines[] = '• لفتی‌های ثبت‌شده: <b>'.bot_account_fmt($orders['left']).'</b>';
        $lines[] = '';
        $lines[] = '👥 <b>زیرمجموعه‌گیری</b>';
        $lines[] = '• کل زیرمجموعه‌ها: <b>'.bot_account_fmt($refs['total']).'</b>';
        $lines[] = '• زیرمجموعه‌های تأییدشده: <b>'.bot_account_fmt($refs['verified']).'</b>';
        $lines[] = '• پورسانت دریافتی: <b>'.bot_account_fmt($refs['commission']).'</b> '.bot_account_h($money);
        $lines[] = '• پیشرفت ارتقا: <b>'.$level['percent'].'%</b> — '.bot_account_h($level['label']);
        $lines[] = '';
        $lines[] = '💳 <b>انتقالات و هدایا</b>';
        $lines[] = '• دریافتی انتقال: <b>'.bot_account_fmt($user['enteghal_as'] ?? 0).'</b>';
        $lines[] = '• واریزی انتقال: <b>'.bot_account_fmt($user['enteghal_to'] ?? 0).'</b>';
        $lines[] = '• هدیه مدیریت: <b>'.bot_account_fmt($user['send-coin-admin'] ?? 0).'</b>';
        $lines[] = '';
        $lines[] = bot_account_daily_status_text($user);
        if($refLink !== ''){
            $lines[] = '';
            $lines[] = '🔗 لینک دعوت اختصاصی شما آماده کپی است.';
        }
        return implode("\n", $lines);
    }
}
?>
