const fs = require('fs');

const path = 'c:/Users/Mobin/Desktop/wizwiz/wizwizxui-timebot/bot.php';
const lines = fs.readFileSync(path, 'utf8').split(/\r?\n/);

const start = lines.findIndex((l) => l.includes("preg_match('/accept"));
const end = lines.findIndex(
  (l, i) => i > start && l.startsWith("if(preg_match('/decline/")
);

if (start < 0 || end < 0) {
  console.error('markers not found', { start, end });
  process.exit(1);
}

const queue = `if(preg_match('/^accept(.+)$/',$data, $match) and $text != $buttonValues['cancel'] && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    setUser();

    $payHash = $match[1];
    $enqueue = PayFulfillmentQueue::enqueue($payHash);

    if ($enqueue === 'not_found') {
        alert('سفارش یافت نشد');
        exit();
    }
    if ($enqueue === 'approved') {
        alert('✅ قبلاً تأیید شده');
        exit();
    }
    if ($enqueue === 'already_queued') {
        $pos = PayFulfillmentQueue::getQueuePosition($payHash);
        alert("📋 قبلاً در صف ($pos)");
        exit();
    }
    if ($enqueue === 'busy') {
        alert('⏳ این سفارش قابل پردازش نیست');
        exit();
    }

    $pos = PayFulfillmentQueue::getQueuePosition($payHash);
    if ($pos <= 1) {
        alert('⏳ در حال پردازش...');
    } else {
        alert("📋 در صف ($pos)");
    }

    PayFulfillmentQueue::processQueue();
    exit();
}`.split('\n');

const out = [...lines.slice(0, start), ...queue, ...lines.slice(end)];
fs.writeFileSync(path, out.join('\n'), 'utf8');

console.log(
  JSON.stringify(
    {
      replacedFrom: start + 1,
      replacedTo: end,
      removedLines: end - start,
      addedLines: queue.length,
      replacementChars: (out.join('\n').match(/\uFFFD/g) || []).length,
      totalLines: out.length,
    },
    null,
    2
  )
);
