<?php
/**
 * ReferralEngine v83 - clean rewrite
 *
 * هدف این فایل: تمام منطق رفرال در یک موتور مرکزی باشد و مسیرهای قدیمی فقط wrapper باشند.
 * پرداخت رفرال فقط بعد از تکمیل جوین اجباری و زدن دکمه «بررسی عضویت» انجام می‌شود.
 */

if(!function_exists('bot_referral_default_settings')){
    function bot_referral_default_settings(){
        return [
            'power' => '✅فعال',
            'Report' => '✅فعال',
            'banerzir' => '📝متنی',
            'zirjoinads' => '20',
            'coin-join' => '10',
            'signup_reward_mode' => 'diamond',
            'active_reward_mode' => 'diamond',
            'invitecoin1' => '10',
            'invitecoin2' => '15',
            'invitecoin3' => '20',
            // نام قدیمی حفظ شده؛ معنی جدید: پاداش یک‌باره بعد از بررسی عضویت جوین اجباری
            'ref_join_reward_power' => '✅فعال',
            'ref_join_reward_per_channel' => '10',
            'upgrade_professional_refs' => '10',
            'upgrade_vip_refs' => '20',
            'notify_referrer_on_pending' => '✅فعال',
            'notify_referrer_on_verified' => '✅فعال',
            'anti_fake_enabled' => '✅فعال',
            'require_forced_join_for_reward' => '✅فعال',
        ];
    }
}

if(!function_exists('bot_referral_setting_enabled')){
    function bot_referral_setting_enabled($value, $default=true){
        $v = trim((string)$value);
        if($v === '') return (bool)$default;
        $low = mb_strtolower($v, 'UTF-8');
        if(in_array($low, ['0','false','off','no','نه','خاموش','غیرفعال','غیر فعال','❌غیرفعال','❌غیر فعال'], true)) return false;
        return true;
    }
}

if(!function_exists('bot_referral_num')){
    function bot_referral_num($v, $min=0){
        if(function_exists('bot_normalize_number_digits')) $v = bot_normalize_number_digits($v);
        $v = preg_replace('/[^0-9]/', '', (string)$v);
        return max((int)$min, (int)($v === '' ? 0 : $v));
    }
}

if(!function_exists('bot_referral_settings')){
    function bot_referral_settings(){
        $s = function_exists('bot_data_get_json') ? bot_data_get_json('lib/kodam/data-zirmjmae.json', []) : [];
        if(!is_array($s)) $s = [];
        $s = array_merge(bot_referral_default_settings(), $s);

        // سازگاری با فایل‌های قدیمی پاداش
        foreach(['invitecoin1','invitecoin2','invitecoin3'] as $k){
            $file = 'lib/Button/'.$k.'.txt';
            $v = function_exists('bot_data_get_text') ? trim((string)bot_data_get_text($file, '')) : (is_file($file) ? trim((string)@file_get_contents($file)) : '');
            if($v !== '' && preg_match('/^[0-9۰-۹٠-٩]+$/u', $v)) $s[$k] = $v;
        }

        $s['power'] = bot_referral_setting_enabled($s['power'] ?? '✅فعال', true) ? '✅فعال' : '❌غیر فعال';
        $s['Report'] = bot_referral_setting_enabled($s['Report'] ?? '✅فعال', true) ? '✅فعال' : '❌غیر فعال';
        $s['ref_join_reward_power'] = bot_referral_setting_enabled($s['ref_join_reward_power'] ?? '✅فعال', true) ? '✅فعال' : '❌غیر فعال';
        $s['notify_referrer_on_pending'] = bot_referral_setting_enabled($s['notify_referrer_on_pending'] ?? '✅فعال', true) ? '✅فعال' : '❌غیر فعال';
        $s['notify_referrer_on_verified'] = bot_referral_setting_enabled($s['notify_referrer_on_verified'] ?? '✅فعال', true) ? '✅فعال' : '❌غیر فعال';
        $s['anti_fake_enabled'] = bot_referral_setting_enabled($s['anti_fake_enabled'] ?? '✅فعال', true) ? '✅فعال' : '❌غیر فعال';
        $s['require_forced_join_for_reward'] = bot_referral_setting_enabled($s['require_forced_join_for_reward'] ?? '✅فعال', true) ? '✅فعال' : '❌غیر فعال';

        $s['signup_reward_mode'] = 'diamond';
        $s['active_reward_mode'] = 'diamond';
        foreach(['invitecoin1','invitecoin2','invitecoin3','coin-join','ref_join_reward_per_channel','upgrade_professional_refs','upgrade_vip_refs'] as $k){
            $s[$k] = (string)bot_referral_num($s[$k] ?? 0, 0);
        }
        $s['zirjoinads'] = (string)bot_referral_num($s['zirjoinads'] ?? 1, 1);
        return $s;
    }
}

if(!function_exists('bot_referral_save_settings')){
    function bot_referral_save_settings(array $settings){
        $old = function_exists('bot_data_get_json') ? bot_data_get_json('lib/kodam/data-zirmjmae.json', []) : [];
        if(!is_array($old)) $old = [];
        $settings = array_merge($old, $settings);
        if(function_exists('saveJson')) saveJson('lib/kodam/data-zirmjmae.json', $settings);
        elseif(function_exists('bot_data_put_json')) bot_data_put_json('lib/kodam/data-zirmjmae.json', $settings);
        else @file_put_contents('lib/kodam/data-zirmjmae.json', json_encode($settings, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT), LOCK_EX);

        foreach(['invitecoin1','invitecoin2','invitecoin3'] as $k){
            if(array_key_exists($k, $settings)){
                $v = (string)bot_referral_num($settings[$k], 0);
                if(function_exists('save')) save('lib/Button/'.$k.'.txt', $v);
                elseif(function_exists('bot_data_put_text')) bot_data_put_text('lib/Button/'.$k.'.txt', $v);
                else @file_put_contents('lib/Button/'.$k.'.txt', $v, LOCK_EX);
            }
        }
        return true;
    }
}

