<?php
// Channel post inline button settings: labels + Telegram Bot API styles.
// Applies to buttons shown under channel order posts, such as "جمع‌آوری الماس".
// In addition to the official Telegram `style` field, we add a small visible
// color marker to the label so the selected color is still visible on clients
// that do not render inline button styles yet.

if(!function_exists('bot_channel_button_map')){
function bot_channel_button_map(){
    return [
        'DOKC0' => ['title'=>'دکمه عنوان سفارش / تعداد ممبر', 'path'=>'lib/Button/dokc0.txt', 'default'=>'👤 سفارش /ozv/ ممبر 👤'],
        'DOKC1' => ['title'=>'دکمه عضویت در کانال', 'path'=>'lib/Button/dokc1.txt', 'default'=>'👥عضویت👥'],
        'DOKC2' => ['title'=>'دکمه جمع‌آوری / دریافت الماس', 'path'=>'lib/Button/dokc2.txt', 'default'=>'💎 دریافت الماس 💎'],
        'DOKC3' => ['title'=>'دکمه گزارش تخلف', 'path'=>'lib/Button/dokc3.txt', 'default'=>'تخلف🚫'],
        'DOKC4' => ['title'=>'دکمه ورود به ربات', 'path'=>'lib/Button/dokc4.txt', 'default'=>'🔙 ربات'],
    ];
}}

if(!function_exists('bot_channel_button_tokens')){
function bot_channel_button_tokens(){ return array_keys(bot_channel_button_map()); }
}

if(!function_exists('bot_channel_button_style_options')){
function bot_channel_button_style_options(){
    return [
        '' => 'پیش‌فرض',
        'primary' => 'آبی / Primary',
        'success' => 'سبز / Success',
        'danger' => 'قرمز / Danger',
    ];
}}

if(!function_exists('bot_channel_button_normalize_style')){
function bot_channel_button_normalize_style($style){
    $style = strtolower(trim((string)$style));
    return in_array($style, ['primary','success','danger'], true) ? $style : '';
}}

if(!function_exists('bot_channel_button_styles_file')){
function bot_channel_button_styles_file(){ return 'lib/keyboard/channel/styles.json'; }
}

if(!function_exists('bot_channel_button_styles')){
function bot_channel_button_styles(){
    $file = bot_channel_button_styles_file();
    $data = function_exists('bot_data_get_json') ? bot_data_get_json($file, []) : (is_file($file) ? json_decode((string)@file_get_contents($file), true) : []);
    if(!is_array($data)) $data = [];
    $out = [];
    $valid = bot_channel_button_tokens();
    foreach($data as $token=>$style){
        $token = strtoupper(trim((string)$token));
        if(!in_array($token, $valid, true)) continue;
        $style = bot_channel_button_normalize_style($style);
        if($style !== '') $out[$token] = $style;
    }
    return $out;
}}

if(!function_exists('bot_channel_button_save_styles')){
function bot_channel_button_save_styles($styles){
    $out = [];
    $valid = bot_channel_button_tokens();
    foreach((array)$styles as $token=>$style){
        $token = strtoupper(trim((string)$token));
        if(!in_array($token, $valid, true)) continue;
        $style = bot_channel_button_normalize_style($style);
        if($style !== '') $out[$token] = $style;
    }
    if(function_exists('saveJson')) saveJson(bot_channel_button_styles_file(), $out);
    elseif(function_exists('bot_data_put_json')) bot_data_put_json(bot_channel_button_styles_file(), $out);
    else {
        $dir = dirname(bot_channel_button_styles_file());
        if($dir && !is_dir($dir)) @mkdir($dir, 0775, true);
        @file_put_contents(bot_channel_button_styles_file(), json_encode($out, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT), LOCK_EX);
    }
    return $out;
}}

if(!function_exists('bot_channel_button_style')){
function bot_channel_button_style($token){
    $token = strtoupper(trim((string)$token));
    $styles = bot_channel_button_styles();
    return isset($styles[$token]) ? bot_channel_button_normalize_style($styles[$token]) : '';
}}

if(!function_exists('bot_channel_button_label')){
function bot_channel_button_label($token){
    $token = strtoupper(trim((string)$token));
    $map = bot_channel_button_map();
    if(!isset($map[$token])) return $token;
    $path = $map[$token]['path'];
    $default = $map[$token]['default'];
    if(function_exists('bot_data_get_text')) return trim((string)bot_data_get_text($path, $default));
    return is_file($path) ? trim((string)@file_get_contents($path)) : $default;
}}

if(!function_exists('bot_channel_button_save_label')){
function bot_channel_button_save_label($token, $label){
    $token = strtoupper(trim((string)$token));
    $map = bot_channel_button_map();
    if(!isset($map[$token])) return false;
    $label = trim((string)$label);
    if($label === '') $label = $map[$token]['default'];
    if(function_exists('Save')) { Save($map[$token]['path'], $label); return true; }
    if(function_exists('bot_data_put_text')) return bot_data_put_text($map[$token]['path'], $label);
    $dir = dirname($map[$token]['path']);
    if($dir && !is_dir($dir)) @mkdir($dir, 0775, true);
    return @file_put_contents($map[$token]['path'], $label, LOCK_EX) !== false;
}}

