const fs = require('fs');

const healthyPath = 'c:/Users/Mobin/Desktop/wizwiz/healthy-bot.php';
const botPath = 'c:/Users/Mobin/Desktop/wizwiz/wizwizxui-timebot/bot.php';

const healthy = fs.readFileSync(healthyPath, 'utf8').split(/\r?\n/);
const bot = fs.readFileSync(botPath, 'utf8').split(/\r?\n/);

const start = healthy.findIndex((l) => l.includes("preg_match('/accept"));
const end = healthy.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);
}

let block = healthy.slice(start, end);

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

const payInfoIdx = block.findIndex((l) => l.includes('$payInfo = $stmt->get_result()'));
block.splice(payInfoIdx + 2, 2,
  '',
  '    if(!$payInfo){',
  "        alert('سفارش یافت نشد');",
  '        exit();',
  '    }',
  '    if($payInfo[\'state\'] == "approved"){',
  "        alert('✅ قبلاً تأیید شده');",
  '        exit();',
  '    }',
  '    $payHash = $match[1];'
);

const remarkBlock = `            if(($botState['remark'] ?? '') == "manual"){
                $remark = $payInfo['description'];
            }else{
                $remark = buildOrderRemarkFromPay($payInfo, $srv_remark, $uid);
            }`;

const remarkStart = block.findIndex((l) => l.includes('if($botState[\'remark\'] == "digits")'));
const remarkEnd = block.findIndex((l, i) => i > remarkStart && l.includes('$remark = "{$srv_remark}-{$uid}-{$rnd}"'));
block.splice(remarkStart, remarkEnd - remarkStart + 1, remarkBlock);

const insertIdx = block.findIndex((l) => l.includes('VALUES (?, ?, \'\','));
if (insertIdx >= 0) {
  block[insertIdx] = block[insertIdx].replace("VALUES (?, ?, '',", 'VALUES (?, ?, ?,');
}
const bindIdx = block.findIndex((l) => l.includes('bind_param("ssiiisssisiiii"'));
if (bindIdx >= 0) {
  block[bindIdx] = '            $stmt->bind_param("sssiiisssisiiii", $uid, $token, $payHash, $fid, $server_id, $inbound_id, $remark, $uniqid, $protocol, $expire_date, $vray_link, $eachPrice, $date, $rahgozar, $agent_bought);';
}

const idempotent = [
  '        $existingOrder = getOrderByPayHash($payHash);',
  '        if($existingOrder){',
  '            $remark = $existingOrder[\'remark\'];',
  '            alert($mainValues[\'sending_config_to_user\']);',
  '            deliverPanelOrder($uid, (int)$existingOrder[\'server_id\'], $remark, json_encode([\'inline_keyboard\'=>[[[\'text\'=>$buttonValues[\'back_to_main\'],\'callback_data\'=>"mainMenu"]]]]));',
  '            markPayApproved($payHash);',
  '            unset($markup[count($markup)-1]);',
  '            $markup[] = [[\'text\'=>\'✅\',\'callback_data\'=>\'wizwizch\']];',
  '            editKeys(json_encode([\'inline_keyboard\'=>array_values($markup)],488));',
  '            sendMessage(str_replace(["REMARK", "VOLUME", "DAYS"],[$remark, $volume, $days], $mainValues[\'sent_config_to_user\']), getMainKeys(), null, null, $uid);',
  '            exit();',
  '        }',
  '        ',
];

const alertIdx = block.findIndex((l) => l.includes('alert($mainValues[\'sending_config_to_user\']);'));
block.splice(alertIdx, 0, ...idempotent);

block = block.map((l) => l.replace('markPayApproved($match[1])', 'markPayApproved($payHash)'));

const botStart = bot.findIndex((l) => l.includes("preg_match('/^accept"));
const botEnd = bot.findIndex((l, i) => i > botStart && l.startsWith("if(preg_match('/decline/'"));
const out = [...bot.slice(0, botStart), ...block, ...bot.slice(botEnd)];
fs.writeFileSync(botPath, out.join('\n'), 'utf8');
console.log('restored accept handler', block.length, 'lines');
