<?php
// Auto-split module from bot.php. Keep this file beside the project root.

// ========================== Telegram runtime / debug bootstrap ==========================
// Bله API is Telegram-like, but the base endpoints are different.
if (!defined('TELEGRAM_API_BASE')) {
    define('TELEGRAM_API_BASE', 'https://api.telegram.org/bot');
}
if (!defined('TELEGRAM_FILE_BASE')) {
    define('TELEGRAM_FILE_BASE', 'https://api.telegram.org/file/bot');
}
ini_set('log_errors', '1');
ini_set('error_log', __DIR__ . '/debug.log');
ini_set('display_errors', '0');
if(!function_exists('mb_strpos')){
    function mb_strpos($haystack, $needle, $offset = 0, $encoding = null){
        return strpos($haystack, $needle, $offset);
    }
}
if(!function_exists('mb_strlen')){
    function mb_strlen($string, $encoding = null){
        return strlen((string)$string);
    }
}
if(!function_exists('mb_substr')){
    function mb_substr($string, $start, $length = null, $encoding = null){
        return $length === null ? substr((string)$string, (int)$start) : substr((string)$string, (int)$start, (int)$length);
    }
}
if(!function_exists('mb_strtolower')){
    function mb_strtolower($string, $encoding = null){
        return strtolower((string)$string);
    }
}
if(!class_exists('CURLFile', false)){
    // Prevent fatal errors on hosts without php-curl. Actual file upload still
    // needs the curl extension and will be logged by bot().
    class CURLFile {
        public $name;
        public $mime;
        public $postname;
        public function __construct($filename, $mime = null, $postname = null){
            $this->name = $filename;
            $this->mime = $mime;
            $this->postname = $postname;
        }
    }
}

function ensure_dir_exists($dir){
    if(!is_dir($dir)){
        @mkdir($dir, 0775, true);
    }
}
function ensure_file_exists($file, $default){
    if(function_exists('bot_data_ensure') && bot_storage_is_managed_path($file)){
        bot_data_ensure($file, $default);
        return;
    }
    $dir = dirname($file);
    if($dir && $dir !== '.') ensure_dir_exists($dir);
    if(!file_exists($file)){
        @file_put_contents($file, $default);
    }
}
foreach(['melat','ads','photos','cache','lib/spam','lib/photos','lib/Button','lib/codes','lib/others','lib/others/codes','lib/kodam','lib/keyboard','lib/keyboard/home'] as $dir){
    ensure_dir_exists($dir);
}

// ========================== Master admins / admin identity ==========================
if(!function_exists('bot_clean_numeric_id')){
    function bot_clean_numeric_id($id){ return preg_replace('/[^0-9]/', '', (string)$id); }
}
if(!function_exists('bot_unique_numeric_ids')){
    function bot_unique_numeric_ids($ids){
        $out = [];
        foreach((array)$ids as $id){
            if(is_array($id)){
                foreach($id as $sub){ $clean = bot_clean_numeric_id($sub); if($clean !== '') $out[] = $clean; }
                continue;
            }
            $clean = bot_clean_numeric_id($id);
            if($clean !== '') $out[] = $clean;
        }
        return array_values(array_unique($out));
    }
}
if(!function_exists('bot_config_master_admin_ids')){
    function bot_config_master_admin_ids(){
        global $admin, $main_admins, $master_admins, $super_admins;
        $ids = [];
        if(isset($admin) && (string)$admin !== '') $ids[] = $admin;
        foreach(['main_admins','master_admins','super_admins'] as $var){
            if(isset($GLOBALS[$var])){
                $v = $GLOBALS[$var];
                if(is_string($v)){
                    $parts = preg_split('/[\s,;]+/', $v, -1, PREG_SPLIT_NO_EMPTY);
                    foreach($parts as $part) $ids[] = $part;
                }elseif(is_array($v)){
                    foreach($v as $part) $ids[] = $part;
                }
            }
        }
        return bot_unique_numeric_ids($ids);
    }
}
if(!function_exists('bot_runtime_admin_list')){
    function bot_runtime_admin_list(){
        $ids = bot_config_master_admin_ids();
        $list = [];
        if(function_exists('bot_data_get_json')){
            $list = bot_data_get_json('lib/kodam/list.json', []);
        }elseif(is_file('lib/kodam/list.json')){
            $list = json_decode((string)@file_get_contents('lib/kodam/list.json'), true);
        }
        if(is_array($list) && isset($list['admins']) && is_array($list['admins'])){
            foreach($list['admins'] as $id) $ids[] = $id;
        }
        return bot_unique_numeric_ids($ids);
    }
}
if(!function_exists('bot_is_master_admin')){
    function bot_is_master_admin($uid){ return in_array(bot_clean_numeric_id($uid), bot_config_master_admin_ids(), true); }
}
if(!function_exists('bot_is_bot_admin')){
    function bot_is_bot_admin($uid){ return in_array(bot_clean_numeric_id($uid), bot_runtime_admin_list(), true); }
}
if(!function_exists('bot_sync_master_admins_to_list')){
    function bot_sync_master_admins_to_list(){
        $masters = bot_config_master_admin_ids();
        if(!$masters) return false;
        $list = [];
        if(function_exists('bot_data_get_json')) $list = bot_data_get_json('lib/kodam/list.json', []);
        elseif(is_file('lib/kodam/list.json')) $list = json_decode((string)@file_get_contents('lib/kodam/list.json'), true);
        if(!is_array($list)) $list = [];
        if(!isset($list['admins']) || !is_array($list['admins'])) $list['admins'] = [];
        if(!isset($list['ban']) || !is_array($list['ban'])) $list['ban'] = [];
        $list['admins'] = bot_unique_numeric_ids(array_merge($list['admins'], $masters));
        if(function_exists('bot_data_put_json')) return bot_data_put_json('lib/kodam/list.json', $list);
        @file_put_contents('lib/kodam/list.json', json_encode($list, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT), LOCK_EX);
        return true;
    }
}
if(!function_exists('bot_master_admin_label')){
    function bot_master_admin_label(){ return implode('، ', bot_config_master_admin_ids()); }
}