if(!function_exists('bot_channel_button_style_marker')){
function bot_channel_button_style_marker($style){
    $style = bot_channel_button_normalize_style($style);
    if($style === 'primary') return '🔵';
    if($style === 'success') return '🟢';
    if($style === 'danger') return '🔴';
    return '';
}}

if(!function_exists('bot_channel_button_strip_style_markers')){
function bot_channel_button_strip_style_markers($text){
    $text = trim((string)$text);
    // Remove only the marker we add at render time, without touching the saved label.
    return trim(preg_replace('/^(🔵|🟢|🔴)\s*/u', '', $text));
}}

if(!function_exists('bot_channel_button_apply_style')){
function bot_channel_button_apply_style($token, array $button){
    $style = bot_channel_button_style($token);
    if($style !== ''){
        // Official Telegram Bot API field for inline/reply button color.
        $button['style'] = $style;

        // Visible fallback: some Telegram clients/accounts may not render `style`
        // immediately for channel inline buttons. The marker guarantees the admin
        // can see the selected color on new channel posts.
        $marker = bot_channel_button_style_marker($style);
        if($marker !== '' && isset($button['text'])){
            $text = bot_channel_button_strip_style_markers($button['text']);
            $button['text'] = $marker . ' ' . $text;
        }
    }
    return $button;
}}


if(!function_exists('bot_channel_button_layout_file')){
function bot_channel_button_layout_file(){ return 'lib/keyboard/channel/layout.json'; }
}

if(!function_exists('bot_channel_button_default_rows')){
function bot_channel_button_default_rows($legacyLayout = 2){
    $legacyLayout = (int)$legacyLayout;
    if($legacyLayout === 1){
        return [['DOKC0'], ['DOKC1'], ['DOKC2'], ['DOKC3'], ['DOKC4']];
    }
    return [['DOKC0'], ['DOKC1'], ['DOKC2','DOKC3'], ['DOKC4']];
}
}

if(!function_exists('bot_channel_button_normalize_rows')){
function bot_channel_button_normalize_rows($rows, $fallbackRows = null){
    $valid = bot_channel_button_tokens();
    $seen = [];
    $out = [];
    foreach((array)$rows as $row){
        $cleanRow = [];
        foreach((array)$row as $token){
            $token = strtoupper(trim((string)$token));
            if(!in_array($token, $valid, true)) continue;
            if(isset($seen[$token])) continue;
            $seen[$token] = true;
            $cleanRow[] = $token;
        }
        if($cleanRow) $out[] = $cleanRow;
    }
    $fallbackRows = $fallbackRows ?: bot_channel_button_default_rows(2);
    foreach($fallbackRows as $row){
        foreach((array)$row as $token){
            $token = strtoupper(trim((string)$token));
            if(!in_array($token, $valid, true) || isset($seen[$token])) continue;
            $seen[$token] = true;
            $out[] = [$token];
        }
    }
    return $out ?: bot_channel_button_default_rows(2);
}
}

if(!function_exists('bot_channel_button_layout')){
function bot_channel_button_layout($legacyLayout = 2){
    $file = bot_channel_button_layout_file();
    $data = function_exists('bot_data_get_json') ? bot_data_get_json($file, []) : (is_file($file) ? json_decode((string)@file_get_contents($file), true) : []);
    $fallback = bot_channel_button_default_rows($legacyLayout);
    if(!is_array($data) || empty($data['rows']) || !is_array($data['rows'])) return $fallback;
    return bot_channel_button_normalize_rows($data['rows'], $fallback);
}
}

if(!function_exists('bot_channel_button_save_layout')){
function bot_channel_button_save_layout($rows){
    $rows = bot_channel_button_normalize_rows($rows, bot_channel_button_default_rows(2));
    $data = ['rows'=>$rows, 'updated_at'=>time()];
    if(function_exists('saveJson')) saveJson(bot_channel_button_layout_file(), $data);
    elseif(function_exists('bot_data_put_json')) bot_data_put_json(bot_channel_button_layout_file(), $data);
    else {
        $path = bot_channel_button_layout_file();
        $dir = dirname($path);
        if($dir && !is_dir($dir)) @mkdir($dir, 0775, true);
        @file_put_contents($path, json_encode($data, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT), LOCK_EX);
    }
    return $rows;
}
}

if(!function_exists('bot_channel_button_build_rows')){
function bot_channel_button_build_rows(array $buttonByToken, $legacyLayout = 2){
    $tokenRows = bot_channel_button_layout($legacyLayout);
    $rows = [];
    foreach($tokenRows as $tokenRow){
        $row = [];
        foreach((array)$tokenRow as $token){
            $token = strtoupper(trim((string)$token));
            if(isset($buttonByToken[$token])) $row[] = $buttonByToken[$token];
        }
        if($row) $rows[] = $row;
    }
    return $rows;
}
}
