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

// ========================== Home keyboard layout manager ==========================
// Admin can move buttons, clear slots, and hide/show main menu buttons.
function bot_home_button_tokens(){
    return ['DOK1','DOK2','DOK3','DOK4','DOK6','DOK9','DOK0','DUQ1','TICKET','SPONSOR','REACTION'];
}
function bot_home_slot_keys(){
    $out = [];
    for($r=1; $r<=8; $r++){
        for($c=1; $c<=4; $c++) $out[] = 'line'.$r.$c;
    }
    return $out;
}
function bot_home_default_layout(){
    return [
        'line11'=>'DOK1',       'line12'=>'DOK2', 'line13'=>'',     'line14'=>'',
        'line21'=>'DOK3',       'line22'=>'DOK4', 'line23'=>'',     'line24'=>'',
        'line31'=>'DOK6',       'line32'=>'DOK9', 'line33'=>'',     'line34'=>'',
        'line41'=>'DOK0',       'line42'=>'DUQ1', 'line43'=>'TICKET','line44'=>'SPONSOR',
        'line51'=>'REACTION',   'line52'=>'',     'line53'=>'',     'line54'=>'',
        'line61'=>'',           'line62'=>'',     'line63'=>'',     'line64'=>'',
        'line71'=>'',           'line72'=>'',     'line73'=>'',     'line74'=>'',
        'line81'=>'',           'line82'=>'',     'line83'=>'',     'line84'=>'',
    ];
}
function bot_home_button_labels(){
    global $dok1,$dok2,$dok3,$dok4,$dok5,$dok6,$dok7,$dok8,$dok9,$dok0,$dok11;
    return [
        'TICKET'=>'🎫 پشتیبانی',
        'SPONSOR'=>'🤝 اسپانسر',
        'REACTION'=>'🔥 خرید ری‌اکشن',
        'DOK1'=>(string)$dok1,
        'DOK2'=>(string)$dok2,
        'DOK3'=>(string)$dok3,
        'DOK4'=>(string)$dok4,
        'DOK5'=>(string)$dok5,
        'DOK6'=>(string)$dok6,
        'DOK7'=>(string)$dok7,
        'DOK8'=>(string)$dok8,
        'DOK9'=>(string)$dok9,
        'DOK0'=>(string)$dok0,
        'DUQ1'=>(string)$dok11,
    ];
}
function bot_home_token_label($token){
    $token = strtoupper(trim((string)$token));
    if(in_array($token, ['DOK5','DOK7'], true)) return ''; // بانک انتقال و پنل‌ها حذف شدند
    if($token === 'DOK4') return '👥 رفرال‌گیری';
    if($token === 'DOK9') return '🛍 فروشگاه';
    if($token === 'TICKET') return '🎫 پشتیبانی';
    if($token === 'SPONSOR') return '🤝 اسپانسر';
    if($token === 'REACTION') return '🔥 خرید ری‌اکشن';
    $labels = bot_home_button_labels();
    $label = isset($labels[$token]) ? trim((string)$labels[$token]) : '';
    $bad = ['بانک انتقال','مبادلات','پنل','پـنـل','اشتراک باقی','زیرمجموعه','برترین'];
    foreach($bad as $b){ if($label !== '' && mb_strpos($label, $b, 0, 'UTF-8') !== false) return ''; }
    return $label;
}
function bot_home_disabled_tokens(){
    $data = bot_data_get_json('lib/keyboard/home/disabled.json', []);
    if(!is_array($data)) $data = [];
    $out = [];
    foreach($data as $v){
        $v = strtoupper(trim((string)$v));
        if(in_array($v, bot_home_button_tokens(), true)) $out[] = $v;
    }
    return array_values(array_unique($out));
}
function bot_home_save_disabled_tokens($tokens){
    $clean = [];
    foreach((array)$tokens as $v){
        $v = strtoupper(trim((string)$v));
        if(in_array($v, bot_home_button_tokens(), true)) $clean[] = $v;
    }
    saveJson('lib/keyboard/home/disabled.json', array_values(array_unique($clean)));
}
function bot_home_is_disabled($token){
    return in_array(strtoupper((string)$token), bot_home_disabled_tokens(), true);
}