if(!function_exists('bot_configured_admin_notify_ids')){
    function bot_configured_admin_notify_ids($extraIds = []){
        $ids = [];
        if(function_exists('bot_runtime_admin_list')){
            foreach(bot_runtime_admin_list() as $id) $ids[] = $id;
        }elseif(function_exists('bot_config_master_admin_ids')){
            foreach(bot_config_master_admin_ids() as $id) $ids[] = $id;
        }else{
            global $admin;
            if(!empty($admin)) $ids[] = $admin;
        }
        foreach((array)$extraIds as $id) $ids[] = $id;
        return function_exists('bot_unique_numeric_ids') ? bot_unique_numeric_ids($ids) : array_values(array_unique(array_filter(array_map('strval', $ids))));
    }
}
if(!function_exists('bot_notify_configured_admins')){
    function bot_notify_configured_admins($text, $parseMode = 'html', $replyMarkup = null, $extraIds = []){
        $ids = bot_configured_admin_notify_ids($extraIds);
        $sent = [];
        foreach($ids as $aid){
            if($aid === '') continue;
            if(function_exists('SM')){
                $res = SM($aid, $text, $parseMode, null, $replyMarkup);
            }else{
                $payload = ['chat_id'=>$aid, 'text'=>$text];
                if($parseMode) $payload['parse_mode'] = $parseMode;
                if($replyMarkup) $payload['reply_markup'] = $replyMarkup;
                $res = function_exists('bot') ? bot('sendMessage', $payload) : false;
            }
            $sent[$aid] = (is_object($res) && !empty($res->ok)) || $res === true;
        }
        return $sent;
    }
}

