<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
header('Content-Type: application/json; charset=utf-8');
$root = __DIR__;
require_once $root . '/config.php';
if(file_exists($root . '/config_db.php')) require_once $root . '/config_db.php';
if(file_exists($root . '/lib/db_storage.php')) require_once $root . '/lib/db_storage.php';
if(file_exists($root . '/lib/button_defaults.php')) require_once $root . '/lib/button_defaults.php';
if(file_exists($root . '/app/Services/HomeKeyboardService.php')) require_once $root . '/app/Services/HomeKeyboardService.php';

function cleanup_save_text($path, $value){
    if(function_exists('Save')) { Save($path, $value); return; }
    $file = __DIR__ . '/' . ltrim($path, '/');
    if(!is_dir(dirname($file))) @mkdir(dirname($file), 0755, true);
    file_put_contents($file, $value);
}
function cleanup_get_text($path){
    if(function_exists('bot_data_get_text')) return bot_data_get_text($path, '');
    $file = __DIR__ . '/' . ltrim($path, '/');
    return is_file($file) ? trim((string)file_get_contents($file)) : '';
}
$changed = [];
$disabled = ['DOK5','DOK7','DOK8'];
if(function_exists('bot_home_save_disabled_tokens')){
    $old = function_exists('bot_home_disabled_tokens') ? bot_home_disabled_tokens() : [];
    bot_home_save_disabled_tokens(array_values(array_unique(array_merge((array)$old, $disabled))));
    $changed[] = 'disabled_tokens';
}
// Remove transfer, panels and top users from physical layout slots too.
for($r=1; $r<=8; $r++){
    for($c=1; $c<=4; $c++){
        $path = "lib/keyboard/home/line{$r}{$c}.txt";
        $v = strtoupper(trim(cleanup_get_text($path)));
        if(in_array($v, $disabled, true)){
            cleanup_save_text($path, '');
            $changed[] = $path;
        }
    }
}
// Rename referral button if legacy label remains.
cleanup_save_text('lib/Button/dok4.txt', '👥 رفرال‌گیری');
$changed[] = 'lib/Button/dok4.txt';
// Hard-disable transfer settings file if present.
if(function_exists('saveJson')){
    saveJson('lib/kodam/data-transfer.json', ['Condition'=>'❌غیر فعال','Report'=>'❌غیر فعال','mintrnfr'=>'0','maxtrnfr'=>'0']);
    $changed[] = 'lib/kodam/data-transfer.json';
}
if(function_exists('bot_cache_clear_heavy')) bot_cache_clear_heavy();

echo json_encode(['ok'=>true,'message'=>'old transfer/top/admin-help buttons cleaned','changed'=>$changed], JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);