function bot_home_style_options(){
    return [
        '' => 'پیش‌فرض',
        'primary' => 'آبی / Primary',
        'success' => 'سبز / Success',
        'danger' => 'قرمز / Danger',
    ];
}
function bot_home_normalize_style($style){
    $style = strtolower(trim((string)$style));
    return in_array($style, ['primary','success','danger'], true) ? $style : '';
}
function bot_home_styles_file(){
    return 'lib/keyboard/home/styles.json';
}
function bot_home_button_styles(){
    $data = bot_data_get_json(bot_home_styles_file(), []);
    if(!is_array($data)) $data = [];
    $out = [];
    foreach($data as $token=>$style){
        $token = strtoupper(trim((string)$token));
        if(!in_array($token, bot_home_button_tokens(), true)) continue;
        $style = bot_home_normalize_style($style);
        if($style !== '') $out[$token] = $style;
    }
    return $out;
}
function bot_home_save_button_styles($styles){
    $out = [];
    foreach((array)$styles as $token=>$style){
        $token = strtoupper(trim((string)$token));
        if(!in_array($token, bot_home_button_tokens(), true)) continue;
        $style = bot_home_normalize_style($style);
        if($style !== '') $out[$token] = $style;
    }
    saveJson(bot_home_styles_file(), $out);
    return $out;
}
function bot_home_button_style($token){
    $token = strtoupper(trim((string)$token));
    $styles = bot_home_button_styles();
    return isset($styles[$token]) ? bot_home_normalize_style($styles[$token]) : '';
}
function bot_home_keyboard_button_object($token, $label){
    $btn = ['text'=>(string)$label];
    $style = bot_home_button_style($token);
    if($style !== '') $btn['style'] = $style;
    return $btn;
}

function bot_home_slot_file($slot){ return 'lib/keyboard/home/'.$slot.'.txt'; }
function bot_home_get_slot_token($slot){
    $slot = trim((string)$slot);
    if(!preg_match('/^line[1-8][1-4]$/', $slot)) return '';
    $raw = trim((string)bot_data_get_text(bot_home_slot_file($slot), ''));
    $raw = strtoupper($raw);
    if(!in_array($raw, bot_home_button_tokens(), true)) return '';
    return $raw;
}
function bot_home_set_slot_token($slot, $token, $moveUnique = true){
    $slot = trim((string)$slot);
    $token = strtoupper(trim((string)$token));
    if(!preg_match('/^line[1-8][1-4]$/', $slot)) return false;
    if($token !== '' && !in_array($token, bot_home_button_tokens(), true)) return false;
    if($moveUnique && $token !== ''){
        foreach(bot_home_slot_keys() as $s){
            if($s !== $slot && bot_home_get_slot_token($s) === $token){
                Save(bot_home_slot_file($s), '');
            }
        }
    }
    Save(bot_home_slot_file($slot), $token);
    return true;
}

function bot_home_normalize_layout(){
    // Keep every home-menu token in exactly one slot. If duplicates exist, the last
    // slot wins because it is usually the newest move made by the admin.
    $valid = bot_home_button_tokens();
    $slots = bot_home_slot_keys();
    $seen = [];
    $changed = false;
    for($i = count($slots) - 1; $i >= 0; $i--){
        $slot = $slots[$i];
        $file = bot_home_slot_file($slot);
        $raw = strtoupper(trim((string)bot_data_get_text($file, '')));
        if($raw === '') continue;
        if(!in_array($raw, $valid, true) || isset($seen[$raw])){
            Save($file, '');
            $changed = true;
            continue;
        }
        $seen[$raw] = true;
        if($raw !== trim((string)bot_data_get_text($file, ''))){
            Save($file, $raw);
            $changed = true;
        }
    }
    return $changed;
}
function bot_home_cleanup_removed_tokens(){
    return bot_home_normalize_layout();
}
function bot_home_reset_layout(){
    foreach(bot_home_default_layout() as $slot=>$token){
        if(in_array(strtoupper((string)$token), ['DOK5','DOK7','DOK8'], true)) $token = '';
        Save(bot_home_slot_file($slot), $token);
    }
    // حذف دائمی بانک انتقال، پنل‌ها و برترین‌ها از منوی کاربران
    bot_home_save_disabled_tokens(['DOK5','DOK7','DOK8']);
}