ensure_file_exists('melat.json', '{"members":0}');
ensure_file_exists('shop-factor.json', '{"factor":{}}');
ensure_file_exists('lib/kodam/list.json', json_encode(['admins'=>bot_config_master_admin_ids(), 'ban'=>[]], JSON_UNESCAPED_UNICODE));
if(function_exists('bot_sync_master_admins_to_list')) bot_sync_master_admins_to_list();
ensure_file_exists('lib/kodam/channel.txt', '');
ensure_file_exists('lib/kodam/channel2.txt', '');
ensure_file_exists('lib/kodam/forced_join_channels.json', json_encode(['channels'=>[], 'updated_at'=>time()], JSON_UNESCAPED_UNICODE));
ensure_file_exists('lib/kodam/cht.txt', '');
ensure_file_exists('lib/kodam/giftch.txt', '');
ensure_file_exists('lib/kodam/channel_map.json', '{}');
ensure_file_exists('lib/kodam/blocked_channels.json', '{}');
ensure_file_exists('lib/kodam/channel_reward_users.json', '{}');
ensure_file_exists('lib/kodam/start_join_ad.json', json_encode(['enabled'=>'❌غیر فعال','text'=>'📢 به ربات خوش آمدید.\nبرای مشاهده کانال ما روی دکمه زیر بزنید.','button_text'=>'📢 ورود به کانال','button_url'=>'','show_mode'=>'once_per_update','updated_at'=>time()], JSON_UNESCAPED_UNICODE));
ensure_file_exists('lib/kodam/start_join_ad_seen.json', '{}');
ensure_file_exists('lib/kodam/manual_receipt_channel.json', json_encode(['enabled'=>'❌غیر فعال','channel_id'=>'','admin_notify_enabled'=>'✅فعال','updated_at'=>time()], JSON_UNESCAPED_UNICODE));
ensure_file_exists('lib/kodam/reward_cooldown.json', '{"days":3}');
ensure_file_exists('lib/kodam/self_reward.json', '{"enabled":false,"days":3}');
ensure_file_exists('lib/kodam/user_status.json', json_encode(['users'=>[], 'updated_at'=>time()], JSON_UNESCAPED_UNICODE));
ensure_file_exists('lib/keyboard/home/styles.json', '{}');
ensure_file_exists('lib/keyboard/channel/styles.json', '{}');
ensure_file_exists('lib/keyboard/channel/layout.json', json_encode(['rows'=>[['DOKC0'],['DOKC1'],['DOKC2','DOKC3'],['DOKC4']], 'updated_at'=>time()], JSON_UNESCAPED_UNICODE));
ensure_file_exists('lib/kodam/data-ads.json', '{"Lock-sabtads":"❌غیر فعال","sabtads":"دستی","eteleatch":"❌غیر فعال","noeeads":"متنی"}');
ensure_file_exists('lib/kodam/data-transfer.json', '{"Condition":"✅فعال","Report":"✅فعال","mintrnfr":"10","maxtrnfr":"100"}');
ensure_file_exists('lib/kodam/data-Cancellads.json', '{"Condition":"✅فعال","mincancell":"1","timecancell":"10","Coefficientadscoin":"0.5"}');
ensure_file_exists('lib/kodam/data-violation.json', '{"enabled":"✅فعال","threshold":10,"admin_direct_delete":"✅فعال","notify_admin":"✅فعال"}');
ensure_file_exists('lib/kodam/data-antispam.json', '{"enabled":"✅فعال","max_messages":5,"window_seconds":10,"block_minutes":3}');
ensure_file_exists('lib/kodam/data-daily.json', '{"enabled":"✅فعال","amount":3,"interval_days":1,"channel_button_enabled":"✅فعال","notify_enabled":"❌غیر فعال","notify_text":"🎁 **الماس روزانه شما آماده دریافت است**\nهدیه امروز شما AMOUNT MONEY است.\nبرای دریافت، روی دکمه زیر بزنید.","success_text":"✅ تبریک!\nبرای این دوره AMOUNT MONEY به حساب شما اضافه شد.\nموجودی فعلی: BALANCE MONEY\nدریافت بعدی بعد از DAYS روز امکان‌پذیر است.","cooldown_text":"⏱ شما قبلاً هدیه این دوره را دریافت کرده‌اید.\nزمان باقی‌مانده: REMAINING"}');
ensure_file_exists('lib/kodam/data-power.json', '{"power":"روشن","power-text":"✅فعال","powertext":"ربات موقتاً خاموش است"}');
ensure_file_exists('lib/kodam/data-zirmjmae.json', '{"power-join":"✅فعال","banerzir":"📝متنی","power":"✅فعال","Report":"✅فعال","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":"✅فعال"}');
ensure_file_exists('lib/kodam/data-fraud.json', json_encode(['enabled'=>'✅فعال','referral_require_forced_join'=>'✅فعال','strict_no_forced_join_no_reward'=>'✅فعال','notify_referrer_after_verified'=>'✅فعال','log_referral_start'=>'✅فعال','log_forced_join_leave'=>'✅فعال','min_verify_seconds'=>0,'pending_expire_days'=>14], JSON_UNESCAPED_UNICODE));
ensure_file_exists('lib/kodam/data-left.json', json_encode(['enabled'=>'✅فعال','leftday'=>'3','ksrleft'=>'2','afzleft'=>'1','max_checks'=>'20','instant_max_checks'=>'500','instant_max_seconds'=>'25','grace_minutes'=>'30','confirm_attempts'=>'2','notify_user'=>'✅فعال','notify_owner'=>'✅فعال','auto_penalty'=>'✅فعال','event_auto_penalty'=>'✅فعال','event_max_orders'=>'50'], JSON_UNESCAPED_UNICODE));

// Seed default button names and keyboard layout into SQL/file storage.
// Without this, a fresh SQL install has empty button settings and renaming buttons may appear not to work.
$__buttonDefaults = dirname(__DIR__) . '/lib/button_defaults.php';
if (is_file($__buttonDefaults)) {
    include_once $__buttonDefaults;
    if (function_exists('bot_seed_button_defaults')) {
        bot_seed_button_defaults(true);
    }
}
