<?php
// Emergency repair for Telegram broadcast queue.
// Upload to bot root, open once with ?run=1, then delete this file.
header('Content-Type: text/plain; charset=utf-8');
$run = php_sapi_name() === 'cli' || (string)($_GET['run'] ?? '') === '1';
if(!$run){
    echo "برای اجرا آدرس را با ?run=1 باز کنید. بعد از اجرا این فایل را حذف کنید.\n";
    exit;
}
$root = __DIR__;
$cacheDir = $root . '/cache';
if(!is_dir($cacheDir)) @mkdir($cacheDir, 0775, true);
$queueFile = $cacheDir . '/broadcast_queue.json';
$lockFile  = $cacheDir . '/broadcast_queue.lock';
$pauseFile = $cacheDir . '/broadcast_paused.flag';
$backup = '';
$cancelled = 0;
$jobsCount = 0;
if(is_file($queueFile)){
    $raw = (string)@file_get_contents($queueFile);
    $backup = $queueFile . '.bak_' . date('Ymd_His');
    @file_put_contents($backup, $raw, LOCK_EX);
    $data = json_decode($raw, true);
    if(!is_array($data)) $data = ['jobs'=>[]];
    if(!isset($data['jobs']) || !is_array($data['jobs'])) $data['jobs'] = [];
    $jobsCount = count($data['jobs']);
    $now = time();
    foreach($data['jobs'] as $i => $job){
        $st = (string)($job['status'] ?? 'queued');
        if(in_array($st, ['queued','running','cooldown'], true)){
            $job['status'] = 'cancelled';
            $job['cancelled_at'] = $now;
            $job['cancelled_by'] = 'broadcast_emergency_repair';
            $job['last_error'] = 'cancelled_by_emergency_repair_after_bot_offline';
            $job['offset'] = max((int)($job['offset'] ?? 0), 0);
            $data['jobs'][$i] = $job;
            $cancelled++;
        }
    }
    if(count($data['jobs']) > 20) $data['jobs'] = array_slice($data['jobs'], -20);
    $tmp = $queueFile . '.tmp';
    @file_put_contents($tmp, json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT), LOCK_EX);
    @rename($tmp, $queueFile);
}
if(is_file($lockFile)) @unlink($lockFile);
@file_put_contents($pauseFile, "paused at ".date('Y-m-d H:i:s')." by broadcast_emergency_repair\n", LOCK_EX);
// Reset admin broadcast steps so the next admin message is not treated as a broadcast payload.
$resetSteps = 0;
foreach(glob($root . '/melat/*.json') ?: [] as $file){
    $raw = (string)@file_get_contents($file);
    $u = json_decode($raw, true);
    if(!is_array($u)) continue;
    $step = (string)($u['step'] ?? '');
    if(in_array($step, ['sendtoall-admin','fortoall-admin'], true)){
        $u['step'] = 'none';
        @file_put_contents($file, json_encode($u, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT), LOCK_EX);
        $resetSteps++;
    }
}
echo "Emergency broadcast repair done.\n";
echo "Queue jobs found: {$jobsCount}\n";
echo "Active jobs cancelled: {$cancelled}\n";
echo "Lock removed: ".(!is_file($lockFile) ? 'yes' : 'no')."\n";
echo "Broadcast paused flag created: {$pauseFile}\n";
if($backup !== '') echo "Backup: {$backup}\n";
echo "Admin broadcast steps reset: {$resetSteps}\n\n";
echo "حالا ربات را با /start تست کنید. اگر بالا آمد، این فایل را از هاست حذف کنید.\n";
echo "برای شروع مجدد ارسال همگانی، فایل cache/broadcast_paused.flag را حذف کنید.\n";