function bot_home_repair_core_buttons($force = false){
    // Fresh installs must show the complete user menu, not only the two buttons
    // that are restored by safety patches. If the saved layout is empty/broken,
    // rebuild the visible core menu from defaults.
    if(function_exists('bot_seed_button_defaults')) bot_seed_button_defaults(true);
    $removed = ['DOK5','DOK7','DOK8'];
    $visible = [];
    foreach(bot_home_slot_keys() as $slot){
        $token = bot_home_get_slot_token($slot);
        if($token !== '' && !in_array($token, $removed, true) && trim((string)bot_home_token_label($token)) !== '') $visible[$token] = true;
    }
    $need = ['DOK1','DOK2','DOK3','DOK4','DOK6','DOK9','DOK0','DUQ1','TICKET','SPONSOR','REACTION'];
    $missing = array_values(array_filter($need, function($t) use ($visible){ return empty($visible[$t]); }));
    if(!$force && count($visible) >= 5 && empty($missing)) return false;
    if(!$force && count($visible) >= 5 && count($missing) <= 1){
        // Do not skip restoring support; it is the user's only ticket entry point.
        if(in_array('TICKET', $missing, true)) return bot_home_restore_support_ticket_button();
        if(in_array('REACTION', $missing, true)) return bot_home_restore_reaction_button();
        return false;
    }

    foreach(bot_home_default_layout() as $slot=>$token){
        Save(bot_home_slot_file($slot), (string)$token);
    }
    bot_home_save_disabled_tokens(['DOK5','DOK7','DOK8']);
    return true;
}

function bot_home_purge_removed_menu_tokens(){
    // حذف کامل دکمه‌های قدیمی از چینش ذخیره‌شده؛ حتی اگر قبلاً در فایل‌های line ذخیره شده باشند.
    $removed = ['DOK5','DOK7','DOK8'];
    foreach(bot_home_slot_keys() as $slot){
        $raw = strtoupper(trim((string)bot_data_get_text(bot_home_slot_file($slot), '')));
        if(in_array($raw, $removed, true)) Save(bot_home_slot_file($slot), '');
    }
}


function bot_home_layout_contains_token($token){
    $token = strtoupper(trim((string)$token));
    foreach(bot_home_slot_keys() as $slot){ if(bot_home_get_slot_token($slot) === $token) return true; }
    return false;
}
function bot_home_restore_orders_tracking_button(){
    // The order-tracking button is critical; restore it if an older layout patch removed it.
    $disabled = bot_home_disabled_tokens();
    $disabled = array_values(array_unique(array_merge(array_diff($disabled, ['DOK6']), ['DOK5','DOK7','DOK8'])));
    bot_home_save_disabled_tokens($disabled);
    if(bot_home_layout_contains_token('DOK6')) return;
    $target = bot_home_get_slot_token('line41') === '' ? 'line41' : '';
    if($target === ''){
        foreach(bot_home_slot_keys() as $slot){ if(bot_home_get_slot_token($slot) === ''){ $target = $slot; break; } }
    }
    if($target !== '') bot_home_set_slot_token($target, 'DOK6', true);
}

function bot_home_restore_support_ticket_button(){
    // User support must always be reachable unless the admin explicitly disabled TICKET.
    $disabled = bot_home_disabled_tokens();
    if(in_array('TICKET', $disabled, true)) return false;
    if(bot_home_layout_contains_token('TICKET')) return false;

    $preferred = ['line43','line44','line42','line34','line33','line51','line52','line53','line54'];
    $target = '';
    foreach($preferred as $slot){
        if(bot_home_get_slot_token($slot) === ''){ $target = $slot; break; }
    }
    if($target === ''){
        foreach(bot_home_slot_keys() as $slot){
            if(bot_home_get_slot_token($slot) === ''){ $target = $slot; break; }
        }
    }
    if($target === '') return false;
    bot_home_set_slot_token($target, 'TICKET', true);
    return true;
}

function bot_home_restore_sponsor_button(){
    // Sponsor must be reachable unless the admin explicitly disabled SPONSOR.
    $disabled = bot_home_disabled_tokens();
    if(in_array('SPONSOR', $disabled, true)) return false;
    if(bot_home_layout_contains_token('SPONSOR')) return false;
    $preferred = ['line44','line51','line52','line53','line54','line34','line33','line42'];
    $target = '';
    foreach($preferred as $slot){
        if(bot_home_get_slot_token($slot) === ''){ $target = $slot; break; }
    }
    if($target === ''){
        foreach(bot_home_slot_keys() as $slot){ if(bot_home_get_slot_token($slot) === ''){ $target = $slot; break; } }
    }
    if($target === '') return false;
    bot_home_set_slot_token($target, 'SPONSOR', true);
    return true;
}



