<?php
// Telegram bot webhook entrypoint - modular safe runtime
flush();
ob_start();
ob_implicit_flush(1);

$rootDir = __DIR__;
if (!defined('BOT_ROOT_DIR')) define('BOT_ROOT_DIR', $rootDir);

// Runtime safety: log fatal errors instead of silently killing the webhook.
ini_set('log_errors', '1');
register_shutdown_function(function() use ($rootDir) {
    $e = error_get_last();
    if (!$e) return;
    $fatalTypes = [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR];
    if (!in_array($e['type'], $fatalTypes, true)) return;
    $dir = $rootDir . '/cache';
    if (!is_dir($dir)) @mkdir($dir, 0755, true);
    $line = date('Y-m-d H:i:s') . ' | ' . ($e['message'] ?? '') . ' | ' . ($e['file'] ?? '') . ':' . ($e['line'] ?? '') . "\n";
    @file_put_contents($dir . '/modular_fatal.log', $line, FILE_APPEND);
    error_log('BOT MODULAR FATAL: ' . trim($line));
});

if (!is_file($rootDir . '/config.php')) {
    $hint = 'config.php not found. install.php را اجرا کن؛ نیازی به تغییر نام config.sample.php نیست.';
    if (!is_file($rootDir . '/install.php')) {
        $hint .= ' اگر install.php را حذف کرده‌ای، config.sample.php را به config.php تبدیل کن و مقادیر توکن و ادمین را داخل آن بگذار.';
    }
    error_log('BOT FATAL: ' . $hint);
    http_response_code(500);
    exit($hint);
}
include $rootDir . '/config.php';

if (is_file($rootDir . '/config_db.php')) { include_once $rootDir . '/config_db.php'; }
if (is_file($rootDir . '/lib/db_storage.php')) { include_once $rootDir . '/lib/db_storage.php'; }

date_default_timezone_set('Asia/Tehran');
if (!defined('TELEGRAM_API_BASE')) define('TELEGRAM_API_BASE', 'https://api.telegram.org/bot');
if (!defined('BOT_TELEGRAM_CONNECT_TIMEOUT')) define('BOT_TELEGRAM_CONNECT_TIMEOUT', 8);
if (!defined('BOT_TELEGRAM_TIMEOUT')) define('BOT_TELEGRAM_TIMEOUT', 18);
if (!defined('BOT_PHP8_VERSION')) define('BOT_PHP8_VERSION', 'PHP8-Modular-2.2.3-safe');

$optionalBootFiles = [
    '/app/Bootstrap.php',
    '/app/Services/ScaleOptimizerService.php',
    '/lib/button_defaults.php',
    '/lib/class.php',
    '/lib/jdf.php',
    '/lib/broadcast_queue.php',
    '/app/Services/HomeKeyboardService.php',
    '/app/Services/ChannelButtonService.php',
    '/app/Services/JoinGiftService.php',
    '/app/Services/RewardSettingsService.php',
    '/app/Services/TextSettingsService.php',
    '/app/Support/TextFormatting.php',
    '/app/Services/JsonCacheService.php',
    '/app/Services/ZibalShopService.php',
    '/app/Services/ViolationReportService.php',
    '/app/Services/AntiSpamService.php',
    '/app/Services/FraudGuardService.php',
    '/app/Services/ReferralService.php',
    '/app/Services/UserAccountService.php',
    '/app/Services/GiftCodeService.php',
    '/app/Services/DailyRewardService.php',
    '/app/Services/StateService.php',
    '/app/Services/CannedReplyService.php',
    '/app/Services/AdminToolsService.php',
    '/app/Services/SettingsBackupService.php',
    '/app/Services/AdminStatsService.php',
    '/app/Services/AdvancedToolsService.php',
    '/app/Services/TicketMiniAppService.php',
    '/app/Services/OrderCancellationService.php',
    '/app/Services/PaymentReportService.php',
    '/app/Services/AccountingService.php',
    '/app/Services/ReactionService.php',
    '/app/Services/SimpleShopService.php',
    '/app/Services/SponsorService.php',
];

foreach ($optionalBootFiles as $file) {
    $path = $rootDir . $file;
    if (is_file($path)) {
        include_once $path;
    }
}

if (function_exists('bot_scale_bootstrap')) {
    bot_scale_bootstrap();
}

// Minimal fallbacks so missing optional helper files do not kill the webhook.
if (!function_exists('bot_data_get_json')) {
    function bot_data_get_json($path, $default = []) {
        if (!is_file($path)) return $default;
        $json = json_decode((string)file_get_contents($path), true);
        return is_array($json) ? $json : $default;
    }
}
if (!function_exists('bot_data_file_exists')) {
    function bot_data_file_exists($path) { return is_file($path); }
}
$time45 = time();

// Config-safe defaults
if (!isset($admin)) $admin = '';
if (function_exists('bot_sync_master_admins_to_list')) { bot_sync_master_admins_to_list(); }
$botMasterAdminIds = function_exists('bot_config_master_admin_ids') ? bot_config_master_admin_ids() : array_values(array_filter([(string)$admin]));
$list = bot_data_get_json('lib/kodam/list.json', []);
if (!is_array($list)) $list = [];
if (!isset($list['admins']) || !is_array($list['admins'])) $list['admins'] = $botMasterAdminIds;
if (!isset($list['ban']) || !is_array($list['ban'])) $list['ban'] = [];

$data_ads = bot_data_get_json('lib/kodam/data-ads.json', []);
$transfer = bot_data_get_json('lib/kodam/data-transfer.json', []);
$data_Cancellads = bot_data_get_json('lib/kodam/data-Cancellads.json', []);
$databot = bot_data_get_json('lib/kodam/data-power.json', []);
$datazir = bot_data_get_json('lib/kodam/data-zirmjmae.json', []);
$data_left = bot_data_get_json('lib/kodam/data-left.json', []);

$botModules = [
    $rootDir . '/app/Legacy/CoreApi.php',
    $rootDir . '/app/Legacy/MenuShopOrderHelpers.php',
    $rootDir . '/app/Legacy/ChannelHelpers.php',
    $rootDir . '/app/Legacy/OrderTrackingHelpers.php',
    $rootDir . '/app/Legacy/LeftPenaltyHelpers.php',
    $rootDir . '/app/Legacy/AdminTopHelpers.php',
    $rootDir . '/app/Runtime/WebhookRuntime.php',
];

foreach ($botModules as $botModuleFile) {
    if (!is_file($botModuleFile)) {
        error_log('BOT FATAL: Missing bot module: ' . $botModuleFile);
        http_response_code(500);
        exit('Missing bot module: ' . basename($botModuleFile));
    }
    require_once $botModuleFile;
}
