<?php
// Fast violation-report moderation for member-order ads.
// Stores report counters in indexed SQL tables and keeps a JSON fallback for hosts without SQL.

if(!function_exists('bot_violation_default_settings')){
    function bot_violation_default_settings(){
        return [
            'enabled' => '✅فعال',
            'threshold' => 10,
            'admin_direct_delete' => '✅فعال',
            'notify_admin' => '✅فعال',
        ];
    }
}

if(!function_exists('bot_violation_install_schema')){
    function bot_violation_install_schema(){
        if(!function_exists('bot_sql_pdo')) return false;
        $pdo = bot_sql_pdo();
        if(!$pdo) return false;
        static $done = false;
        if($done) return true;
        try{
            $pdo->exec("CREATE TABLE IF NOT EXISTS bot_order_reports (
                id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
                order_id VARCHAR(64) NOT NULL,
                reporter_id VARCHAR(32) NOT NULL,
                report_source VARCHAR(30) NOT NULL DEFAULT 'user',
                status VARCHAR(30) NOT NULL DEFAULT 'open',
                created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
                UNIQUE KEY uniq_order_reporter (order_id, reporter_id),
                KEY idx_order_status (order_id, status),
                KEY idx_reporter (reporter_id),
                KEY idx_created (created_at)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
            $pdo->exec("CREATE TABLE IF NOT EXISTS bot_order_moderation_actions (
                id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
                order_id VARCHAR(64) NOT NULL,
                actor_id VARCHAR(32) NULL,
                action_type VARCHAR(40) NOT NULL,
                reason VARCHAR(191) NULL,
                report_count INT NOT NULL DEFAULT 0,
                data_json LONGTEXT NULL,
                created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
                KEY idx_order_action (order_id, action_type),
                KEY idx_actor (actor_id),
                KEY idx_created (created_at)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
            if(function_exists('bot_sql_put_setting')){
                $st = $pdo->prepare('SELECT 1 FROM bot_settings WHERE setting_key=? LIMIT 1');
                $st->execute(['violation_report_settings']);
                if(!$st->fetchColumn()) bot_sql_put_setting('violation_report_settings', json_encode(bot_violation_default_settings(), JSON_UNESCAPED_UNICODE), 'json');
            }
            $done = true;
            return true;
        }catch(Throwable $e){
            error_log('BOT violation schema failed: '.$e->getMessage());
            return false;
        }
    }
}

if(!function_exists('bot_violation_get_settings')){
    function bot_violation_get_settings(){
        $defaults = bot_violation_default_settings();
        bot_violation_install_schema();
        if(function_exists('bot_sql_pdo')){
            $pdo = bot_sql_pdo();
            if($pdo){
                try{
                    $st = $pdo->prepare('SELECT storage_value FROM bot_settings WHERE setting_key=? LIMIT 1');
                    $st->execute(['violation_report_settings']);
                    $raw = $st->fetchColumn();
                    $data = json_decode((string)$raw, true);
                    if(is_array($data)) return array_merge($defaults, $data);
                }catch(Throwable $e){ error_log('BOT violation settings read failed: '.$e->getMessage()); }
            }
        }
        if(function_exists('bot_data_get_json')){
            $data = bot_data_get_json('lib/kodam/data-violation.json', $defaults);
            return is_array($data) ? array_merge($defaults, $data) : $defaults;
        }
        return $defaults;
    }
}

if(!function_exists('bot_violation_save_settings')){
    function bot_violation_save_settings(array $settings){
        $settings = array_merge(bot_violation_default_settings(), $settings);
        $settings['threshold'] = max(1, (int)($settings['threshold'] ?? 10));
        bot_violation_install_schema();
        if(function_exists('bot_sql_pdo')){
            $pdo = bot_sql_pdo();
            if($pdo && function_exists('bot_sql_put_setting')){
                try{ bot_sql_put_setting('violation_report_settings', json_encode($settings, JSON_UNESCAPED_UNICODE), 'json'); }
                catch(Throwable $e){ error_log('BOT violation settings write failed: '.$e->getMessage()); }
            }
        }
        if(function_exists('bot_data_put_json')) bot_data_put_json('lib/kodam/data-violation.json', $settings);
        else @file_put_contents('lib/kodam/data-violation.json', json_encode($settings, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
        return $settings;
    }
}

if(!function_exists('bot_violation_toggle_text')){
    function bot_violation_toggle_text($value){
        return ((string)$value === '✅فعال') ? '❌غیر فعال' : '✅فعال';
    }
}

if(!function_exists('bot_violation_clean_order_id')){
    function bot_violation_clean_order_id($raw){
        $raw = preg_replace('/[^A-Za-z0-9_\-]/', '', (string)$raw);
        if($raw !== '' && function_exists('bale_resolve_order_id_from_callback')){
            $raw = bale_resolve_order_id_from_callback($raw);
            $raw = preg_replace('/[^A-Za-z0-9_\-]/', '', (string)$raw);
        }
        return $raw;
    }
}


if(!function_exists('bot_violation_migrate_order_reports')){
    function bot_violation_migrate_order_reports($orderId, $order = null){
        if(!function_exists('bot_sql_pdo')) return;
        $pdo = bot_sql_pdo();
        if(!$pdo) return;
        if(!is_array($order) && function_exists('bot_data_get_json')) $order = bot_data_get_json("ads/$orderId.json", []);
        $reports = is_array($order['Report'] ?? null) ? $order['Report'] : [];
        if(!$reports) return;
        try{
            $st = $pdo->prepare("INSERT IGNORE INTO bot_order_reports (order_id, reporter_id, report_source, status) VALUES (?,?,'legacy','open')");
            foreach($reports as $r){
                $r = (string)$r;
                if($r === '' || $r === '0') continue;
                $st->execute([(string)$orderId, $r]);
            }
        }catch(Throwable $e){ error_log('BOT violation legacy report migration failed: '.$e->getMessage()); }
    }
}

if(!function_exists('bot_violation_report_count')){
    function bot_violation_report_count($orderId, $order = null){
        $orderId = bot_violation_clean_order_id($orderId);
        bot_violation_install_schema();
        if(function_exists('bot_sql_pdo')){
            $pdo = bot_sql_pdo();
            if($pdo){
                if($order !== null) bot_violation_migrate_order_reports($orderId, $order);
                try{
                    $st = $pdo->prepare("SELECT COUNT(*) FROM bot_order_reports WHERE order_id=? AND status='open'");
                    $st->execute([$orderId]);
                    return (int)$st->fetchColumn();
                }catch(Throwable $e){ error_log('BOT violation count failed: '.$e->getMessage()); }
            }
        }
        if(!is_array($order) && function_exists('bot_data_get_json')) $order = bot_data_get_json("ads/$orderId.json", []);
        $reports = is_array($order['Report'] ?? null) ? $order['Report'] : [];
        $clean = [];
        foreach($reports as $r){ $r = (string)$r; if($r !== '' && $r !== '0') $clean[$r] = true; }
        return count($clean);
    }
}

if(!function_exists('bot_violation_order_is_closed')){
    function bot_violation_order_is_closed(array $order){
        $status = (string)($order['stats'] ?? $order['status'] ?? '');
        return (mb_strpos($status, 'حذف', 0, 'UTF-8') !== false)
            || (mb_strpos($status, 'تکمیل', 0, 'UTF-8') !== false)
            || (mb_strpos($status, 'لغو', 0, 'UTF-8') !== false)
            || (mb_strpos($status, 'کنسل', 0, 'UTF-8') !== false)
            || (mb_strpos($status, 'پایان', 0, 'UTF-8') !== false);
    }
}

if(!function_exists('bot_violation_channel_chat_id')){
    function bot_violation_channel_chat_id($chads){
        $chads = trim((string)$chads);
        if($chads === '') return '';
        if(preg_match('/^-?\d+$/', $chads)) return $chads;
        if($chads[0] === '@') return $chads;
        return '@'.$chads;
    }
}



if(!function_exists('bot_violation_order_chat_id')){
    function bot_violation_order_chat_id(array $order, $fallbackChads = ''){
        $chat = trim((string)($order['post_chat_id'] ?? ''));
        if($chat !== '') return $chat;
        return bot_violation_channel_chat_id($fallbackChads);
    }
}

if(!function_exists('bot_violation_order_message_id')){
    function bot_violation_order_message_id(array $order){
        $mid = trim((string)($order['post_message_id'] ?? ''));
        if($mid !== '') return $mid;
        return trim((string)($order['postid'] ?? ''));
    }
}

if(!function_exists('bot_violation_public_post_url')){
    function bot_violation_public_post_url(array $order, $fallbackChads = ''){
        $chat = bot_violation_order_chat_id($order, $fallbackChads);
        $mid = bot_violation_order_message_id($order);
        if($chat === '' || $mid === '') return '';
        if($chat[0] === '@') return 'https://t.me/'.ltrim($chat, '@').'/'.$mid;
        if(preg_match('/^-100(\d+)$/', $chat, $m)) return 'https://t.me/c/'.$m[1].'/'.$mid;
        return '';
    }
}

if(!function_exists('bot_violation_order_summary_text')){
    function bot_violation_order_summary_text($orderId, array $order){
        $owner = (string)($order['admin'] ?? $order['owner_id'] ?? 'نامشخص');
        $member = (string)($order['member'] ?? 'نامشخص');
        $channel = (string)($order['channel'] ?? 'نامشخص');
        $date = (string)($order['date'] ?? 'نامشخص');
        $status = (string)($order['stats'] ?? 'نامشخص');
        $postId = bot_violation_order_message_id($order);
        $count = bot_violation_report_count($orderId, $order);
        return "👁 **آگهی گزارش‌شده / مشکوک**\n\n".
            "کد سفارش: **$orderId**\n".
            "آیدی سفارش‌دهنده: **$owner**\n".
            "کانال سفارش: **$channel**\n".
            "ممبر درخواستی: **$member**\n".
            "تاریخ ثبت: **$date**\n".
            "وضعیت سفارش: **$status**\n".
            "شناسه پست کانال: **$postId**\n".
            "تعداد گزارش‌ها: **$count**";
    }
}

if(!function_exists('bot_violation_view_keyboard')){
    function bot_violation_view_keyboard($orderId, array $order = [], $fallbackChads = ''){
        $rows = [];
        $rows[] = [[ 'text'=>'👁 مشاهده آگهی تقلب‌کننده', 'callback_data'=>'vshow-'.$orderId ]];
        if(is_array($order) && $order){
            $url = bot_violation_public_post_url($order, $fallbackChads);
            if($url !== '') $rows[] = [[ 'text'=>'🔗 باز کردن پست در کانال', 'url'=>$url ]];
        }
        $rows[] = [[ 'text'=>'🗑 حذف تبلیغ', 'callback_data'=>'vdel-'.$orderId ]];
        return json_encode(['inline_keyboard'=>$rows], JSON_UNESCAPED_UNICODE);
    }
}

if(!function_exists('bot_violation_show_reported_ad')){
    function bot_violation_show_reported_ad($orderId, $adminChatId, $callbackId = null){
        global $chads;
        $orderId = bot_violation_clean_order_id($orderId);
        if($orderId === '' || !function_exists('bot_data_file_exists') || !bot_data_file_exists("ads/$orderId.json")){
            if($callbackId) bot('answercallbackquery', ['callback_query_id'=>$callbackId, 'text'=>'سفارش پیدا نشد.', 'show_alert'=>true]);
            return false;
        }
        $order = bot_data_get_json("ads/$orderId.json", []);
        if(!is_array($order) || !$order){
            if($callbackId) bot('answercallbackquery', ['callback_query_id'=>$callbackId, 'text'=>'اطلاعات سفارش قابل خواندن نیست.', 'show_alert'=>true]);
            return false;
        }
        $chat = bot_violation_order_chat_id($order, $chads ?? '');
        $mid = bot_violation_order_message_id($order);
        if($callbackId) bot('answercallbackquery', ['callback_query_id'=>$callbackId, 'text'=>'در حال ارسال آگهی گزارش‌شده...', 'show_alert'=>false]);
        $sent = false;
        if($chat !== '' && $mid !== ''){
            $res = bot('forwardMessage', ['chat_id'=>$adminChatId, 'from_chat_id'=>$chat, 'message_id'=>$mid]);
            $sent = isset($res->ok) && $res->ok;
            if(!$sent){
                $res = bot('copyMessage', ['chat_id'=>$adminChatId, 'from_chat_id'=>$chat, 'message_id'=>$mid]);
                $sent = isset($res->ok) && $res->ok;
            }
        }
        $summary = bot_violation_order_summary_text($orderId, $order);
        if(!$sent){
            $summary .= "\n\n⚠️ ارسال/کپی خود پست ممکن نشد. احتمالاً پست حذف شده یا ربات دسترسی لازم به کانال را ندارد.";
        }
        bot('sendMessage', [
            'chat_id'=>$adminChatId,
            'text'=>$summary,
            'parse_mode'=>'MarkDown',
            'reply_markup'=>bot_violation_view_keyboard($orderId, $order, $chads ?? '')
        ]);
        return true;
    }
}

if(!function_exists('bot_violation_log_action')){
    function bot_violation_log_action($orderId, $actorId, $actionType, $reason, $reportCount, array $extra = []){
        bot_violation_install_schema();
        if(function_exists('bot_sql_pdo')){
            $pdo = bot_sql_pdo();
            if($pdo){
                try{
                    $st = $pdo->prepare('INSERT INTO bot_order_moderation_actions (order_id, actor_id, action_type, reason, report_count, data_json) VALUES (?,?,?,?,?,?)');
                    $st->execute([(string)$orderId, (string)$actorId, (string)$actionType, (string)$reason, (int)$reportCount, json_encode($extra, JSON_UNESCAPED_UNICODE)]);
                }catch(Throwable $e){ error_log('BOT violation action log failed: '.$e->getMessage()); }
            }
        }
    }
}

if(!function_exists('bot_violation_add_report')){
    function bot_violation_add_report($orderId, $reporterId){
        $orderId = bot_violation_clean_order_id($orderId);
        $reporterId = (string)$reporterId;
        if($orderId === '' || $reporterId === '') return ['ok'=>false, 'error'=>'bad_input'];
        if(!function_exists('bot_data_file_exists') || !bot_data_file_exists("ads/$orderId.json")) return ['ok'=>false, 'error'=>'order_not_found'];
        $order = bot_data_get_json("ads/$orderId.json", []);
        if(!is_array($order) || !$order) return ['ok'=>false, 'error'=>'order_not_found'];
        if(bot_violation_order_is_closed($order)) return ['ok'=>false, 'error'=>'order_closed', 'count'=>bot_violation_report_count($orderId, $order), 'order'=>$order];

        bot_violation_install_schema();
        $inserted = false;
        if(function_exists('bot_sql_pdo')){
            $pdo = bot_sql_pdo();
            if($pdo){
                try{
                    $st = $pdo->prepare("INSERT IGNORE INTO bot_order_reports (order_id, reporter_id, report_source, status) VALUES (?,?,'user','open')");
                    $st->execute([$orderId, $reporterId]);
                    $inserted = $st->rowCount() > 0;
                }catch(Throwable $e){ error_log('BOT violation report insert failed: '.$e->getMessage()); }
            }
        }
        if(!function_exists('bot_sql_pdo') || !bot_sql_pdo()){
            if(!isset($order['Report']) || !is_array($order['Report'])) $order['Report'] = [];
            $clean = array_map('strval', $order['Report']);
            if(in_array($reporterId, $clean, true)) return ['ok'=>false, 'error'=>'duplicate', 'count'=>bot_violation_report_count($orderId, $order), 'order'=>$order];
            $order['Report'][] = $reporterId;
            bot_data_put_json("ads/$orderId.json", $order);
            $inserted = true;
        }
        if(!$inserted) return ['ok'=>false, 'error'=>'duplicate', 'count'=>bot_violation_report_count($orderId, $order), 'order'=>$order];

        $count = bot_violation_report_count($orderId, $order);
        $order['violation_report_count'] = $count;
        $order['violation_last_reporter'] = $reporterId;
        $order['violation_last_report_at'] = time();
        bot_data_put_json("ads/$orderId.json", $order);
        return ['ok'=>true, 'count'=>$count, 'order'=>$order];
    }
}

if(!function_exists('bot_violation_delete_order')){
    function bot_violation_delete_order($orderId, $actorId, $reason = 'admin_direct'){
        global $admin, $chads;
        $orderId = bot_violation_clean_order_id($orderId);
        if($orderId === '' || !function_exists('bot_data_file_exists') || !bot_data_file_exists("ads/$orderId.json")) return ['ok'=>false, 'error'=>'order_not_found'];
        $order = bot_data_get_json("ads/$orderId.json", []);
        if(!is_array($order) || !$order) return ['ok'=>false, 'error'=>'order_not_found'];
        $count = bot_violation_report_count($orderId, $order);
        if(bot_violation_order_is_closed($order)) return ['ok'=>true, 'already'=>true, 'count'=>$count, 'order'=>$order];

        $chat = bot_violation_channel_chat_id($chads);
        $deleteOk = null;
        if($chat !== '' && !empty($order['postid'])){
            $res = bot('deletemessage', ['chat_id'=>$chat, 'message_id'=>(string)$order['postid']]);
            $deleteOk = (isset($res->ok) && $res->ok) ? true : false;
        }

        $label = ($reason === 'auto_report_threshold') ? 'حذف خودکار به دلیل گزارش تخلف 🚫' : 'حذف شده توسط ادمین 🚫';
        $order['stats'] = $label;
        $order['violation_deleted'] = true;
        $order['violation_deleted_at'] = time();
        $order['violation_deleted_by'] = (string)$actorId;
        $order['violation_delete_reason'] = $reason;
        $order['violation_report_count'] = $count;
        $order['violation_channel_delete_ok'] = $deleteOk;
        bot_data_put_json("ads/$orderId.json", $order);

        bot_violation_install_schema();
        if(function_exists('bot_sql_pdo')){
            $pdo = bot_sql_pdo();
            if($pdo){
                try{
                    $st = $pdo->prepare("UPDATE bot_order_reports SET status='closed' WHERE order_id=?");
                    $st->execute([$orderId]);
                }catch(Throwable $e){ error_log('BOT violation close reports failed: '.$e->getMessage()); }
            }
        }
        bot_violation_log_action($orderId, $actorId, ($reason === 'auto_report_threshold' ? 'auto_delete' : 'admin_delete'), $reason, $count, ['channel_delete_ok'=>$deleteOk]);

        $owner = (string)($order['admin'] ?? '');
        if($owner !== ''){
            $ownerText = ($reason === 'auto_report_threshold')
                ? "🚫 تبلیغ شما به دلیل رسیدن تعداد گزارش تخلف به حد مجاز حذف شد.\n\nکد سفارش: **$orderId**\nتعداد گزارش: **$count**"
                : "🚫 تبلیغ شما توسط ادمین حذف شد.\n\nکد سفارش: **$orderId**";
            bot('sendMessage', ['chat_id'=>$owner, 'text'=>$ownerText, 'parse_mode'=>'MarkDown']);
        }
        if(!empty($admin)){
            $adminText = "✅ تبلیغ حذف شد.\n\nکد سفارش: **$orderId**\nتعداد گزارش: **$count**\nوضعیت حذف از کانال: ".($deleteOk === false ? 'ناموفق یا قبلاً حذف شده' : 'انجام شد');
            bot('sendMessage', ['chat_id'=>$admin, 'text'=>$adminText, 'parse_mode'=>'MarkDown']);
        }
        return ['ok'=>true, 'count'=>$count, 'order'=>$order, 'channel_delete_ok'=>$deleteOk];
    }
}

if(!function_exists('bot_violation_settings_keyboard')){
    function bot_violation_settings_keyboard(array $settings = null){
        if($settings === null) $settings = bot_violation_get_settings();
        return json_encode(['inline_keyboard'=>[
            [['text'=>(string)$settings['enabled'], 'callback_data'=>'vset_toggle_enabled'], ['text'=>'وضعیت گزارش تخلف', 'callback_data'=>'0']],
            [['text'=>(string)((int)$settings['threshold']).' گزارش', 'callback_data'=>'vset_threshold'], ['text'=>'حد حذف خودکار', 'callback_data'=>'0']],
            [['text'=>(string)$settings['admin_direct_delete'], 'callback_data'=>'vset_toggle_direct'], ['text'=>'حذف مستقیم ادمین', 'callback_data'=>'0']],
            [['text'=>(string)$settings['notify_admin'], 'callback_data'=>'vset_toggle_notify'], ['text'=>'اعلان گزارش به ادمین', 'callback_data'=>'0']],
        ]], JSON_UNESCAPED_UNICODE);
    }
}

if(!function_exists('bot_violation_show_settings')){
    function bot_violation_show_settings($chatID, $messageId = null){
        $settings = bot_violation_get_settings();
        $text = "🚫 **تنظیمات تخلف تبلیغات**\n\nبا این بخش می‌توانید تعیین کنید چند گزارش باعث حذف خودکار تبلیغ شود.\n\nحد فعلی حذف خودکار: **".(int)$settings['threshold']." گزارش**\nوضعیت گزارش تخلف: **{$settings['enabled']}**\nحذف مستقیم توسط ادمین: **{$settings['admin_direct_delete']}**";
        $payload = ['chat_id'=>$chatID, 'text'=>$text, 'parse_mode'=>'MarkDown', 'reply_markup'=>bot_violation_settings_keyboard($settings)];
        if($messageId){ $payload['message_id'] = $messageId; unset($payload['chat_id']); $payload['chat_id'] = $chatID; bot('editMessageText', $payload); }
        else bot('sendMessage', $payload);
    }
}

if(!function_exists('bot_violation_runtime_router')){
    function bot_violation_runtime_router(){
        global $Tc, $isAdmin, $msg, $data, $chatID, $userID, $user, $step, $data_id, $admin, $Button_Panel, $Button_back_panel, $msg_id, $chads;

        if(isset($msg) && $Tc === 'private' && $isAdmin && trim((string)$msg) === '🚫 تنظیم تخلف تبلیغ'){
            if(is_array($user)){ $user['step'] = 'none'; saveJson("melat/$userID.json", $user); }
            bot_violation_show_settings($chatID);
            return true;
        }

        if(isset($data) && $Tc === 'private' && $isAdmin && preg_match('/^vset_/', (string)$data)){
            $settings = bot_violation_get_settings();
            if((string)$data === 'vset_toggle_enabled') $settings['enabled'] = bot_violation_toggle_text($settings['enabled']);
            elseif((string)$data === 'vset_toggle_direct') $settings['admin_direct_delete'] = bot_violation_toggle_text($settings['admin_direct_delete']);
            elseif((string)$data === 'vset_toggle_notify') $settings['notify_admin'] = bot_violation_toggle_text($settings['notify_admin']);
            elseif((string)$data === 'vset_threshold'){
                if(is_array($user)){ $user['step'] = 'violation_threshold'; saveJson("melat/$userID.json", $user); }
                bot('answercallbackquery', ['callback_query_id'=>$data_id, 'text'=>'عدد حد گزارش را ارسال کنید', 'show_alert'=>false]);
                bot('sendMessage', ['chat_id'=>$chatID, 'text'=>"عدد حد گزارش تخلف را ارسال کنید.\n\nمثال: **10**", 'parse_mode'=>'MarkDown', 'reply_markup'=>$Button_back_panel ?? null]);
                return true;
            }
            bot_violation_save_settings($settings);
            bot('answercallbackquery', ['callback_query_id'=>$data_id, 'text'=>'تنظیم شد', 'show_alert'=>false]);
            bot_violation_show_settings($chatID, $msg_id ?? null);
            return true;
        }

        if(isset($msg) && $Tc === 'private' && $isAdmin && (string)($step ?? '') === 'violation_threshold'){
            $raw = function_exists('bot_normalize_number_digits') ? bot_normalize_number_digits($msg) : (string)$msg;
            $raw = preg_replace('/[^0-9]/', '', (string)$raw);
            if($raw === '' || (int)$raw < 1){
                bot('sendMessage', ['chat_id'=>$chatID, 'text'=>'❌ فقط عدد بزرگ‌تر از صفر ارسال کنید. مثال: **10**', 'parse_mode'=>'MarkDown', 'reply_markup'=>$Button_back_panel ?? null]);
                return true;
            }
            $settings = bot_violation_get_settings();
            $settings['threshold'] = min(100000, (int)$raw);
            bot_violation_save_settings($settings);
            if(is_array($user)){ $user['step'] = 'none'; saveJson("melat/$userID.json", $user); }
            bot('sendMessage', ['chat_id'=>$chatID, 'text'=>'✅ حد گزارش تخلف با موفقیت ثبت شد.', 'parse_mode'=>'MarkDown', 'reply_markup'=>$Button_Panel ?? null]);
            bot_violation_show_settings($chatID);
            return true;
        }

        if(isset($data) && preg_match('/^vshow-([A-Za-z0-9_\-]+)$/', (string)$data, $m)){
            if(!$isAdmin){ bot('answercallbackquery', ['callback_query_id'=>$data_id, 'text'=>'فقط ادمین اجازه مشاهده آگهی را دارد.', 'show_alert'=>true]); return true; }
            bot_violation_show_reported_ad($m[1], $chatID, $data_id);
            return true;
        }

        if(isset($data) && preg_match('/^vdel-([A-Za-z0-9_\-]+)$/', (string)$data, $m)){
            if(!$isAdmin){ bot('answercallbackquery', ['callback_query_id'=>$data_id, 'text'=>'فقط ادمین اجازه حذف دارد.', 'show_alert'=>true]); return true; }
            $settings = bot_violation_get_settings();
            if((string)$settings['admin_direct_delete'] !== '✅فعال'){
                bot('answercallbackquery', ['callback_query_id'=>$data_id, 'text'=>'حذف مستقیم ادمین غیرفعال است.', 'show_alert'=>true]);
                return true;
            }
            bot('answercallbackquery', ['callback_query_id'=>$data_id, 'text'=>'در حال حذف تبلیغ...', 'show_alert'=>false]);
            bot_violation_delete_order($m[1], $userID, 'admin_direct');
            return true;
        }

        if(isset($data) && preg_match('/^goz-([A-Za-z0-9_\-]+)$/', (string)$data, $m)){
            $settings = bot_violation_get_settings();
            $orderId = bot_violation_clean_order_id($m[1]);
            if($isAdmin){
                if((string)$settings['admin_direct_delete'] !== '✅فعال'){
                    bot('answercallbackquery', ['callback_query_id'=>$data_id, 'text'=>'حذف مستقیم ادمین غیرفعال است.', 'show_alert'=>true]);
                    return true;
                }
                bot('answercallbackquery', ['callback_query_id'=>$data_id, 'text'=>'در حال حذف تبلیغ...', 'show_alert'=>false]);
                bot_violation_delete_order($orderId, $userID, 'admin_direct');
                return true;
            }
            if((string)$settings['enabled'] !== '✅فعال'){
                bot('answercallbackquery', ['callback_query_id'=>$data_id, 'text'=>'گزارش تخلف فعلاً غیرفعال است.', 'show_alert'=>true]);
                return true;
            }
            if(!function_exists('bot_data_file_exists') || !bot_data_file_exists("melat/$userID.json")){
                bot('answercallbackquery', ['callback_query_id'=>$data_id, 'text'=>function_exists('bot_notif_text') ? bot_notif_text('claim_not_started', ['ORDER_ID'=>$orderId]) : '❌ ابتدا ربات را استارت کنید.', 'show_alert'=>true]);
                return true;
            }
            $res = bot_violation_add_report($orderId, $userID);
            if(empty($res['ok'])){
                $err = $res['error'] ?? '';
                $txt = $err === 'duplicate' ? (function_exists('bot_notif_text') ? bot_notif_text('report_already', ['ORDER_ID'=>$orderId]) : 'شما قبلاً این پست را گزارش داده بودید ❌') : ($err === 'order_closed' ? (function_exists('bot_notif_text') ? bot_notif_text('claim_inactive', ['ORDER_ID'=>$orderId]) : 'این تبلیغ قبلاً بسته شده است.') : (function_exists('bot_notif_text') ? bot_notif_text('claim_not_found', ['ORDER_ID'=>$orderId]) : '❌ سفارش یافت نشد'));
                bot('answercallbackquery', ['callback_query_id'=>$data_id, 'text'=>$txt, 'show_alert'=>true]);
                return true;
            }
            $count = (int)$res['count'];
            $threshold = max(1, (int)$settings['threshold']);
            bot('answercallbackquery', ['callback_query_id'=>$data_id, 'text'=>function_exists('bot_notif_text') ? bot_notif_text('report_success', ['ORDER_ID'=>$orderId, 'REPORT_COUNT'=>$count, 'THRESHOLD'=>$threshold]) : "گزارش ثبت شد: $count از $threshold", 'show_alert'=>true]);

            if($count >= $threshold){
                bot_violation_delete_order($orderId, 'system', 'auto_report_threshold');
                return true;
            }

            if((string)$settings['notify_admin'] === '✅فعال' && !empty($admin)){
                $order = is_array($res['order'] ?? null) ? $res['order'] : [];
                $owner = (string)($order['admin'] ?? 'نامشخص');
                $member = (string)($order['member'] ?? 'نامشخص');
                $date = (string)($order['date'] ?? 'نامشخص');
                $text = "🚫 گزارش تخلف جدید\n\nکد سفارش: **$orderId**\nآیدی سفارش‌دهنده: **$owner**\nآیدی گزارش‌دهنده: **$userID**\nممبر درخواستی: **$member**\nتاریخ ثبت: **$date**\nتعداد گزارش: **$count / $threshold**";
                $keyboard = bot_violation_view_keyboard($orderId, $order, $chads ?? '');
                bot('sendMessage', ['chat_id'=>$admin, 'text'=>$text, 'parse_mode'=>'MarkDown', 'reply_markup'=>$keyboard]);
            }
            return true;
        }

        return false;
    }
}

// Create SQL tables automatically on hosts where BOT_SQL_AUTO_INSTALL is enabled.
if(defined('BOT_SQL_AUTO_INSTALL') && BOT_SQL_AUTO_INSTALL){ bot_violation_install_schema(); }