function bot_home_restore_reaction_button(){
    // Reaction shop must be reachable unless the admin explicitly disabled REACTION.
    $disabled = bot_home_disabled_tokens();
    if(in_array('REACTION', $disabled, true)) return false;
    if(bot_home_layout_contains_token('REACTION')) return false;
    $preferred = ['line51','line52','line53','line54','line44','line34','line33','line42'];
    $target = '';
    foreach($preferred as $slot){
        if(bot_home_get_slot_token($slot) === ''){ $target = $slot; break; }
    }
    if($target === ''){
        foreach(bot_home_slot_keys() as $slot){ if(bot_home_get_slot_token($slot) === ''){ $target = $slot; break; } }
    }
    if($target === '') return false;
    bot_home_set_slot_token($target, 'REACTION', true);
    return true;
}

function bot_home_restore_daily_reward_button(){
    // Compatibility name kept, but the separate DAILYREWARD button has been removed.
    // The only user-side entry must be DOK1 with the visible label "💎 جمع اوری الماس".
    $removed = ['DAILYREWARD','DOK5','DOK7','DOK8'];
    $disabled = bot_home_disabled_tokens();
    $disabled = array_values(array_unique(array_merge(array_diff($disabled, ['DOK1']), ['DOK5','DOK7','DOK8'])));
    bot_home_save_disabled_tokens($disabled);

    foreach(bot_home_slot_keys() as $slot){
        $raw = strtoupper(trim((string)bot_data_get_text(bot_home_slot_file($slot), '')));
        if(in_array($raw, $removed, true)) Save(bot_home_slot_file($slot), '');
    }

    $topSlot = 'line11';
    if(bot_home_get_slot_token($topSlot) === 'DOK1') return;

    $oldTop = bot_home_get_slot_token($topSlot);
    foreach(bot_home_slot_keys() as $slot){
        if($slot !== $topSlot && bot_home_get_slot_token($slot) === 'DOK1'){
            Save(bot_home_slot_file($slot), '');
        }
    }

    if($oldTop !== '' && $oldTop !== 'DOK1' && !in_array($oldTop, ['DOK5','DOK7','DOK8','DAILYREWARD'], true)){
        $moveTo = '';
        $preferred = ['line12','line21','line22','line31','line32','line41','line42','line43','line13','line14','line23','line24','line33','line34'];
        foreach($preferred as $slot){
            if($slot !== $topSlot && bot_home_get_slot_token($slot) === ''){ $moveTo = $slot; break; }
        }
        if($moveTo === ''){
            foreach(bot_home_slot_keys() as $slot){
                if($slot !== $topSlot && bot_home_get_slot_token($slot) === ''){ $moveTo = $slot; break; }
            }
        }
        if($moveTo !== '') Save(bot_home_slot_file($moveTo), $oldTop);
    }

    Save(bot_home_slot_file($topSlot), 'DOK1');
    Save('lib/Button/dok1.txt', '💎 جمع اوری الماس');
}