if(!function_exists('bot_referral_json')){
    function bot_referral_json(array $data){
        return function_exists('bot_json_encode') ? bot_json_encode($data) : json_encode($data, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
    }
}

if(!function_exists('bot_referral_log')){
    function bot_referral_log($type, $referrerId='', $referredId='', array $data=[]){
        if(!is_dir('cache')) @mkdir('cache', 0755, true);
        $line = date('c').' | '.$type.' | ref='.(string)$referrerId.' | user='.(string)$referredId;
        if($data) $line .= ' | data='.bot_referral_json($data);
        @file_put_contents('cache/referral_engine.log', $line."\n", FILE_APPEND);
    }
}

if(!function_exists('bot_referral_notify_log')){
    function bot_referral_notify_log($kind, $referrerId, $referredId, $ok, $description='', array $extra=[]){
        bot_referral_log('notify_'.$kind, $referrerId, $referredId, ['ok'=>$ok?1:0, 'description'=>(string)$description, 'extra'=>$extra]);
        if(!is_dir('cache')) @mkdir('cache',0755,true);
        @file_put_contents('cache/referral_notify.log', date('c').' | notify_'.$kind.' | ref='.$referrerId.' | user='.$referredId.' | ok='.($ok?'1':'0').' | '.(string)$description.($extra?' | data='.bot_referral_json($extra):'')."\n", FILE_APPEND);
    }
}

if(!function_exists('bot_referral_verify_log')){
    function bot_referral_verify_log($referredId, $referrerId, $result, array $extra=[]){
        if(!is_dir('cache')) @mkdir('cache',0755,true);
        $line = date('c').' | verify_forced_join | user='.(string)$referredId.' | ref='.(string)$referrerId;
        $line .= ' | result='.(is_array($result) ? bot_referral_json($result) : (string)$result);
        if($extra) $line .= ' | extra='.bot_referral_json($extra);
        @file_put_contents('cache/referral_verify.log', $line."\n", FILE_APPEND);
    }
}

if(!function_exists('bot_referral_pdo')){
    function bot_referral_pdo(){ return function_exists('bot_sql_pdo') ? bot_sql_pdo() : null; }
}

if(!function_exists('bot_referral_install_schema')){
    function bot_referral_install_schema(){
        $pdo = bot_referral_pdo();
        if(!$pdo) return false;
        try{
            $pdo->exec("CREATE TABLE IF NOT EXISTS bot_referrals (
                id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
                referrer_id VARCHAR(32) NOT NULL,
                referred_id VARCHAR(32) NOT NULL,
                status VARCHAR(32) NOT NULL DEFAULT 'pending_start',
                signup_reward_mode VARCHAR(20) NOT NULL DEFAULT 'diamond',
                signup_reward_amount INT NOT NULL DEFAULT 0,
                signup_reward_applied TINYINT(1) NOT NULL DEFAULT 0,
                active_required_count INT NOT NULL DEFAULT 0,
                active_reward_mode VARCHAR(20) NOT NULL DEFAULT 'diamond',
                active_reward_amount INT NOT NULL DEFAULT 0,
                active_reward_applied TINYINT(1) NOT NULL DEFAULT 0,
                referred_join_count INT NOT NULL DEFAULT 0,
                data_json LONGTEXT NULL,
                created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                UNIQUE KEY uniq_referred (referred_id),
                KEY idx_referrer (referrer_id),
                KEY idx_status (status),
                KEY idx_referrer_created (referrer_id, created_at)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
            $pdo->exec("CREATE TABLE IF NOT EXISTS bot_referral_events (
                id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
                referrer_id VARCHAR(32) NOT NULL,
                referred_id VARCHAR(32) NOT NULL,
                event_type VARCHAR(40) NOT NULL,
                reward_mode VARCHAR(20) NULL,
                amount INT NOT NULL DEFAULT 0,
                before_balance INT NULL,
                after_balance INT NULL,
                data_json LONGTEXT NULL,
                created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
                KEY idx_referrer (referrer_id),
                KEY idx_referred (referred_id),
                KEY idx_event_type (event_type),
                KEY idx_created (created_at)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
            return true;
        }catch(Throwable $e){
            error_log('BOT referral schema failed: '.$e->getMessage());
            return false;
        }
    }
}

if(!function_exists('bot_referral_event')){
    function bot_referral_event($referrerId, $referredId, $type, $mode=null, $amount=0, $before=null, $after=null, array $data=[]){
        $pdo = bot_referral_pdo();
        if($pdo && bot_referral_install_schema()){
            try{
                $st=$pdo->prepare('INSERT INTO bot_referral_events (referrer_id,referred_id,event_type,reward_mode,amount,before_balance,after_balance,data_json) VALUES (?,?,?,?,?,?,?,?)');
                $st->execute([(string)$referrerId,(string)$referredId,(string)$type,$mode===null?null:(string)$mode,(int)$amount,$before===null?null:(int)$before,$after===null?null:(int)$after,bot_referral_json($data)]);
            }catch(Throwable $e){ error_log('BOT referral event failed: '.$e->getMessage()); }
        }
        bot_referral_log('event_'.$type, $referrerId, $referredId, ['mode'=>$mode, 'amount'=>(int)$amount, 'before'=>$before, 'after'=>$after, 'data'=>$data]);
    }
}

if(!function_exists('bot_referral_clean_id')){
    function bot_referral_clean_id($id){ return preg_replace('/\D+/', '', (string)$id); }
}

if(!function_exists('bot_referral_user_path')){
    function bot_referral_user_path($userId){ return 'melat/'.bot_referral_clean_id($userId).'.json'; }
}

if(!function_exists('bot_referral_read_user')){
    function bot_referral_read_user($userId){
        $uid = bot_referral_clean_id($userId);
        if($uid === '') return [];
        $u = function_exists('bot_data_get_json') ? bot_data_get_json("melat/$uid.json", []) : [];
        return is_array($u) ? $u : [];
    }
}

if(!function_exists('bot_referral_write_user')){
    function bot_referral_write_user($userId, array $data){
        $uid = bot_referral_clean_id($userId);
        if($uid === '') return false;
        if(function_exists('saveJson')) saveJson("melat/$uid.json", $data);
        elseif(function_exists('bot_data_put_json')) bot_data_put_json("melat/$uid.json", $data);
        else{
            if(!is_dir('melat')) @mkdir('melat',0755,true);
            @file_put_contents("melat/$uid.json", json_encode($data, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT), LOCK_EX);
        }
        return true;
    }
}

if(!function_exists('bot_referral_user_exists')){
    function bot_referral_user_exists($userId){
        $uid = bot_referral_clean_id($userId);
        if($uid === '') return false;
        if(function_exists('bot_data_file_exists')) return bot_data_file_exists("melat/$uid.json");
        return is_file("melat/$uid.json");
    }
}

if(!function_exists('bot_referral_create_default_user')){
    function bot_referral_create_default_user($userId, $referrerId=null){
        global $date;
        $uid = bot_referral_clean_id($userId);
        $ref = bot_referral_clean_id($referrerId);
        $u = [
            'step'=>'none','zirmjmae'=>'0','Points'=>(string)(function_exists('bot_join_gift_amount') ? bot_join_gift_amount() : 10),'time-day'=>'0','days'=>'0','ads'=>'0',
            'enteghal_as'=>0,'enteghal_to'=>0,'type-panel'=>'عادی','date-start'=>isset($date)?$date:date('Y/m/d'),'sefaresh'=>'0','warn'=>'0','send-coin-admin'=>'0','zirmjmae-porsant'=>'0','zirmjmae-join'=>'0',
            'sub'=>$ref !== '' ? $ref : null,
            'referrer_id'=>$ref !== '' ? $ref : null,
            'referral_status'=>$ref !== '' ? 'pending_start' : 'none',
            'referral_registered_at'=>time(),
        ];
        if(function_exists('bot_fraud_prepare_new_user_for_start_gift')) $u = bot_fraud_prepare_new_user_for_start_gift($u, $uid);
        return $u;
    }
}

if(!function_exists('bot_referral_extract_referrer_id')){
    function bot_referral_extract_referrer_id($payload){
        $payload = trim((string)$payload);
        if($payload === '') return '';
        if(stripos($payload, 'ref_') === 0) $payload = substr($payload, 4);
        if(preg_match('/^(?:ref|start|user)[_\-]?([0-9]{4,32})$/i', $payload, $m)) return $m[1];
        if(preg_match('/^([0-9]{4,32})$/', $payload, $m)) return $m[1];
        return '';
    }
}

if(!function_exists('bot_referral_user_can_accept_referrer')){
    function bot_referral_user_can_accept_referrer(array $user){
        if(empty($user)) return true;
        if(!empty($user['sub']) || !empty($user['referrer_id'])) return false;
        // ترمیم نسخه‌های خراب: اگر کاربر فقط ساخته شده و هنوز فعالیت جدی ندارد، می‌تواند ref بگیرد.
        $points = (int)($user['Points'] ?? 0);
        $ads = (int)($user['ads'] ?? 0);
        $refs = (int)($user['zirmjmae'] ?? 0);
        $orders = (int)($user['sefaresh'] ?? 0);
        $status = (string)($user['referral_status'] ?? '');
        return ($ads <= 0 && $refs <= 0 && $orders <= 0 && in_array($status, ['', 'none', 'pending_start'], true));
    }
}

if(!function_exists('bot_referral_panel_rank')){
    function bot_referral_panel_rank($panel){
        $p = trim((string)$panel);
        if($p === 'ویژه' || $p === 'پرو' || stripos($p,'vip') !== false || stripos($p,'pro') !== false) return 3;
        if($p === 'حرفه‌ای' || $p === 'حرفه ای' || stripos($p,'professional') !== false) return 2;
        return 1;
    }
}

if(!function_exists('bot_referral_amount_for_referrer')){
    function bot_referral_amount_for_referrer(array $referrer, array $settings){
        $rank = bot_referral_panel_rank($referrer['type-panel'] ?? 'عادی');
        if($rank >= 3) return (int)($settings['invitecoin3'] ?? 0);
        if($rank >= 2) return (int)($settings['invitecoin2'] ?? 0);
        return (int)($settings['invitecoin1'] ?? 0);
    }
}

if(!function_exists('bot_referral_sql_find')){
    function bot_referral_sql_find($referredId){
        $pdo = bot_referral_pdo();
        if(!$pdo || !bot_referral_install_schema()) return null;
        try{ $st=$pdo->prepare('SELECT * FROM bot_referrals WHERE referred_id=? LIMIT 1'); $st->execute([(string)$referredId]); $r=$st->fetch(PDO::FETCH_ASSOC); return $r ?: null; }catch(Throwable $e){ return null; }
    }
}

if(!function_exists('bot_referral_sql_upsert')){
    function bot_referral_sql_upsert($referrerId, $referredId, $status='pending_start', array $data=[]){
        $pdo = bot_referral_pdo();
        if(!$pdo || !bot_referral_install_schema()) return false;
        try{
            $existing = bot_referral_sql_find($referredId);
            if($existing){
                if((string)$existing['referrer_id'] !== (string)$referrerId) return false;
                $st=$pdo->prepare('UPDATE bot_referrals SET status=?, data_json=?, updated_at=CURRENT_TIMESTAMP WHERE referred_id=?');
                $st->execute([(string)$status, bot_referral_json($data), (string)$referredId]);
                return true;
            }
            $st=$pdo->prepare('INSERT INTO bot_referrals (referrer_id,referred_id,status,data_json) VALUES (?,?,?,?)');
            $st->execute([(string)$referrerId,(string)$referredId,(string)$status,bot_referral_json($data)]);
            return true;
        }catch(Throwable $e){ error_log('BOT referral upsert failed: '.$e->getMessage()); return false; }
    }
}

if(!function_exists('bot_referral_sql_mark_verified')){
    function bot_referral_sql_mark_verified($referrerId, $referredId, $signupAmount, $forcedAmount, array $data=[]){
        $pdo = bot_referral_pdo();
        if(!$pdo || !bot_referral_install_schema()) return false;
        try{
            $st=$pdo->prepare('UPDATE bot_referrals SET status=?, signup_reward_amount=?, signup_reward_applied=1, active_reward_amount=GREATEST(active_reward_amount, ?), data_json=?, updated_at=CURRENT_TIMESTAMP WHERE referred_id=? AND referrer_id=?');
            $st->execute(['forced_join_verified', (int)$signupAmount, (int)$forcedAmount, bot_referral_json($data), (string)$referredId, (string)$referrerId]);
            return true;
        }catch(Throwable $e){ return false; }
    }
}

if(!function_exists('bot_referral_find_referrer_for_referred')){
    function bot_referral_find_referrer_for_referred($referredId, array $user=null){
        $uid = bot_referral_clean_id($referredId);
        if($uid === '') return '';
        if($user === null) $user = bot_referral_read_user($uid);
        $ref = bot_referral_clean_id($user['sub'] ?? ($user['referrer_id'] ?? ''));
        if($ref !== '') return $ref;
        $row = bot_referral_sql_find($uid);
        if($row && !empty($row['referrer_id'])) return bot_referral_clean_id($row['referrer_id']);
        return '';
    }
}

if(!function_exists('bot_referral_register_start_payload')){
    function bot_referral_register_start_payload($referredId, $payload, array $currentUser=[], $allowFreshExisting=true){
        $settings = bot_referral_settings();
        if((string)($settings['power'] ?? '✅فعال') !== '✅فعال') return ['ok'=>false,'reason'=>'disabled'];
        $referredId = bot_referral_clean_id($referredId);
        $referrerId = bot_referral_extract_referrer_id($payload);
        if($referredId === '' || $referrerId === '') return ['ok'=>false,'reason'=>'bad_payload'];
        if($referredId === $referrerId) return ['ok'=>false,'reason'=>'self_ref'];
        if(!bot_referral_user_exists($referrerId)) return ['ok'=>false,'reason'=>'referrer_not_found'];

        if(!$currentUser) $currentUser = bot_referral_read_user($referredId);
        if(!bot_referral_user_can_accept_referrer($currentUser) && !$allowFreshExisting){
            return ['ok'=>false,'reason'=>'already_user'];
        }
        if(!bot_referral_user_can_accept_referrer($currentUser)){
            $existing = bot_referral_find_referrer_for_referred($referredId, $currentUser);
            if($existing === $referrerId) return ['ok'=>true,'reason'=>'already_registered','referrer_id'=>$referrerId];
            return ['ok'=>false,'reason'=>'already_has_referrer','existing_referrer'=>$existing];
        }

        $user = $currentUser ?: bot_referral_create_default_user($referredId, $referrerId);
        $user = array_merge(bot_referral_create_default_user($referredId, $referrerId), $user);
        $user['sub'] = $referrerId;
        $user['referrer_id'] = $referrerId;
        $user['referral_status'] = 'pending_start';
        $user['referral_registered_at'] = $user['referral_registered_at'] ?? time();
        $user['ref_pending_notified'] = $user['ref_pending_notified'] ?? 0;
        bot_referral_write_user($referredId, $user);
        bot_referral_sql_upsert($referrerId, $referredId, 'pending_start', ['registered_at'=>time(), 'payload'=>(string)$payload]);
        bot_referral_event($referrerId, $referredId, 'start_registered', null, 0, null, null, ['payload'=>(string)$payload]);

        if((string)($settings['notify_referrer_on_pending'] ?? '✅فعال') === '✅فعال' && empty($user['ref_pending_notified'])){
            $res = bot_referral_notify_referrer($referrerId, $referredId, 'pending', 0, 'diamond', []);
            $user['ref_pending_notified'] = time();
            $user['ref_pending_notify_ok'] = !empty($res['ok']) ? 1 : 0;
            $user['ref_pending_notify_desc'] = (string)($res['description'] ?? '');
            bot_referral_write_user($referredId, $user);
        }
        return ['ok'=>true,'reason'=>'registered','referrer_id'=>$referrerId,'referred_id'=>$referredId];
    }
}

if(!function_exists('bot_referral_add_balance')){
    function bot_referral_add_balance($userId, $amount, $mode, $reason, array $extra=[]){
        $uid = bot_referral_clean_id($userId);
        $amount = max(0, (int)$amount);
        $u = bot_referral_read_user($uid);
        if(!$u && !bot_referral_user_exists($uid)) return ['ok'=>false,'reason'=>'user_not_found'];
        $before = (int)($u['Points'] ?? 0);
        if($mode !== 'diamond') $mode = 'diamond';
        $after = $before + $amount;
        $u['Points'] = (string)$after;
        $u['wallet_log'][] = ['time'=>time(),'reason'=>$reason,'delta'=>$amount,'before'=>$before,'after'=>$after,'extra'=>$extra];
        bot_referral_write_user($uid, $u);
        return ['ok'=>true,'before'=>$before,'after'=>$after,'data'=>$u];
    }
}

if(!function_exists('bot_referral_collect_forced_join_channels')){
    function bot_referral_collect_forced_join_channels(array $runtimeChannels=[]){
        $out = [];
        $add = function($items) use (&$out){
            foreach((array)$items as $row){
                if(is_array($row)) $ref = $row['ref'] ?? $row['channel'] ?? $row['username'] ?? '';
                else $ref = $row;
                $ref = trim((string)$ref);
                if($ref === '') continue;
                $key = function_exists('bale_forced_join_channel_key') ? bale_forced_join_channel_key($ref) : strtolower($ref);
                if($key === '') $key = strtolower($ref);
                $out[$key] = $ref;
            }
        };
        $add($runtimeChannels);
        if(function_exists('bale_forced_join_channels_active')) $add(bale_forced_join_channels_active());
        if(function_exists('bot_fraud_forced_join_channels')) $add(bot_fraud_forced_join_channels());
        if(function_exists('bot_data_get_text')){
            $add([bot_data_get_text('lib/kodam/channel.txt',''), bot_data_get_text('lib/kodam/channel2.txt','')]);
        }
        return array_values($out);
    }
}

if(!function_exists('bot_referral_missing_forced_join_channels')){
    function bot_referral_missing_forced_join_channels($userId, array $channels, $force=true){
        $uid = bot_referral_clean_id($userId);
        if(!$channels) return [];
        if(function_exists('bot_forced_join_missing_channels')) return bot_forced_join_missing_channels($channels, $uid, (bool)$force);
        $missing = [];
        foreach($channels as $ch){
            $status = function_exists('bale_get_channel_member_status_cached') ? bale_get_channel_member_status_cached($ch, $uid, null, (bool)$force) : (function_exists('bale_get_channel_member_status') ? bale_get_channel_member_status($ch, $uid) : null);
            if($status === null) continue;
            if(function_exists('bale_is_member_status')){ if(!bale_is_member_status($status)) $missing[] = $ch; }
            elseif(!in_array($status, ['creator','administrator','member','restricted'], true)) $missing[] = $ch;
        }
        return array_values(array_unique($missing));
    }
}

if(!function_exists('bot_referral_verified_count_for_referrer')){
    function bot_referral_verified_count_for_referrer($referrerId){
        $referrerId = bot_referral_clean_id($referrerId);
        $pdo = bot_referral_pdo();
        if($pdo && bot_referral_install_schema()){
            try{ $st=$pdo->prepare("SELECT COUNT(*) FROM bot_referrals WHERE referrer_id=? AND status IN ('forced_join_verified','active_rewarded')"); $st->execute([$referrerId]); return (int)$st->fetchColumn(); }catch(Throwable $e){}
        }
        $count = 0;
        foreach(glob('melat/*.json') ?: [] as $file){
            $u = json_decode((string)@file_get_contents($file), true);
            if(!is_array($u)) continue;
            $r = bot_referral_clean_id($u['sub'] ?? ($u['referrer_id'] ?? ''));
            if($r === $referrerId && !empty($u['ref_verified_counted'])) $count++;
        }
        return $count;
    }
}

if(!function_exists('bot_referral_apply_referrer_upgrades')){
    function bot_referral_apply_referrer_upgrades($referrerId, $verifiedCount=null, array $settings=null, array $extra=[]){
        $settings = $settings ?: bot_referral_settings();
        $referrerId = bot_referral_clean_id($referrerId);
        if($referrerId === '') return ['ok'=>false,'reason'=>'bad_referrer'];
        $u = bot_referral_read_user($referrerId);
        if(!$u) return ['ok'=>false,'reason'=>'referrer_not_found'];
        if($verifiedCount === null) $verifiedCount = max((int)($u['zirmjmae'] ?? 0), bot_referral_verified_count_for_referrer($referrerId));
        $oldPanel = (string)($u['type-panel'] ?? 'عادی');
        $newPanel = $oldPanel;
        $proAt = (int)($settings['upgrade_professional_refs'] ?? 0);
        $vipAt = (int)($settings['upgrade_vip_refs'] ?? 0);
        if($vipAt > 0 && $verifiedCount >= $vipAt) $newPanel = 'ویژه';
        elseif($proAt > 0 && $verifiedCount >= $proAt && bot_referral_panel_rank($oldPanel) < 2) $newPanel = 'حرفه‌ای';
        if(bot_referral_panel_rank($newPanel) > bot_referral_panel_rank($oldPanel)){
            $u['type-panel'] = $newPanel;
            $u['referral_upgraded_at'] = time();
            $u['referral_upgrade_refs'] = (string)$verifiedCount;
            bot_referral_write_user($referrerId, $u);
            $text = $newPanel === 'ویژه'
                ? "⭐ تبریک! حساب شما به پرو/ویژه ارتقا پیدا کرد.\n\n📊 زیرمجموعه‌های تأییدشده: {$verifiedCount}"
                : "🚀 تبریک! حساب شما به حرفه‌ای ارتقا پیدا کرد.\n\n📊 زیرمجموعه‌های تأییدشده: {$verifiedCount}";
            if(function_exists('bot')) bot('sendMessage', ['chat_id'=>$referrerId, 'text'=>$text, 'parse_mode'=>'HTML']);
            bot_referral_event($referrerId, $extra['referred_id'] ?? '', 'upgrade_'.$newPanel, null, 0, null, null, ['verified_count'=>$verifiedCount, 'old_panel'=>$oldPanel, 'new_panel'=>$newPanel]);
            return ['ok'=>true,'upgraded'=>true,'old'=>$oldPanel,'new'=>$newPanel];
        }
        return ['ok'=>true,'upgraded'=>false,'panel'=>$oldPanel];
    }
}

if(!function_exists('bot_referral_send_final_forced_join_referral_notice')){
    function bot_referral_send_final_forced_join_referral_notice($referrerId, $referredId, $signupAmount=0, $forcedAmount=0, $after=null, array &$invitee=null){
        $settings = bot_referral_settings();
        if((string)($settings['notify_referrer_on_verified'] ?? '✅فعال') !== '✅فعال') return ['ok'=>false,'description'=>'disabled'];
        if(!function_exists('bot')) return ['ok'=>false,'description'=>'bot_function_missing'];
        $referrerId = bot_referral_clean_id($referrerId);
        $referredId = bot_referral_clean_id($referredId);
        $signupAmount = max(0, (int)$signupAmount);
        $forcedAmount = max(0, (int)$forcedAmount);
        $total = $signupAmount + $forcedAmount;
        if($after === null){ $r = bot_referral_read_user($referrerId); $after = (int)($r['Points'] ?? 0); }
        $verifiedCount = bot_referral_verified_count_for_referrer($referrerId);
        $lines = [];
        $lines[] = "✅ زیرمجموعه شما تأیید شد";
        $lines[] = "";
        $lines[] = "👤 کاربر <code>{$referredId}</code> عضویت کانال‌های جوین اجباری را کامل کرد و روی «بررسی عضویت» زد.";
        if($signupAmount > 0) $lines[] = "🎁 هدیه زیرمجموعه: <b>{$signupAmount}</b> 💎 الماس";
        if($forcedAmount > 0) $lines[] = "🎁 هدیه بررسی عضویت: <b>{$forcedAmount}</b> 💎 الماس";
        $lines[] = "💎 جمع هدیه: <b>{$total}</b> 💎 الماس";
        $lines[] = "💰 موجودی جدید شما: <b>".(int)$after."</b> 💎 الماس";
        $lines[] = "📊 زیرمجموعه‌های تأییدشده شما: <b>{$verifiedCount}</b>";
        $res = bot('sendMessage', ['chat_id'=>$referrerId, 'text'=>implode("\n", $lines), 'parse_mode'=>'HTML']);
        $ok = (is_object($res) && !empty($res->ok)) || (is_array($res) && !empty($res['ok'])) || $res === true;
        $desc = is_object($res) ? (string)($res->description ?? '') : (is_array($res) ? (string)($res['description'] ?? '') : '');
        bot_referral_notify_log('verified', $referrerId, $referredId, $ok, $desc, ['signup'=>$signupAmount, 'forced'=>$forcedAmount, 'after'=>$after]);
        if(is_array($invitee)){
            $invitee['ref_verified_notified'] = time();
            $invitee['ref_verified_notify_ok'] = $ok ? 1 : 0;
            $invitee['ref_verified_notify_desc'] = $desc;
        }
        return ['ok'=>$ok, 'description'=>$desc];
    }
}

if(!function_exists('bot_referral_notify_referrer')){
    function bot_referral_notify_referrer($referrerId, $referredId, $kind, $amount=0, $mode='diamond', array $extra=[]){
        if(!function_exists('bot')) return ['ok'=>false,'description'=>'bot_function_missing'];
        $referrerId = bot_referral_clean_id($referrerId);
        $referredId = bot_referral_clean_id($referredId);
        if($kind === 'pending'){
            $text = "🔔 زیرمجموعه جدید\n\nیک کاربر با لینک دعوت شما وارد ربات شد.\n👤 آیدی کاربر: <code>{$referredId}</code>\n\n⏳ بعد از اینکه عضویت کانال‌های اجباری را کامل کند و روی «بررسی عضویت» بزند، پاداش به موجودی شما اضافه می‌شود.";
        }elseif($kind === 'active'){
            $text = "✅ زیرمجموعه شما فعال شد و پاداش مرحله‌ای دریافت کردید.\n\n👤 آیدی کاربر: <code>{$referredId}</code>\n🎁 پاداش: <b>".(int)$amount."</b> 💎 الماس";
        }else{
            $text = "✅ وضعیت زیرمجموعه بروزرسانی شد.\n👤 آیدی کاربر: <code>{$referredId}</code>";
        }
        $res = bot('sendMessage', ['chat_id'=>$referrerId, 'text'=>$text, 'parse_mode'=>'HTML']);
        $ok = (is_object($res) && !empty($res->ok)) || (is_array($res) && !empty($res['ok'])) || $res === true;
        $desc = is_object($res) ? (string)($res->description ?? '') : (is_array($res) ? (string)($res['description'] ?? '') : '');
        bot_referral_notify_log($kind, $referrerId, $referredId, $ok, $desc, $extra);
        return ['ok'=>$ok, 'description'=>$desc];
    }
}

if(!function_exists('bot_referral_verify_forced_join_and_reward')){
    function bot_referral_verify_forced_join_and_reward($referredId, $force=true, array $runtimeForcedJoinChannels=[]){
        $settings = bot_referral_settings();
        $referredId = bot_referral_clean_id($referredId);
        if($referredId === '') return ['ok'=>false,'reason'=>'bad_user'];
        if((string)($settings['power'] ?? '✅فعال') !== '✅فعال') return ['ok'=>false,'reason'=>'disabled'];

        $invitee = bot_referral_read_user($referredId);
        $referrerId = bot_referral_find_referrer_for_referred($referredId, $invitee);
        if($referrerId === ''){
            $res = ['ok'=>false,'reason'=>'not_referred'];
            bot_referral_verify_log($referredId, '', $res);
            return $res;
        }
        if($referrerId === $referredId){
            $res = ['ok'=>false,'reason'=>'self_ref'];
            bot_referral_verify_log($referredId, $referrerId, $res);
            return $res;
        }
        if(!bot_referral_user_exists($referrerId)){
            $res = ['ok'=>false,'reason'=>'bad_referrer'];
            bot_referral_verify_log($referredId, $referrerId, $res);
            return $res;
        }

        $channels = bot_referral_collect_forced_join_channels($runtimeForcedJoinChannels);
        $requireForced = (string)($settings['require_forced_join_for_reward'] ?? '✅فعال') === '✅فعال';
        if($requireForced && empty($channels)){
            // اگر callback از وبهوک رسیده ولی لیست پیدا نشد، پرداخت نمی‌کنیم؛ لاگ واضح می‌دهیم.
            $res = ['ok'=>false,'reason'=>'no_forced_join_config'];
            bot_referral_verify_log($referredId, $referrerId, $res, ['runtime_channels'=>$runtimeForcedJoinChannels]);
            return $res;
        }
        $missing = $channels ? bot_referral_missing_forced_join_channels($referredId, $channels, (bool)$force) : [];
        if(!empty($missing)){
            $res = ['ok'=>false,'reason'=>'missing_forced_join','missing'=>$missing, 'channels_count'=>count($channels)];
            bot_referral_verify_log($referredId, $referrerId, $res);
            return $res;
        }

        $referrer = bot_referral_read_user($referrerId);
        $signupAmount = 0;
        $forcedAmount = 0;
        $events = [];
        $finalAfter = (int)($referrer['Points'] ?? 0);

        // شمارش زیرمجموعه تأییدشده فقط یک بار
        if(empty($invitee['ref_verified_counted'])){
            $referrer['zirmjmae'] = (string)((int)($referrer['zirmjmae'] ?? 0) + 1);
            $invitee['ref_verified_counted'] = time();
            $events[] = 'verified_counted';
        }

        // پاداش اصلی زیرمجموعه، براساس سطح معرف، اما فقط بعد از بررسی عضویت
        if(empty($invitee['ref_signup_rewarded'])){
            $amount = bot_referral_amount_for_referrer($referrer, $settings);
            if($amount > 0){
                bot_referral_write_user($referrerId, $referrer);
                $balance = bot_referral_add_balance($referrerId, $amount, 'diamond', 'referral_signup_after_forced_join', ['referred_id'=>$referredId]);
                if(!empty($balance['data'])) $referrer = $balance['data'];
                $signupAmount = $amount;
                $finalAfter = (int)($balance['after'] ?? ($referrer['Points'] ?? 0));
                $referrer['zirmjmae-porsant'] = (string)((int)($referrer['zirmjmae-porsant'] ?? 0) + $amount);
                $invitee['ref_signup_rewarded'] = time();
                $invitee['ref_signup_reward_amount'] = (string)$amount;
                bot_referral_event($referrerId, $referredId, 'signup_reward_verified_forced_join', 'diamond', $amount, $balance['before'] ?? null, $balance['after'] ?? null, ['trigger'=>'forced_join_check']);
                $events[] = 'signup_reward';
            }else{
                $invitee['ref_signup_rewarded'] = time();
                $invitee['ref_signup_reward_amount'] = '0';
            }
        }

        // پاداش اضافه بررسی عضویت جوین اجباری، یک بار برای هر زیرمجموعه
        if((string)($settings['ref_join_reward_power'] ?? '✅فعال') === '✅فعال' && empty($invitee['ref_forced_join_bonus_rewarded'])){
            $bonus = (int)($settings['ref_join_reward_per_channel'] ?? 0);
            if($bonus > 0){
                bot_referral_write_user($referrerId, $referrer);
                $balance2 = bot_referral_add_balance($referrerId, $bonus, 'diamond', 'referral_forced_join_check_bonus', ['referred_id'=>$referredId]);
                if(!empty($balance2['data'])) $referrer = $balance2['data'];
                $forcedAmount = $bonus;
                $finalAfter = (int)($balance2['after'] ?? ($referrer['Points'] ?? 0));
                $referrer['zirmjmae-porsant'] = (string)((int)($referrer['zirmjmae-porsant'] ?? 0) + $bonus);
                $invitee['ref_forced_join_bonus_rewarded'] = time();
                $invitee['ref_forced_join_bonus_amount'] = (string)$bonus;
                bot_referral_event($referrerId, $referredId, 'forced_join_check_bonus', 'diamond', $bonus, $balance2['before'] ?? null, $balance2['after'] ?? null, ['trigger'=>'forced_join_check']);
                $events[] = 'forced_join_bonus';
            }else{
                $invitee['ref_forced_join_bonus_rewarded'] = time();
                $invitee['ref_forced_join_bonus_amount'] = '0';
            }
        }

        $invitee['referral_status'] = 'forced_join_verified';
        $invitee['ref_verified_at'] = $invitee['ref_verified_at'] ?? time();
        $invitee['sub'] = $referrerId;
        $invitee['referrer_id'] = $referrerId;
        bot_referral_write_user($referrerId, $referrer);
        bot_referral_write_user($referredId, $invitee);
        bot_referral_sql_mark_verified($referrerId, $referredId, $signupAmount, $forcedAmount, ['verified_at'=>time(), 'events'=>$events, 'channels_count'=>count($channels)]);

        $verifiedCount = max((int)($referrer['zirmjmae'] ?? 0), bot_referral_verified_count_for_referrer($referrerId));
        bot_referral_apply_referrer_upgrades($referrerId, $verifiedCount, $settings, ['referred_id'=>$referredId]);

        $notify = ['ok'=>true,'description'=>'not_needed'];
        if($signupAmount > 0 || $forcedAmount > 0 || empty($invitee['ref_verified_notified'])){
            $notify = bot_referral_send_final_forced_join_referral_notice($referrerId, $referredId, $signupAmount, $forcedAmount, $finalAfter, $invitee);
            bot_referral_write_user($referredId, $invitee);
        }
        $res = ['ok'=>true,'verified'=>true,'amount'=>$signupAmount+$forcedAmount,'signup_amount'=>$signupAmount,'forced_join_amount'=>$forcedAmount,'after'=>$finalAfter,'events'=>$events,'channels_count'=>count($channels),'notify_ok'=>!empty($notify['ok']),'notify_desc'=>(string)($notify['description'] ?? '')];
        bot_referral_verify_log($referredId, $referrerId, $res);
        return $res;
    }
}

// ====== Backward-compatible wrappers for old code ======
if(!function_exists('bot_referral_find_by_referred')){
    function bot_referral_find_by_referred($referredId){
        $uid = bot_referral_clean_id($referredId);
        $row = bot_referral_sql_find($uid);
        if($row) return $row;
        $u = bot_referral_read_user($uid);
        $ref = bot_referral_find_referrer_for_referred($uid, $u);
        if($ref === '') return null;
        return ['referrer_id'=>$ref,'referred_id'=>$uid,'status'=>$u['referral_status'] ?? 'pending_start','signup_reward_applied'=>empty($u['ref_signup_rewarded'])?0:1,'active_reward_applied'=>empty($u['ref_active_rewarded'])?0:1,'referred_join_count'=>(int)($u['ads'] ?? 0)];
    }
}

if(!function_exists('bot_referral_mark_active_awarded')){
    function bot_referral_mark_active_awarded($referredId, $joinCount, $mode, $amount, array $data=[]){
        $row = bot_referral_find_by_referred($referredId);
        if(!$row) return;
        $pdo = bot_referral_pdo();
        if($pdo && bot_referral_install_schema()){
            try{ $st=$pdo->prepare('UPDATE bot_referrals SET active_reward_mode=?, active_reward_amount=?, active_reward_applied=1, referred_join_count=?, status="active_rewarded", data_json=?, updated_at=CURRENT_TIMESTAMP WHERE referred_id=?'); $st->execute([(string)$mode,(int)$amount,(int)$joinCount,bot_referral_json($data),(string)$referredId]); }catch(Throwable $e){}
        }
    }
}

if(!function_exists('bot_referral_update_join_count')){
    function bot_referral_update_join_count($referredId, $joinCount){
        $pdo = bot_referral_pdo();
        if($pdo && bot_referral_install_schema()){
            try{ $st=$pdo->prepare('UPDATE bot_referrals SET referred_join_count=?, updated_at=CURRENT_TIMESTAMP WHERE referred_id=?'); $st->execute([(int)$joinCount,(string)$referredId]); }catch(Throwable $e){}
        }
    }
}

if(!function_exists('bot_referral_handle_member_join_progress')){
    function bot_referral_handle_member_join_progress($referredId, $joinCount, array $settings=null){
        // پاداش هر جوین سفارش حذف شد؛ فقط milestone قدیمی حفظ شده است.
        $settings = $settings ? array_merge(bot_referral_settings(), $settings) : bot_referral_settings();
        $referredId = bot_referral_clean_id($referredId);
        $joinCount = max(0, (int)$joinCount);
        $ref = bot_referral_find_by_referred($referredId);
        if(!$ref || empty($ref['referrer_id'])) return ['ok'=>false,'reason'=>'not_referred'];
        $referrerId = bot_referral_clean_id($ref['referrer_id']);
        bot_referral_update_join_count($referredId, $joinCount);
        $invitee = bot_referral_read_user($referredId);
        $referrer = bot_referral_read_user($referrerId);
        $required = max(1, (int)($settings['zirjoinads'] ?? 20));
        if($joinCount >= $required && empty($invitee['ref_active_rewarded'])){
            $amount = (int)($settings['coin-join'] ?? 0);
            $balance = bot_referral_add_balance($referrerId, $amount, 'diamond', 'referral_active_reward', ['referred_id'=>$referredId,'join_count'=>$joinCount]);
            $referrer = !empty($balance['data']) ? $balance['data'] : bot_referral_read_user($referrerId);
            $referrer['zirmjmae-join'] = (string)max((int)($referrer['zirmjmae-join'] ?? 0), $joinCount);
            $referrer['zirmjmae-porsant'] = (string)((int)($referrer['zirmjmae-porsant'] ?? 0) + $amount);
            $invitee['ref_active_rewarded'] = time();
            bot_referral_write_user($referrerId, $referrer);
            bot_referral_write_user($referredId, $invitee);
            bot_referral_mark_active_awarded($referredId, $joinCount, 'diamond', $amount, ['required'=>$required]);
            bot_referral_event($referrerId, $referredId, 'active_reward', 'diamond', $amount, $balance['before'] ?? null, $balance['after'] ?? null, ['join_count'=>$joinCount,'required'=>$required]);
            bot_referral_notify_referrer($referrerId, $referredId, 'active', $amount, 'diamond', ['join_count'=>$joinCount]);
            return ['ok'=>true,'active_reward'=>$amount];
        }
        return ['ok'=>true,'active_reward'=>0];
    }
}

if(!function_exists('bot_referral_mode_label')){
    function bot_referral_mode_label($mode){ return '💎 الماس'; }
}

if(!function_exists('bot_referral_admin_stats_text')){
    function bot_referral_admin_stats_text($limit=15){
        $settings = bot_referral_settings();
        $total = $verified = $bonus = 0;
        $top = [];
        $pdo = bot_referral_pdo();
        if($pdo && bot_referral_install_schema()){
            try{
                $total = (int)$pdo->query('SELECT COUNT(*) FROM bot_referrals')->fetchColumn();
                $verified = (int)$pdo->query("SELECT COUNT(*) FROM bot_referrals WHERE status IN ('forced_join_verified','active_rewarded')")->fetchColumn();
                $bonus = (int)$pdo->query("SELECT COALESCE(SUM(amount),0) FROM bot_referral_events WHERE event_type IN ('signup_reward_verified_forced_join','forced_join_check_bonus','active_reward')")->fetchColumn();
                $st=$pdo->query("SELECT referrer_id, COUNT(*) refs, SUM(CASE WHEN status IN ('forced_join_verified','active_rewarded') THEN 1 ELSE 0 END) verified_refs FROM bot_referrals GROUP BY referrer_id ORDER BY verified_refs DESC, refs DESC LIMIT ".max(1,(int)$limit));
                $top=$st->fetchAll(PDO::FETCH_ASSOC);
            }catch(Throwable $e){}
        }
        if(!$total){
            foreach(glob('melat/*.json') ?: [] as $file){
                $u=json_decode((string)@file_get_contents($file), true); if(!is_array($u)) continue;
                $ref=bot_referral_clean_id($u['sub'] ?? ($u['referrer_id'] ?? '')); if($ref==='') continue;
                $total++; if(!empty($u['ref_verified_counted'])){ $verified++; $top[$ref]=($top[$ref] ?? 0)+1; }
                $bonus += (int)($u['ref_signup_reward_amount'] ?? 0) + (int)($u['ref_forced_join_bonus_amount'] ?? 0) + (int)($u['ref_active_reward_amount'] ?? 0);
            }
            arsort($top);
            $rows=[]; foreach(array_slice($top,0,$limit,true) as $rid=>$cnt) $rows[]=['referrer_id'=>$rid,'refs'=>$cnt,'verified_refs'=>$cnt]; $top=$rows;
        }
        $text = "👥 <b>آمار رفرال</b>\n\n";
        $text .= "وضعیت: <b>".htmlspecialchars($settings['power'])."</b>\n";
        $text .= "کل ثبت‌ها: <b>{$total}</b>\n";
        $text .= "تأییدشده بعد از جوین اجباری: <b>{$verified}</b>\n";
        $text .= "کل پاداش پرداخت‌شده: <b>{$bonus}</b> 💎\n\n";
        $text .= "🏆 <b>برترین‌ها</b>\n";
        if(!$top) $text .= "فعلاً آماری نیست.";
        else{ $i=1; foreach($top as $r){ $text .= $i.'. <code>'.htmlspecialchars((string)$r['referrer_id']).'</code> — تأییدشده: <b>'.(int)($r['verified_refs'] ?? 0).'</b> / کل: <b>'.(int)($r['refs'] ?? 0)."</b>\n"; $i++; } }
        return $text;
    }
}

if(!function_exists('bot_referral_admin_stats_keyboard')){
    function bot_referral_admin_stats_keyboard(){
        return json_encode(['inline_keyboard'=>[[['text'=>'⚙️ تنظیمات رفرال','callback_data'=>'refadm_back_settings']]]], JSON_UNESCAPED_UNICODE);
    }
}

if(!function_exists('bot_referral_admin_text')){
    function bot_referral_admin_text(){
        $s = bot_referral_settings();
        return "👥 <b>تنظیمات رفرال‌گیری</b>\n\n".
            "وضعیت: <b>{$s['power']}</b>\n".
            "🎁 پاداش زیرمجموعه بعد از بررسی عضویت:\n".
            "عادی: <b>{$s['invitecoin1']}</b> 💎 | حرفه‌ای: <b>{$s['invitecoin2']}</b> 💎 | پرو/ویژه: <b>{$s['invitecoin3']}</b> 💎\n".
            "✅ پاداش اضافه بررسی عضویت: <b>{$s['ref_join_reward_power']}</b> / مقدار: <b>{$s['ref_join_reward_per_channel']}</b> 💎\n".
            "🚀 حرفه‌ای در: <b>{$s['upgrade_professional_refs']}</b> زیرمجموعه تأییدشده\n".
            "⭐ پرو/ویژه در: <b>{$s['upgrade_vip_refs']}</b> زیرمجموعه تأییدشده\n\n".
            "پرداخت فقط بعد از تکمیل کانال‌های جوین اجباری و زدن دکمه «بررسی عضویت» انجام می‌شود.";
    }
}

if(!function_exists('bot_referral_admin_keyboard')){
    function bot_referral_admin_keyboard(){
        $s = bot_referral_settings();
        return json_encode(['inline_keyboard'=>[
            [['text'=>'وضعیت: '.$s['power'], 'callback_data'=>'refadm_toggle_power'], ['text'=>'📊 آمار', 'callback_data'=>'refadm_stats']],
            [['text'=>'عادی: '.$s['invitecoin1'], 'callback_data'=>'refadm_set_invitecoin1'], ['text'=>'حرفه‌ای: '.$s['invitecoin2'], 'callback_data'=>'refadm_set_invitecoin2']],
            [['text'=>'پرو/ویژه: '.$s['invitecoin3'], 'callback_data'=>'refadm_set_invitecoin3']],
            [['text'=>'پاداش بررسی: '.$s['ref_join_reward_power'], 'callback_data'=>'refadm_toggle_ref_join_reward_power'], ['text'=>'مقدار بررسی: '.$s['ref_join_reward_per_channel'], 'callback_data'=>'refadm_set_ref_join_reward_per_channel']],
            [['text'=>'🚀 حرفه‌ای در: '.$s['upgrade_professional_refs'], 'callback_data'=>'refadm_set_upgrade_professional_refs'], ['text'=>'⭐ پرو در: '.$s['upgrade_vip_refs'], 'callback_data'=>'refadm_set_upgrade_vip_refs']],
        ]], JSON_UNESCAPED_UNICODE);
    }
}

if(!function_exists('bot_referral_show_admin')){
    function bot_referral_show_admin($chatId, $editMsgId=null){
        $payload = ['chat_id'=>$chatId, 'text'=>bot_referral_admin_text(), 'parse_mode'=>'HTML', 'reply_markup'=>bot_referral_admin_keyboard()];
        if($editMsgId){ $payload['message_id']=$editMsgId; return bot('editMessageText', $payload); }
        return bot('sendMessage', $payload);
    }
}

if(!function_exists('bot_referral_user_text')){
    function bot_referral_user_text($userId){
        global $boter_id;
        $uid = bot_referral_clean_id($userId);
        $bot = isset($boter_id) && trim((string)$boter_id) !== '' ? ltrim((string)$boter_id, '@') : 'BOT_USERNAME';
        $u = bot_referral_read_user($uid);
        $refs = (int)($u['zirmjmae'] ?? 0);
        $points = (int)($u['Points'] ?? 0);
        return "👥 <b>رفرال‌گیری</b>\n\n".
            "لینک دعوت شما:\n<code>https://t.me/{$bot}?start={$uid}</code>\n\n".
            "✅ زیرمجموعه‌های تأییدشده: <b>{$refs}</b>\n".
            "💰 موجودی شما: <b>{$points}</b> 💎\n\n".
            "پاداش وقتی پرداخت می‌شود که زیرمجموعه کانال‌های جوین اجباری را عضو شود و روی «بررسی عضویت» بزند.";
    }
}

if(!function_exists('bot_referral_user_keyboard')){
    function bot_referral_user_keyboard(){
        return json_encode(['inline_keyboard'=>[[['text'=>'📣 دریافت بنر دعوت','callback_data'=>'ref_user_banner']]]], JSON_UNESCAPED_UNICODE);
    }
}

if(!function_exists('bot_referral_send_user_banner')){
    function bot_referral_send_user_banner($chatId, $userId){
        global $boter_id;
        $uid = bot_referral_clean_id($userId);
        $bot = isset($boter_id) && trim((string)$boter_id) !== '' ? ltrim((string)$boter_id, '@') : 'BOT_USERNAME';
        $s = bot_referral_settings();
        $banner = trim((string)($s['zirtext'] ?? 'با لینک من وارد ربات شو و بعد از عضویت در کانال‌ها، برای من امتیاز بگیر.'));
        $text = $banner."\n\nhttps://t.me/{$bot}?start={$uid}";
        return bot('sendMessage', ['chat_id'=>$chatId, 'text'=>$text, 'parse_mode'=>'HTML']);
    }
}

if(!function_exists('bot_referral_menu_text')){
    function bot_referral_menu_text(){
        global $userID;
        return bot_referral_user_text($userID ?? '');
    }
}

if(!function_exists('bot_referral_runtime_router')){
    function bot_referral_runtime_router(){
        global $msg, $data, $data_id, $chatID, $userID, $Tc, $isAdmin, $msg_id, $Button_back_panel, $user, $step, $starttext, $Button_Home, $forcedJoinMissingChannels, $forcedJoinChannels;
        if(!isset($Tc) || $Tc !== 'private' || empty($userID)) return false;

        if(!empty($isAdmin) && isset($msg) && in_array(trim((string)$msg), ['👥 رفرال‌گیری','⚙️ رفرال‌گیری','تنظیمات رفرال'], true)){
            if(is_array($user)){ $user['step']='none'; bot_referral_write_user($userID, $user); }
            bot_referral_show_admin($chatID);
            return true;
        }
        if(!empty($isAdmin) && isset($msg) && in_array(trim((string)$msg), ['👥 آمار رفرال','📊 آمار رفرال','آمار رفرال'], true)){
            bot('sendMessage', ['chat_id'=>$chatID, 'text'=>bot_referral_admin_stats_text(), 'parse_mode'=>'HTML', 'reply_markup'=>bot_referral_admin_stats_keyboard()]);
            return true;
        }
        if(!empty($isAdmin) && isset($data) && strpos((string)$data, 'refadm_') === 0){
            $d = (string)$data;
            if(!empty($data_id)) bot('answercallbackquery', ['callback_query_id'=>$data_id, 'text'=>'انجام شد', 'show_alert'=>false]);
            if($d === 'refadm_stats'){
                bot('editMessageText', ['chat_id'=>$chatID, 'message_id'=>$msg_id, 'text'=>bot_referral_admin_stats_text(), 'parse_mode'=>'HTML', 'reply_markup'=>bot_referral_admin_stats_keyboard()]);
                return true;
            }
            if($d === 'refadm_back_settings'){
                bot_referral_show_admin($chatID, $msg_id);
                return true;
            }
            $s = bot_referral_settings();
            if($d === 'refadm_toggle_power') $s['power'] = $s['power']==='✅فعال' ? '❌غیر فعال' : '✅فعال';
            elseif($d === 'refadm_toggle_ref_join_reward_power') $s['ref_join_reward_power'] = $s['ref_join_reward_power']==='✅فعال' ? '❌غیر فعال' : '✅فعال';
            elseif(preg_match('/^refadm_set_(invitecoin1|invitecoin2|invitecoin3|zirjoinads|coin_join|ref_join_reward_per_channel|upgrade_professional_refs|upgrade_vip_refs)$/', $d, $m)){
                $field = $m[1] === 'coin_join' ? 'coin-join' : $m[1];
                $user = is_array($user) ? $user : bot_referral_read_user($userID);
                $user['step'] = 'refadm_set_'.$field;
                bot_referral_write_user($userID, $user);
                bot('sendMessage', ['chat_id'=>$chatID, 'text'=>'عدد جدید را ارسال کنید:', 'parse_mode'=>'HTML', 'reply_markup'=>$Button_back_panel ?? null]);
                return true;
            }
            bot_referral_save_settings($s);
            bot_referral_show_admin($chatID, $msg_id);
            return true;
        }
        if(!empty($isAdmin) && isset($step) && preg_match('/^refadm_set_(invitecoin1|invitecoin2|invitecoin3|zirjoinads|coin-join|ref_join_reward_per_channel|upgrade_professional_refs|upgrade_vip_refs)$/', (string)$step, $m) && isset($msg)){
            $v = bot_referral_num($msg, $m[1]==='zirjoinads' ? 1 : 0);
            $s = bot_referral_settings();
            $s[$m[1]] = (string)$v;
            bot_referral_save_settings($s);
            $user = is_array($user) ? $user : bot_referral_read_user($userID);
            $user['step']='none'; bot_referral_write_user($userID, $user);
            bot('sendMessage', ['chat_id'=>$chatID, 'text'=>'✅ تنظیمات رفرال ذخیره شد.', 'parse_mode'=>'HTML', 'reply_markup'=>bot_referral_admin_keyboard()]);
            return true;
        }

        // /start ref route. این مسیر فقط ثبت می‌کند؛ پرداخت فقط forced_join_check است.
        if(isset($msg) && preg_match('/^\/start\s+(.+)$/', trim((string)$msg), $m)){
            $current = bot_referral_read_user($userID);
            $reg = bot_referral_register_start_payload($userID, $m[1], $current, true);
            $txt = isset($starttext) && trim((string)$starttext) !== '' ? $starttext : 'به ربات خوش آمدید.';
            if(function_exists('bot_text_settings_apply_vars') && function_exists('bot_text_settings_user_vars')) $txt = bot_text_settings_apply_vars($txt, bot_text_settings_user_vars());
            bot('sendMessage', ['chat_id'=>$chatID, 'text'=>$txt, 'parse_mode'=>'HTML', 'reply_to_message_id'=>$msg_id ?? null, 'reply_markup'=>$Button_Home ?? null]);
            if(!empty($forcedJoinMissingChannels) && function_exists('bot_send_forced_join_message')) bot_send_forced_join_message($chatID, $forcedJoinMissingChannels);
            elseif(empty($forcedJoinMissingChannels) && function_exists('bot_referral_verify_forced_join_and_reward')) bot_referral_verify_forced_join_and_reward($userID, true, is_array($forcedJoinChannels ?? null) ? $forcedJoinChannels : []);
            return true;
        }

        $labels = ['👥 رفرال‌گیری','👥رفرال‌گیری','👥جذب زیرمجموعه','👥 جذب زیرمجموعه'];
        if(isset($GLOBALS['dok4']) && trim((string)$GLOBALS['dok4']) !== '') $labels[] = trim((string)$GLOBALS['dok4']);
        if(isset($msg) && in_array(trim((string)$msg), array_unique($labels), true)){
            bot('sendMessage', ['chat_id'=>$chatID, 'text'=>bot_referral_user_text($userID), 'parse_mode'=>'HTML', 'reply_markup'=>bot_referral_user_keyboard()]);
            return true;
        }
        if(isset($data) && in_array((string)$data, ['banerzir','ref_user_banner'], true)){
            if(!empty($data_id)) bot('answercallbackquery',['callback_query_id'=>$data_id,'text'=>'بنر دعوت','show_alert'=>false]);
            bot_referral_send_user_banner($chatID, $userID);
            return true;
        }
        return false;
    }
}