function bot_reset_button_names_to_defaults(){
    $count = 0;
    if(!function_exists('bot_button_default_values')) return 0;
    foreach(bot_button_default_values() as $path=>$value){
        if(strpos($path, 'lib/Button/') !== 0) continue; // only reset button names/text labels, not keyboard layout
        Save($path, (string)$value);
        $count++;
    }
    if(function_exists('bot_seed_button_defaults')) bot_seed_button_defaults(true);
    if(function_exists('bot_cache_clear_heavy')) bot_cache_clear_heavy();
    return $count;
}
function bot_buttons_panel_keyboard(){
    global $money,$icmoney;
    $money = bot_data_get_text('lib/Button/money.txt', $money);
    $icmoney = bot_data_get_text('lib/Button/icmoney.txt', $icmoney);
    return json_encode(['inline_keyboard' => [
        [["text" => "💎 واحد امتیاز: $money", 'callback_data' => "uyfuyfuyyf"], ["text" => "آیکون: $icmoney", 'callback_data' => "tdxytdciyt"]],
        [["text" => "🧩 چینش و خاموش/روشن منوی کاربران", 'callback_data' => "home_layout"]],
        [["text" => "♻️ ریست نام دکمه‌ها", 'callback_data' => "reset_button_names_ask"]],
        [["text" => "🔙 بازگشت به منوی ادمین", 'callback_data' => "admin_main_menu"]],
    ]], JSON_UNESCAPED_UNICODE);
}
function bot_member_order_value_is_placeholder($value){
    $value = trim((string)$value);
    if($value === '') return true;
    $normalized = mb_strtolower($value, 'UTF-8');
    $bad = ['', 'تنظیم نشده', 'null', 'none', '0', '-', 'تنظیم عضو', 'تنظیم الماس', 'تنظیم سکه'];
    if(in_array($normalized, $bad, true) || in_array($value, $bad, true)) return true;
    return (mb_strpos($normalized, 'تنظیم نشده') !== false);
}
function bot_member_order_read_item($i){
    $i = (int)$i;
    $name = trim((string)bot_data_get_text("lib/Button/dokt{$i}.txt", ''));
    $members = trim((string)bot_data_get_text("lib/Button/memsabt{$i}.txt", ''));
    $coins = trim((string)bot_data_get_text("lib/Button/coinsabt{$i}.txt", ''));
    $ok = !bot_member_order_value_is_placeholder($name)
        && preg_match('/^\d+$/', $members) && (int)$members > 0
        && preg_match('/^\d+$/', $coins) && (int)$coins > 0;
    return ['i'=>$i, 'name'=>$name, 'members'=>$members, 'coins'=>$coins, 'ok'=>$ok];
}
function bot_member_order_items($configuredOnly = true){
    $out = [];
    for($i=1; $i<=6; $i++){
        $it = bot_member_order_read_item($i);
        if(!$configuredOnly || $it['ok']) $out[] = $it;
    }
    return $out;
}
function bot_member_order_keyboard($orderkey = 1){
    global $money;
    // User side: show ONLY fully configured items. Never show placeholders such as تنظیم نشده.
    $items = bot_member_order_items(true);
    $rows = [];
    if(empty($items)){
        $rows[] = [["text"=>"❌ هنوز آیتم سفارشی توسط ادمین تنظیم نشده", 'callback_data'=>"0"]];
        return json_encode(['inline_keyboard'=>$rows], JSON_UNESCAPED_UNICODE);
    }
    $chunk = ((string)$orderkey === '3') ? 1 : 2;
    $row = [];
    foreach($items as $it){
        if(empty($it['ok'])) continue;
        $label = trim((string)$it['name']);
        // Keep the button useful and clear without exposing any unset item.
        if($label === '' || bot_member_order_value_is_placeholder($label)) continue;
        $row[] = ["text"=>$label, 'callback_data'=>"cr-{$it['members']}-{$it['coins']}-item{$it['i']}"];
        if(count($row) >= $chunk){ $rows[] = $row; $row = []; }
    }
    if(!empty($row)) $rows[] = $row;
    if(empty($rows)) $rows[] = [["text"=>"❌ هنوز آیتم سفارشی توسط ادمین تنظیم نشده", 'callback_data'=>"0"]];
    return json_encode(['inline_keyboard'=>$rows], JSON_UNESCAPED_UNICODE);
}
function bot_member_order_admin_keyboard(){
    global $money,$icmoney,$data_ads,$data_left;
    if(!is_array($data_ads)) $data_ads = bot_data_get_json('lib/kodam/data-ads.json');
    if(!is_array($data_left)) $data_left = bot_data_get_json('lib/kodam/data-left.json');
    $rows = [
        [["text"=>isset($data_ads['Lock-sabtads'])?$data_ads['Lock-sabtads']:'❌غیر فعال', 'callback_data'=>"dpo_Lock-sabtads"],["text"=>"🎯 قفل ثبت سفارش", 'callback_data'=>"0"]],
        [["text"=>isset($data_ads['noeeads'])?$data_ads['noeeads']:'متنی', 'callback_data'=>"dpo_noeeads"],["text"=>"🖌 نوع سفارش", 'callback_data'=>"0"]],
        [["text"=>isset($data_ads['eteleatch'])?$data_ads['eteleatch']:'❌غیر فعال', 'callback_data'=>"dpo_eteleatch"],["text"=>"📊 دریافت اطلاعات کانال", 'callback_data'=>"0"]],
        [["text"=>"🚫 تنظیمات ترک کانال", 'callback_data'=>"0"]],
        [["text"=>(isset($data_left['leftday'])?$data_left['leftday']:'0')." روز", 'callback_data'=>"coin_left-leftday"],["text"=>"⏰ مهلت ترک", 'callback_data'=>"0"]],
        [["text"=>isset($data_left['ksrleft'])?$data_left['ksrleft']:'0', 'callback_data'=>"ksr_left-ksrleft"],["text"=>"$icmoney کسر $money", 'callback_data'=>"0"]],
        [["text"=>isset($data_left['afzleft'])?$data_left['afzleft']:'0', 'callback_data'=>"afz_left-afzleft"],["text"=>"$icmoney $money بازگشتی", 'callback_data'=>"0"]],
        [["text"=>"🔰 آیتم‌های سفارش ممبر", 'callback_data'=>"0"]],
    ];
    for($i=1; $i<=6; $i++){
        $it = bot_member_order_read_item($i);
        if($it['ok']){
            $summary = "✅ آیتم {$i}: ".$it['name']." | {$it['members']} عضو | {$it['coins']} {$money}";
        }else{
            $missing = [];
            if(bot_member_order_value_is_placeholder($it['name'])) $missing[] = 'نام';
            if(!preg_match('/^\d+$/', (string)$it['members']) || (int)$it['members'] <= 0) $missing[] = 'عضو';
            if(!preg_match('/^\d+$/', (string)$it['coins']) || (int)$it['coins'] <= 0) $missing[] = 'هزینه';
            $summary = "➕ آیتم {$i} ناقص: ".implode('، ', $missing);
        }
        $rows[] = [["text"=>$summary, 'callback_data'=>"0"]];
        $rows[] = [
            ["text"=>"✏️ نام", 'callback_data'=>"aytem_ads-dokt{$i}"],
            ["text"=>"💎 هزینه", 'callback_data'=>"coin_ads-coinsabt{$i}"],
            ["text"=>"👥 عضو", 'callback_data'=>"member_ads-memsabt{$i}"],
        ];
    }
    $rows[] = [["text"=>"📚 فیلم یا متن آموزشی /help", 'callback_data'=>"set_help_ads"]];
    $rows[] = [["text"=>"🔙بازگشت به منوی ادمین", 'callback_data'=>"admin_main_menu"]];
    return json_encode(['inline_keyboard'=>$rows], JSON_UNESCAPED_UNICODE);
}

function bot_home_is_back_label($label){
    $label = trim((string)$label);
    if(in_array($label, ['🔙بازگشت به منو','🔙 بازگشت به منو','🔙بازگشت','🔙 بازگشت','➡️ بازگشت','↩️ بازگشت','⬅️ بازگشت','🔙 برگشت','بازگشت','برگشت'], true)) return true;
    $compact = preg_replace('/[^\p{L}\p{N}]+/u', '', $label);
    return in_array($compact, ['بازگشت','برگشت','بازگشتبهمنو','برگشتبهمنو'], true);
}
function bot_home_render_token_for_keyboard($token){
    $token = strtoupper(trim((string)$token));
    if($token === '' || bot_home_is_disabled($token)) return '';
    $label = bot_home_token_label($token);
    // Back buttons are only for temporary step keyboards; never show them in the normal user home menu.
    if(bot_home_is_back_label($label)) return '';
    return $label;
}
function bot_home_build_reply_keyboard($includeAdmin = null){
    global $isAdmin;
    bot_home_normalize_layout();
    bot_home_restore_support_ticket_button();
    bot_home_restore_sponsor_button();
    bot_home_restore_reaction_button();
    if($includeAdmin === null) $includeAdmin = !empty($isAdmin);
    $rows = [];
    if(!empty($includeAdmin)) $rows[] = [['text'=>'👤 پنل مدیریت 👤']];
    for($r=1; $r<=8; $r++){
        $row = [];
        for($c=1; $c<=4; $c++){
            $slot = 'line'.$r.$c;
            $label = bot_home_render_token_for_keyboard(bot_home_get_slot_token($slot));
            if(trim($label) !== '' && !bot_home_is_back_label($label)) $row[] = bot_home_keyboard_button_object(bot_home_get_slot_token($slot), $label);
        }
        if(!empty($row)) $rows[] = $row;
    }
    if(empty($rows)) $rows[] = [['text'=>'/start']];
    return json_encode(['keyboard'=>$rows, 'resize_keyboard'=>true], JSON_UNESCAPED_UNICODE);
}
function bot_home_slot_admin_label($slot){
    $token = bot_home_get_slot_token($slot);
    if($token === '') return '➕ خالی';
    $label = bot_home_token_label($token);
    if($label === '') $label = $token;
    $prefix = bot_home_is_disabled($token) ? '🚫 ' : '✅ ';
    if(function_exists('mb_substr')) $label = mb_substr($label, 0, 18, 'UTF-8');
    else $label = substr($label, 0, 18);
    return $prefix.$label;
}
function bot_home_row_summary($rowNumber){
    $rowNumber = max(1, min(8, (int)$rowNumber));
    $parts = [];
    for($c=1; $c<=4; $c++){
        $slot = 'line'.$rowNumber.$c;
        $token = bot_home_get_slot_token($slot);
        if($token === ''){ $parts[] = '➕ خالی'; continue; }
        $label = bot_home_token_label($token);
        if($label === '') $label = $token;
        if(function_exists('mb_substr')) $label = mb_substr($label, 0, 10, 'UTF-8'); else $label = substr($label, 0, 10);
        $parts[] = (bot_home_is_disabled($token) ? '🚫 ' : '✅ ') . $label;
    }
    return implode(' | ', $parts);
}
function bot_home_layout_keyboard(){
    $rows = [];
    for($r=1; $r<=8; $r+=2){
        $rows[] = [
            ['text'=>'📍 ردیف '.$r, 'callback_data'=>'home_row-'.$r],
            ['text'=>($r+1 <= 8 ? '📍 ردیف '.($r+1) : '—'), 'callback_data'=>($r+1 <= 8 ? 'home_row-'.($r+1) : '0')],
        ];
    }
    $rows[] = [
        ['text'=>'🚫 فعال/غیرفعال دکمه‌ها', 'callback_data'=>'home_toggle_panel'],
        ['text'=>'🎨 رنگ دکمه‌ها', 'callback_data'=>'home_style_panel'],
    ];
    $rows[] = [
        ['text'=>'♻️ ریست چینش', 'callback_data'=>'home_reset_ask'],
    ];
    $rows[] = [
        ['text'=>'➡️ بازگشت به تنظیم دکمه‌ها', 'callback_data'=>'backbuttons'],
    ];
    return json_encode(['inline_keyboard'=>$rows], JSON_UNESCAPED_UNICODE);
}
function bot_home_layout_text(){
    bot_home_normalize_layout();
    $disabled = bot_home_disabled_tokens();
    $disabledCount = count($disabled);
    $filled = 0;
    foreach(bot_home_slot_keys() as $slot) if(bot_home_get_slot_token($slot) !== '') $filled++;
    $preview = [];
    for($r=1; $r<=8; $r++){
        $summary = bot_home_row_summary($r);
        if(trim(str_replace(['➕ خالی','|'], '', $summary)) !== ''){
            $preview[] = "**ردیف $r:** <code>".htmlspecialchars($summary, ENT_QUOTES, 'UTF-8')."</code>";
        }
    }
    if(empty($preview)) $preview[] = 'هنوز چینشی ثبت نشده است.';
    return "🧩 **مدیریت چینش منوی کاربران**\n\n".
           "برای تغییر جای دکمه‌ها، اول ردیف را انتخاب کن و بعد خانه موردنظر را بزن.\n".
           "اگر یک دکمه را جای جدید بگذاری، از جای قبلی حذف می‌شود.\n\n".
           "📌 خانه‌های پر: <code>$filled</code>\n".
           "🚫 دکمه‌های غیرفعال: <code>$disabledCount</code>\n\n".
           implode("\n", $preview);
}
function bot_home_row_text($rowNumber){
    $rowNumber = max(1, min(8, (int)$rowNumber));
    return "📍 **ویرایش ردیف $rowNumber منوی کاربران**\n\n".
           "روی هر خانه بزن تا دکمه آن را تغییر بدهی یا خالی‌اش کنی.\n\n".
           "وضعیت فعلی:\n<code>".htmlspecialchars(bot_home_row_summary($rowNumber), ENT_QUOTES, 'UTF-8')."</code>";
}
function bot_home_row_keyboard($rowNumber){
    $rowNumber = max(1, min(8, (int)$rowNumber));
    $row = [];
    for($c=1; $c<=4; $c++){
        $slot = 'line'.$rowNumber.$c;
        $row[] = ['text'=>'خانه '.$c.': '.bot_home_slot_admin_label($slot), 'callback_data'=>'home_slot-'.$slot];
    }
    return json_encode(['inline_keyboard'=>[
        [$row[0], $row[1]],
        [$row[2], $row[3]],
        [['text'=>'➡️ برگشت به همه ردیف‌ها', 'callback_data'=>'home_layout']],
    ]], JSON_UNESCAPED_UNICODE);
}
function bot_home_slot_picker_keyboard($slot){
    $rows = [];
    $labels = bot_home_button_labels();
    $tokens = bot_home_button_tokens();
    for($i=0; $i<count($tokens); $i+=2){
        $row = [];
        foreach(array_slice($tokens, $i, 2) as $token){
            $label = isset($labels[$token]) ? $labels[$token] : $token;
            if(function_exists('mb_substr')) $short = mb_substr((string)$label, 0, 20, 'UTF-8'); else $short = substr((string)$label, 0, 20);
            $status = bot_home_is_disabled($token) ? '🚫' : '✅';
            $row[] = [ 'text'=>$status.' '.$short, 'callback_data'=>'home_set-'.$token.'_'.$slot ];
        }
        $rows[] = $row;
    }
    $rows[] = [[ 'text'=>'🧹 خالی کردن این خانه', 'callback_data'=>'home_clear-'.$slot ]];
    $rowNum = (preg_match('/^line([1-8])/', $slot, $m)) ? $m[1] : 1;
    $rows[] = [[ 'text'=>'➡️ برگشت به ردیف '.$rowNum, 'callback_data'=>'home_row-'.$rowNum ]];
    return json_encode(['inline_keyboard'=>$rows], JSON_UNESCAPED_UNICODE);
}
function bot_home_toggle_keyboard(){
    $rows = [];
    $labels = bot_home_button_labels();
    $tokens = bot_home_button_tokens();
    for($i=0; $i<count($tokens); $i+=2){
        $row = [];
        foreach(array_slice($tokens, $i, 2) as $token){
            $label = isset($labels[$token]) ? $labels[$token] : $token;
            if(function_exists('mb_substr')) $short = mb_substr((string)$label, 0, 18, 'UTF-8'); else $short = substr((string)$label, 0, 18);
            $status = bot_home_is_disabled($token) ? '🚫' : '✅';
            $row[] = [ 'text'=>$status.' '.$short, 'callback_data'=>'home_toggle-'.$token ];
        }
        $rows[] = $row;
    }
    $rows[] = [[ 'text'=>'✅ فعال‌کردن همه', 'callback_data'=>'home_enable_all' ]];
    $rows[] = [[ 'text'=>'➡️ برگشت به چینش', 'callback_data'=>'home_layout' ]];
    return json_encode(['inline_keyboard'=>$rows], JSON_UNESCAPED_UNICODE);
}

function bot_home_style_status_label($token){
    $label = bot_home_token_label($token);
    if($label === '') $label = $token;
    if(function_exists('mb_substr')) $label = mb_substr((string)$label, 0, 18, 'UTF-8'); else $label = substr((string)$label, 0, 18);
    $style = bot_home_button_style($token);
    $names = bot_home_style_options();
    return $label.' | '.($names[$style] ?? 'پیش‌فرض');
}
function bot_home_style_panel_text(){
    return "🎨 **رنگ دکمه‌های منوی کاربران**\n\n".
           "در تلگرام می‌توان برای دکمه‌های Reply Keyboard و Inline Keyboard یکی از رنگ‌های <code>primary</code>، <code>success</code> یا <code>danger</code> را تنظیم کرد.\n".
           "اگر رنگ را روی پیش‌فرض بگذاری، ظاهر دکمه مثل حالت عادی اپ تلگرام می‌شود.";
}
function bot_home_style_panel_keyboard(){
    $rows = [];
    $tokens = bot_home_button_tokens();
    for($i=0; $i<count($tokens); $i+=2){
        $row = [];
        foreach(array_slice($tokens, $i, 2) as $token){
            $row[] = ['text'=>'🎨 '.bot_home_style_status_label($token), 'callback_data'=>'home_stylepick-'.$token];
        }
        $rows[] = $row;
    }
    $rows[] = [['text'=>'🧹 حذف رنگ همه دکمه‌ها', 'callback_data'=>'home_style_clear_all']];
    $rows[] = [['text'=>'➡️ برگشت به چینش', 'callback_data'=>'home_layout']];
    return json_encode(['inline_keyboard'=>$rows], JSON_UNESCAPED_UNICODE);
}
function bot_home_style_picker_keyboard($token){
    $token = strtoupper(trim((string)$token));
    $current = bot_home_button_style($token);
    $rows = [];
    foreach(bot_home_style_options() as $style=>$title){
        $mark = ($style === $current) ? '✅' : '◻️';
        $cb = $style === '' ? 'default' : $style;
        $rows[] = [['text'=>$mark.' '.$title, 'callback_data'=>'home_styleset-'.$token.'-'.$cb]];
    }
    $rows[] = [['text'=>'➡️ برگشت به رنگ‌ها', 'callback_data'=>'home_style_panel']];
    return json_encode(['inline_keyboard'=>$rows], JSON_UNESCAPED_UNICODE);
}

function bot_home_message_is_disabled($msg){
    $msg = trim((string)$msg);
    if($msg === '') return false;
    foreach(bot_home_disabled_tokens() as $token){
        if(trim(bot_home_token_label($token)) === $msg) return true;
    }
    return false;
}
