<?php
$conn = new mysqli("localhost", "root", "", "list_goa");
register_shutdown_function(function () use ($conn, &$wh_id) {

    $error = error_get_last();
    if ($error !== NULL && $wh_id) {

        $msg = $conn->real_escape_string(print_r($error, true));

        $conn->query("
            UPDATE li_whatsapp
            SET wh_status = 9
            WHERE wh_id = $wh_id
        ");

        file_put_contents(
            'webhook_fatal.log',
            date('Y-m-d H:i:s') . " " . $msg . "\n",
            FILE_APPEND
        );
    }
});

/*************************************************
 * WHATSAPP WEBHOOK – FINAL (PHP 5.6)
 * INSTANT PROCESSING – NO LOOP
 * COMPATIBLE WITH type=chat PAYLOAD
 *************************************************/
try {
date_default_timezone_set('Asia/Kolkata');

// Enable error logging
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/webhook_error.log');

// Enable/disable command tracing (writes JSON lines to command_trace.jsonl)
// Set env var COMMAND_TRACE=1 to enable, OR set true below to always enable
define('COMMAND_TRACE_ENABLED', (getenv('COMMAND_TRACE') === '1') || true); // true = always trace (for debugging)

function appendCommandTrace($payload) {
    if (!defined('COMMAND_TRACE_ENABLED') || !COMMAND_TRACE_ENABLED) return;
    $line = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    if ($line === false) {
        $line = '{"error":"json_encode_failed"}';
    }
    @file_put_contents(__DIR__ . '/command_trace.jsonl', $line . "\n", FILE_APPEND);
}

/* ================= DB ================= */

$b_url='http://localhost/server4';
if ($conn->connect_error) {
    error_log("MySQL connection error: " . $conn->connect_error);
    http_response_code(500);
    exit;
}

/* ============ READ WEBHOOK ============ */
$raw = file_get_contents("php://input");
$event = json_decode($raw, true);

/* OPTIONAL LOG (keep while testing) */
// file_put_contents('webhook_log.txt', $raw . "\n", FILE_APPEND);

/* ============ VALIDATE EVENT ============ */
if (!isset($event['event_type']) || $event['event_type'] != 'message_received') {
    http_response_code(200);
    exit;
}

if (!isset($event['data'])) {
    http_response_code(200);
    exit;
}

$msg = $event['data'];

/* ============ BASIC FIELDS ============ */
$wh_mid  = isset($msg['id']) ? $msg['id'] : '';
$wh_from = isset($msg['from']) ? $msg['from'] : '';
$wh_type = isset($msg['type']) ? $msg['type'] : '';
$wh_body = isset($msg['body']) ? trim($msg['body']) : '';
$wh_media = '';
if (isset($msg['media']) && is_string($msg['media']) && $msg['media'] !== '') {
    $wh_media = trim($msg['media']);
} elseif (isset($msg['mediaUrl']) && is_string($msg['mediaUrl']) && $msg['mediaUrl'] !== '') {
    $wh_media = trim($msg['mediaUrl']);
}

$wh_type_l = strtolower(trim($wh_type));
/* OpenWA often puts media URL into body for image msgs */
if ($wh_media === '' && preg_match('#^https?://.+/(api/ultramsg/media/|media/)#i', $wh_body)) {
    $wh_media = $wh_body;
}
$is_image_msg = (
    in_array($wh_type_l, array('image', 'sticker', 'document', 'ptt'), true) ||
    $wh_media !== ''
);

/* Require id + from; body required only for text (images may have empty caption) */
if ($wh_mid == '' || $wh_from == '') {
    http_response_code(200);
    exit;
}
if (!$is_image_msg && $wh_body == '') {
    http_response_code(200);
    exit;
}

/* ============ NORMALIZE MOBILE ============ */
$bet_numer = str_replace(array('@c.us','@g.us','@lid'), '', $wh_from);
if (strlen($bet_numer) == 12) {
    $bet_numer = substr($bet_numer, 2);
}

/* ============ IMAGE → OCR TEXT ============ */
$wh_img_url = '';
$wh_img_read = 0;
$msg_type_db = 1; /* 1=text, 2=image */

if ($is_image_msg && $wh_media !== '') {
    $msg_type_db = 2;
    $localImg = downloadWhatsAppMedia($wh_media, $wh_mid);
    if ($localImg !== '') {
        $wh_img_url = $localImg;
        $ocrText = runBetImageOcr($localImg);
        if ($ocrText !== '') {
            $wh_body = normalizeOcrBetText($ocrText);
            $wh_img_read = 1;
            error_log("OCR ok for mid=$wh_mid body_len=" . strlen($wh_body));
        } else {
            error_log("OCR empty for mid=$wh_mid file=$localImg");
            $wh_body = '';
        }
    } else {
        error_log("Media download failed for mid=$wh_mid url=" . substr($wh_media, 0, 120));
        $wh_body = '';
    }
} elseif ($is_image_msg && $wh_media === '') {
    $msg_type_db = 2;
    error_log("Image message without media URL. mid=$wh_mid");
}

/* Caption-only / OCR body cleanup — image messages only */
if ($is_image_msg && $wh_body !== '') {
    $wh_body = normalizeOcrBetText($wh_body);
}

/* ============ INPUT SANITY (weird/garbage string reject) ============ */
if (strlen($wh_body) > 4000) {
    error_log("Rejected: message too long (" . strlen($wh_body) . " chars)");
    http_response_code(200);
    exit;
}

/* ============ QUOTED MESSAGE (SAFE) ============ */
$wh_replyfor = '';
if (isset($msg['quotedMsg']) && is_array($msg['quotedMsg']) && isset($msg['quotedMsg']['id'])) {
    $wh_replyfor = $msg['quotedMsg']['id'];
}

/* ============ DUPLICATE CHECK ============ */
$chk = $conn->query("SELECT wh_id FROM li_whatsapp WHERE wh_mid='$wh_mid' LIMIT 1");
if ($chk->num_rows > 0) {
    http_response_code(200);
    exit;
}

/* ============ SAVE MESSAGE ============ */
$esc_mid  = $conn->real_escape_string($wh_mid);
$esc_from = $conn->real_escape_string($wh_from);
$esc_body = $conn->real_escape_string($wh_body);
$esc_img  = $conn->real_escape_string($wh_img_url);
$conn->query("
    INSERT INTO li_whatsapp
    (wh_mid, wh_from, wh_message, wh_img_url, wh_type, wh_img_read, wh_status, wh_string_status, wh_date)
    VALUES
    ('$esc_mid','$esc_from','$esc_body','$esc_img',$msg_type_db,$wh_img_read,1,0,NOW())
");
$wh_id = $conn->insert_id;

/* Image could not be OCR'd → do not treat media URL as bet text */
if ($is_image_msg && $wh_body === '') {
    sendWhatsApp($bet_numer, "Image read failed ❌");
    markDone($wh_id);
    http_response_code(200);
    exit;
}

/* =================================================
 * 1️⃣ COMMAND HANDLING (GAME, GROUP, ETC)
 * ================================================= */
$is_group = false;
$groupname = '';
$group_game_name = '';

$processed = checkStringForCommand($wh_body);
// Persist command trace for this message (if enabled)
if (isset($GLOBALS['last_command_trace']) && is_array($GLOBALS['last_command_trace'])) {
    appendCommandTrace(array(
        'ts' => date('Y-m-d H:i:s'),
        'wh_mid' => $wh_mid,
        'from' => $bet_numer,
        'body' => $wh_body,
        'trace' => $GLOBALS['last_command_trace']
    ));
}

/* GAME COMMAND HANDLED */
if ($processed === '') {
    error_log("Processed is empty for message: " . $wh_body);
    markDone($wh_id);
    exit;
}

error_log("Processing message - From: $bet_numer, Body: $wh_body, Processed: $processed");

/* =================================================
 * 2️⃣ DELETE BET (reply based)
 * ================================================= */
if (deletebetByMessageRep($wh_body, $wh_id, $wh_replyfor, 0, 0, $bet_numer)) {
    sendWhatsApp($bet_numer, "Deleted Successfully ✅");
    markDone($wh_id);
    exit;
}

/* =================================================
 * 3️⃣ BALANCE
 * ================================================= */
if (preg_match('/^(bal|balance)$/i', $wh_body)) {
	//echo "hello"; die();
    checkforBalanceEnq($bet_numer);
    markDone($wh_id);
    exit;
}

/* =================================================
 * 3.2️⃣ HELP / COMMANDS LIST
 * ================================================= */
if (preg_match('/^(help|commands|command|cmd)$/i', trim($wh_body))) {
    sendHelpCommands($bet_numer);
    markDone($wh_id);
    exit;
}

/* =================================================
 * 3.5️⃣ CHECK MOBILE IN MSSQL (BEFORE FORMAT CHECK)
 * ================================================= */

// Normalize mobile number (remove all non-digits)
$mobile_normalized = preg_replace('/\D+/', '', $bet_numer);

// Check if mobile exists in MSSQL TbParty table
error_log("Checking mobile in MSSQL: " . $mobile_normalized);
$partyData = exportTbPartyByMobileMSSQL($mobile_normalized);

if (empty($partyData)) {
    error_log("Mobile not found in MSSQL TbParty: " . $mobile_normalized . " - No reply sent");
    markDone($wh_id);
    exit;
}

error_log("Mobile found in MSSQL. Party data: " . print_r($partyData, true));

// Get customer info from MSSQL
$partyName = isset($partyData[0]['p_party']) ? $partyData[0]['p_party'] : 'UNKNOWN';
$partyName = trim($partyName);

$replyLines = array();


/* =================================================
 * 4️⃣ PARSE BET STRING
 * ================================================= */
error_log("Before extractBetsWithPatterns - processed: '$processed'");
$betData = extractBetsWithPatterns($processed);
$processed   = $betData['normal'];
$patternBets = $betData['pattern'];
error_log("After extractBetsWithPatterns - normal: '$processed', pattern bets count: " . count($patternBets));

$expandedPatternLines = array();

foreach ($patternBets as $pb) {

    $replyLines[] = implode('.', $pb['numbers']) . '=' . $pb['amount'];

    $expanded = expandPatternBetToPana(
        $pb['pattern'],
        $pb['numbers'],
        $pb['amount'],
        $conn
    );

    foreach ($expanded as $line) {
        $expandedPatternLines[] = $line;
    }
}

/* merge expanded pattern bets into normal flow */
if (!empty($expandedPatternLines)) {
    $processed = trim(
        implode("\n", $expandedPatternLines) . "\n" . $processed
    );
}


if ($processed == '' && empty($patternBets) ) {
    error_log("Wrong format - Processed empty and no pattern bets. Original: $wh_body");
    sendWhatsApp($bet_numer, "Wrong format ❌");
    markDone($wh_id);
    exit;
}

// Strict guard:
// Agar raw message ki kisi line me sirf digits hain (e.g. "800300")
// to usko ambiguous/missed format maan kar poora message reject karo.
// Isse partial processing (kuch lines insert, kuch miss) nahi hogi.
$rawLinesForStrict = preg_split('/\r\n|\n/', trim((string)$wh_body));
foreach ($rawLinesForStrict as $rawLineStrict) {
    $rawLineStrict = trim($rawLineStrict);
    if ($rawLineStrict === '') continue;
    // pure digits, length >= 4 (likely num+amount glued without separator)
    if (preg_match('/^\d{4,}$/', $rawLineStrict)) {
        error_log("Strict format reject: ambiguous numeric line without separator: " . $rawLineStrict);
        sendWhatsApp($bet_numer, "Wrong format ❌");
        markDone($wh_id);
        exit;
    }
}

error_log("Bet parsed successfully. Processed: $processed, Pattern bets: " . count($patternBets));

/* =================================================
 * 4.9️⃣ MSSQL CONNECTION (needed for mode check)
 * ================================================= */

// Get MSSQL PDO connection (used for open-result check + insert)
$pdoMSSQL = getMSSQLConnection();
if (!$pdoMSSQL) {
    sendWhatsApp($bet_numer, "Database connection error ❌");
    markDone($wh_id);
    exit;
}

/* =================================================
 * 5️⃣ GAME ID SETTING (Mobile already checked above)
 * ================================================= */

list($manual_game_id, $gameName, $bettype_opcl_id, $timeOverMsg) = resolveActiveGameAndBetType($conn, $pdoMSSQL);
if ($timeOverMsg !== '') {
    sendWhatsApp($bet_numer, $timeOverMsg);
    markDone($wh_id);
    exit;
}

$opcltype_ms = ($bettype_opcl_id == 1) ? 'OPEN' : 'CLOSE';





/* =================================================
 * 6️⃣ SAVE BET DIRECTLY TO MSSQL
 * ================================================= */

$total = 0;
$msgstring = '';
$invalidNums = array();
$invalidLines = array();

error_log("Processing bets. Processed string: '$processed'");

$lines = preg_split('/\r\n|\n/', $processed);
error_log("Split into " . count($lines) . " lines");

/* ===== PASS 1: Validate ALL - if any invalid pana, reject ENTIRE message ===== */
$invalidPana = array();
$invalidNums = array();
$invalidJodiClose = array();
$betsToProcess = array();
foreach ($lines as $line) {
    $line = trim($line);
    if ($line == '') continue;
    
    if (strpos($line, '=') === false) continue;
    $parts = explode('=', $line, 2);
    if (count($parts) < 2) continue;
    
    $num = trim($parts[0]);
    $amt = trim($parts[1]);
    if (!is_numeric($amt) || (int)$amt <= 0 || (int)$amt > 999999) continue;

    if (strpos($num, ',') !== false) {
        $nums = explode(',', $num);
        foreach ($nums as $n) {
            $n = trim($n);
            if (!is_numeric($n)) continue;
            $nlen = strlen($n);
            if ($nlen > 3 || $nlen <= 0) {
                $invalidNums[] = $n;
                continue;
            }
            // Rule:
            // 1 digit -> OPEN/CLOSE both
            // 2 digit -> OPEN only
            // 3 digit -> OPEN/CLOSE both (but must exist in li_pana.pana)
            if ($nlen == 2 && $opcltype_ms !== 'OPEN') {
                $invalidJodiClose[] = $n;
                continue;
            }
            if ($nlen == 3) {
                $n_esc = $conn->real_escape_string($n);
                $chk = $conn->query("SELECT 1 FROM li_pana WHERE pana = '$n_esc' LIMIT 1");
                if (!$chk || $chk->num_rows == 0) {
                    $invalidPana[] = $n;
                    continue;
                }
            }
            $betsToProcess[] = array('num' => $n, 'amt' => $amt);
        }
    } else {
        if (!is_numeric($num)) continue;
        $nlen = strlen($num);
        if ($nlen > 3 || $nlen <= 0) {
            $invalidNums[] = $num;
            continue;
        }
        // 2 digit -> OPEN only
        if ($nlen == 2 && $opcltype_ms !== 'OPEN') {
            $invalidJodiClose[] = $num;
            continue;
        }
        if ($nlen == 3) {
            $num_esc = $conn->real_escape_string($num);
            $chk = $conn->query("SELECT 1 FROM li_pana WHERE pana = '$num_esc' LIMIT 1");
            if (!$chk || $chk->num_rows == 0) {
                $invalidPana[] = $num;
                continue;
            }
        }
        $betsToProcess[] = array('num' => $num, 'amt' => $amt);
    }
}

// If ANY invalid pana: reject entire message, no bets inserted
if (!empty($invalidPana)) {
    $invalidPanaList = implode(', ', array_values(array_unique($invalidPana)));
    $hint = "Invalid pana: " . $invalidPanaList;
    sendWhatsApp($bet_numer, $hint);
    markDone($wh_id);
    exit;
}

// If jodi was sent in CLOSE mode: reject entire message
if (!empty($invalidJodiClose)) {
    $badJodi = implode(', ', array_values(array_unique($invalidJodiClose)));
    sendWhatsApp($bet_numer, "Jodi only allowed in Open: " . $badJodi);
    markDone($wh_id);
    exit;
}

/* ===== PASS 2: Insert all bets (no invalid pana found) ===== */
foreach ($betsToProcess as $b) {
    $n = $b['num'];
    $amt = $b['amt'];
    $insertResult = insertBetToMSSQL($pdoMSSQL, $n, $amt, $opcltype_ms, $manual_game_id, $partyName, $mobile_normalized, $partyData);
    if ($insertResult) {
        $total += (int)$amt;
        $msgstring .= $n . '=' . $amt . "\n";
        error_log("Bet inserted successfully: $n=$amt");
    } else {
        error_log("Bet insertion failed: $n=$amt");
    }
}

error_log("After processing all bets - Total: $total, Message string length: " . strlen($msgstring));

/* =================================================
 * 7️⃣ CONFIRMATION
 * ================================================= */

// Check if any bets were processed
if ($total == 0 || trim($msgstring) == '') {
    error_log("No bets processed - Total: $total, MsgString: '$msgstring'");
    if (!empty($invalidNums)) {
        $badList = implode(', ', array_values(array_unique($invalidNums)));
        sendWhatsApp($bet_numer, "Invalid number(s): " . $badList);
    } else {
        sendWhatsApp($bet_numer, "No valid bets found. Please check your format ❌");
    }
    markDone($wh_id);
    exit;
}

$opcl = ($bettype_opcl_id == 1) ? 'Open' : 'Close';

error_log("Sending confirmation to: $bet_numer, Total: $total, Msg: " . trim($msgstring));
error_log("Current gameName variable before confirmation: '$gameName'");

// Double-check game name if it's still empty or fallback
if ($gameName == '' || strpos($gameName, 'Game ID:') !== false) {
    error_log("Re-checking game name - current value is: '$gameName'");
    // Try again with MSSQL connection
    if ($pdoMSSQL) {
        $gameName = getGameNameFromMSSQLWithPDO($pdoMSSQL, $manual_game_id);
        error_log("Re-fetched game name: '$gameName'");
    }
    
    // Final fallback if still empty
    if ($gameName == '') {
        $gameName = "Game ID: $manual_game_id";
    }
}

error_log("Final gameName for confirmation message: '$gameName'");

$confirmMsg = $gameName . " " . $opcl . "\n" .
    trim($msgstring) . "\n" .
    "Total Amount = $total ✅";

error_log("About to send confirmation message: " . substr($confirmMsg, 0, 200));
sendWhatsApp($bet_numer, $confirmMsg);
error_log("Confirmation message sent to WhatsApp");

markDone($wh_id);


exit;

}catch (Exception $e) {

    $err = $conn->real_escape_string($e->getMessage());

    $conn->query("
        UPDATE li_whatsapp
        SET wh_status = 9,
            wh_string_status = 0
        WHERE wh_id = $wh_id
    ");
}


/* =================================================
 * 🔹 FUNCTIONS (PHP 5.6 SAFE)
 * ================================================= */

/**
 * Download OpenWA/UltraMsg media URL to uploads/whatsapp/.
 * Returns relative path (uploads/whatsapp/xxx.jpg) or '' on failure.
 */
function downloadWhatsAppMedia($mediaUrl, $wh_mid) {
    $dir = __DIR__ . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'whatsapp';
    if (!is_dir($dir)) {
        @mkdir($dir, 0777, true);
    }
    if (!is_dir($dir)) {
        error_log("downloadWhatsAppMedia: cannot create dir $dir");
        return '';
    }

    $ext = 'jpg';
    $pathPart = parse_url($mediaUrl, PHP_URL_PATH);
    if (is_string($pathPart) && preg_match('/\.(jpe?g|png|gif|webp|bmp)$/i', $pathPart, $m)) {
        $ext = strtolower($m[1]);
        if ($ext === 'jpeg') $ext = 'jpg';
    }

    $safeMid = preg_replace('/[^a-zA-Z0-9_-]/', '_', $wh_mid);
    if (strlen($safeMid) > 80) {
        $safeMid = substr($safeMid, 0, 80);
    }
    $filename = date('Ymd_His') . '_' . $safeMid . '.' . $ext;
    $fullPath = $dir . DIRECTORY_SEPARATOR . $filename;

    $fp = @fopen($fullPath, 'wb');
    if (!$fp) {
        error_log("downloadWhatsAppMedia: cannot open $fullPath");
        return '';
    }

    $curl = curl_init($mediaUrl);
    curl_setopt_array($curl, array(
        CURLOPT_FILE => $fp,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_TIMEOUT => 60,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_USERAGENT => 'Mozilla/5.0'
    ));
    $ok = curl_exec($curl);
    $http = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    $err = curl_error($curl);
    curl_close($curl);
    fclose($fp);

    if (!$ok || $http >= 400 || !file_exists($fullPath) || filesize($fullPath) < 50) {
        error_log("downloadWhatsAppMedia failed http=$http err=$err");
        @unlink($fullPath);
        return '';
    }

    return 'uploads/whatsapp/' . $filename;
}

/**
 * Run Python OCR script on local image path.
 * Uses admin/ocr toolchain (shared).
 */
function runBetImageOcr($relativeOrAbsolutePath) {
    $imgPath = $relativeOrAbsolutePath;
    if (!preg_match('/^[A-Za-z]:[\\\\\\/]/', $imgPath) && strpos($imgPath, DIRECTORY_SEPARATOR) !== 0) {
        $imgPath = __DIR__ . DIRECTORY_SEPARATOR . str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $imgPath);
    }
    if (!is_file($imgPath)) {
        error_log("runBetImageOcr: file missing $imgPath");
        return '';
    }

    $ocrRoot = 'C:\\xampp\\htdocs\\admin\\ocr';
    $python = $ocrRoot . DIRECTORY_SEPARATOR . 'python' . DIRECTORY_SEPARATOR . 'python.exe';
    if (!is_file($python)) {
        $python = 'python';
    }
    $script = $ocrRoot . DIRECTORY_SEPARATOR . 'ocr_bet_image.py';
    if (!is_file($script)) {
        error_log("runBetImageOcr: script missing $script");
        return '';
    }

    putenv('TESSERACT_CMD=C:\\Program Files\\Tesseract-OCR\\tesseract.exe');

    $cmd = 'cmd /c ""' . $python . '" "' . $script . '" "' . $imgPath . '""';
    $lines = array();
    $code = 1;
    exec($cmd, $lines, $code);

    if ($code !== 0) {
        error_log("runBetImageOcr exit=$code cmd=$cmd");
        return '';
    }
    return trim(implode("\n", $lines));
}

/**
 * Light OCR cleanup — keep Rs/=/_/x for bet normalizers.
 */
function normalizeOcrBetText($text) {
    $text = trim($text);
    if ($text === '') return '';

    $lines = preg_split('/\r\n|\r|\n/', $text);
    $out = array();
    $headerRe = '/^(pana|sutta|jodi|joddi|sp|dp|tp|sanju(\s+pune)?)$/i';
    $marketRe = '/\b(kalyan|milan|time|sridevi|rajdhani|madhur|supreme|open|close|day|night|bazar|bazaar)\b/i';

    foreach ($lines as $line) {
        $line = trim($line);
        if ($line === '') continue;
        if (preg_match($headerRe, $line)) continue;
        if (preg_match($marketRe, $line) && !preg_match('/\d/', $line)) continue;
        if (!preg_match('/\d/', $line) && preg_match('/[A-Za-z]/', $line)) continue;
        $line = preg_replace('/[ \t]+/', ' ', $line);
        $out[] = trim($line);
    }
    return implode("\n", $out);
}

function markDone($wh_id) {
    global $conn;
    $conn->query("UPDATE li_whatsapp SET wh_status=2, wh_string_status=1 WHERE wh_id=$wh_id");
}

function getUserIDbyBetNo($mobile) {
    global $conn;
    // Only used for balance check - keep if balance feature is needed
    $r = $conn->query("SELECT id FROM users WHERE phone='$mobile' AND active=1 LIMIT 1");
    if ($r->num_rows > 0) {
        $row = $r->fetch_assoc();
        return $row['id'];
    }
    return 0;
}

// REMOVED UNUSED FUNCTIONS (they used MySQL tables we don't need for MSSQL version):
// - getUserSelectedOrTimeGame() - used li_gamename, user_selected_game
// - getGameByCommand() - used li_gamename  
// - decideGameByResultAndTime() - used final_result, li_gamename
// - createBetHeader() - used place_bet (we insert directly to MSSQL TbAKADA)

/**
 * Get active game based on current time from li_game_times table
 * Returns game data with mssql_game_id, game_name, and bet_type (1=OPEN, 2=CLOSE)
 */
function getActiveGameByTime($conn, $current_time, $current_hour_min) {
    // Special case: 00:00 to 00:06 AM - use CLOSE mode
    if ($current_hour_min >= '00:00' && $current_hour_min < '00:06') {
        $sql = "SELECT mssql_game_id, game_name, close_time 
                FROM li_game_times 
                WHERE is_active=1 and id = 12
                AND close_time IS NOT NULL
                ORDER BY mssql_game_id LIMIT 1";
        $result = $conn->query($sql);
        if ($result && $result->num_rows > 0) {
            $game = $result->fetch_assoc();
            return array(
                'mssql_game_id' => $game['mssql_game_id'],
                'game_name' => $game['game_name'],
                'bet_type' => 2 // CLOSE
            );
        }
    }
    
    // Normal logic: Find game where current time is within start_time and close_time
    $sql = "SELECT mssql_game_id, game_name, start_time, open_time, close_time
            FROM li_game_times 
            WHERE is_active=1 
            AND start_time IS NOT NULL 
            AND close_time IS NOT NULL
            AND TIME('$current_time') >= TIME(start_time)
            AND TIME('$current_time') <= TIME(close_time)
            ORDER BY mssql_game_id LIMIT 1";
	 $sql = "SELECT mssql_game_id, game_name, start_time, open_time, close_time
            FROM li_game_times 
            WHERE is_active=1 
            AND id = 12 ORDER BY mssql_game_id LIMIT 1";
    
    $result = $conn->query($sql);
    
    if ($result && $result->num_rows > 0) {
        $game = $result->fetch_assoc();
        
        // Determine OPEN or CLOSE based on open_time
        $bet_type = 1; // Default to OPEN
        
        if ($game['open_time']) {
            // If current time is before open_time → OPEN
            // If current time is after open_time → CLOSE
            if (strtotime($current_time) > strtotime($game['open_time'])) {
                $bet_type = 2; // CLOSE
            } else {
                $bet_type = 1; // OPEN
            }
        }
        
        return array(
            'mssql_game_id' => $game['mssql_game_id'],
            'game_name' => $game['game_name'],
            'bet_type' => $bet_type
        );
    }
    
    return false;
}

function getGameNameFromMSSQL($gameId, $pdo = null) {
    // Get MSSQL connection if not provided
    if (!$pdo) {
        $pdo = getMSSQLConnection();
    }
    
    if (!$pdo) {
        error_log("getGameNameFromMSSQL: MSSQL connection not available");
        return '';
    }
    
    if ($gameId <= 0) {
        error_log("getGameNameFromMSSQL: Invalid game ID: $gameId");
        return '';
    }
    
    try {
        // Query MSSQL TbNewGame table using N_Id for game ID and N_BazarName for game name
        $tableName = 'TbNewGame';
        $sql = "SELECT N_BazarName FROM $tableName WHERE N_Id = :gameId";
        error_log("getGameNameFromMSSQL: Executing query: $sql with N_Id: $gameId");
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute([':gameId' => $gameId]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($row && isset($row['N_BazarName'])) {
            $name = trim($row['N_BazarName']);
            error_log("getGameNameFromMSSQL: Found game name: '$name' from table $tableName");
            return $name;
        } else {
            error_log("getGameNameFromMSSQL: No game found with N_Id: $gameId in table $tableName");
        }
    } catch (Exception $e) {
        error_log("getGameNameFromMSSQL exception: " . $e->getMessage());
    }
    
    return '';
}

// Helper function to use existing PDO connection
function getGameNameFromMSSQLWithPDO($pdo, $gameId) {
    return getGameNameFromMSSQL($gameId, $pdo);
}

// Keep old function for backward compatibility (if needed elsewhere)
function getGameNameById($gameId) {
    // Redirect to MSSQL function
    return getGameNameFromMSSQL($gameId);
}

// REMOVED UNUSED FUNCTIONS (they used MySQL tables we don't need for MSSQL version):
// - getSubgameAndWonType() - used users table (only needed for MySQL place_bet_child which we don't use)
// - insertBetChildInstant() - used place_bet_child table (we insert directly to MSSQL TbAKADA instead)

function parseDotAmountLine($line) {
    $out = [];
    preg_match_all('/\d+/', $line, $m);
    if (count($m[0]) < 2) return $out;

    $current = [];
    foreach ($m[0] as $n) {
        if ((int)$n >= 1000) {
            if ($current) {
                $out[] = implode(',', $current) . '=' . $n;
                $current = [];
            }
        } else {
            $current[] = $n;
        }
    }
    return $out;
}

function extractNumberAmountPairs($input) {

    $output = [];

    /* RULE 0: 1–9–0 MAP */
    if (
        !preg_match('/[a-zA-Z=\/\*\.,\-_]/', $input) &&
        preg_match_all('/\d+/', $input, $m10) &&
        count($m10[0]) === 10
    ) {
        $digits = ['1','2','3','4','5','6','7','8','9','0'];
        foreach ($digits as $i => $d) {
            $output[] = $d . '=' . $m10[0][$i];
        }
        return implode("\n", $output);
    }

    $lines = preg_split('/\r\n|\r|\n/', trim($input));
    $carryAmount = null;

    foreach ($lines as $line) {
        $line = trim($line);
        if ($line === '') continue;

        // DATE IGNORE
        if (
            preg_match('/\b\d{1,2}[\.\/\-]\d{1,2}[\.\/\-]\d{2,4}\b/', $line) &&
            !preg_match('/(==|__|=|\/|\*)/', $line)
        ) continue;

        // DIRECT PAIR
        if (
            substr_count($line, '=') === 1 &&
            preg_match('/^\D*(\d+)\D*=\D*(\d+)\D*$/', $line, $mm) &&
            !preg_match('/[.,\-]/', $mm[1])
        ) {
            $carryAmount = $mm[2];
            $output[] = $mm[1] . '=' . $mm[2];
            continue;
        }

        // == HEADER
        if (preg_match('/(\d+)[^\d]*==+[^\d]*(\d+)/', $line, $m)) {
            $carryAmount = $m[2];
            $output[] = $m[1] . '=' . $carryAmount;
            continue;
        }

        // __ HEADER
        if (preg_match('/(\d+)[^\d]*__+[^\d]*(\d+)/', $line, $m)) {
            $carryAmount = $m[2];
            $output[] = $m[1] . '=' . $carryAmount;
            continue;
        }

        // DOT STYLE
        if (preg_match('/\d{4,}/', $line)) {
            foreach (parseDotAmountLine($line) as $g) {
                $output[] = $g;
            }
            continue;
        }

        // FALLBACK
        preg_match_all('/\d+/', $line, $m2);
        if (!count($m2[0])) continue;

        if (count($m2[0]) === 1 && $carryAmount !== null) {
            $output[] = $m2[0][0] . '=' . $carryAmount;
            continue;
        }

        if (count($m2[0]) === 2) {
            $carryAmount = $m2[0][1];
            $output[] = $m2[0][0] . '=' . $carryAmount;
            continue;
        }

        if (count($m2[0]) >= 2) {
            // Agar line "num1,num2,num3=" jaisa hai (= ke baad kuch nahi) to guess mat karo - last pana ko amount na banao
            if (preg_match('/=\s*$/', $line) || preg_match('/=\s*$/', trim($line))) {
                continue;  // empty amount, skip - avoid wrong guess (e.g. 126,180,...,568= me 568 amount nahi)
            }
            $amt = array_pop($m2[0]);
            $output[] = implode(',', $m2[0]) . '=' . $amt;
        }
    }

    return implode("\n", array_values(array_unique($output)));
}

function sendWhatsApp($num, $msg) {
    global $conn;

    error_log("sendWhatsApp called - To: $num, Message: " . substr($msg, 0, 100));

    $r = $conn->query("SELECT * FROM application_mst WHERE appmst_status=0 LIMIT 1");
    if ($r->num_rows == 0) {
        error_log("sendWhatsApp: No active application_mst record found");
        return;
    }

    $a = $r->fetch_assoc();
    error_log("sendWhatsApp: Using API URL: " . (isset($a['whatsup_apinew2_url']) ? $a['whatsup_apinew2_url'] : 'NOT SET'));

    if (strlen($num) == 10) {
        $num = "91" . $num;
    } elseif (strlen($num) > 12) {
        $num = $num . "@g.us";
    }

    $postData = "token=".$a['whatsup_apinew2']."&to=".$num."&body=".urlencode($msg);
    error_log("sendWhatsApp: Post data length: " . strlen($postData));

    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => $a['whatsup_apinew2_url'],
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $postData,
        CURLOPT_SSL_VERIFYPEER => false,  // Disable SSL certificate verification
        CURLOPT_SSL_VERIFYHOST => false   // Disable SSL host verification
    ));
    $response = curl_exec($curl);
    $curlError = curl_error($curl);
    $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    curl_close($curl);

    if ($curlError) {
        error_log("sendWhatsApp cURL error: " . $curlError);
    }
    error_log("sendWhatsApp response - HTTP Code: $httpCode, Response: " . substr($response, 0, 200));
}

function sendHelpCommands($bet_numer) {
    global $conn;

    $rows = $conn->query("
        SELECT com_display_name, com_name, game_name, com_min_no, com_max_no
        FROM li_com
        WHERE com_status = 1
        ORDER BY com_id
    ");

    if (!$rows) {
        sendWhatsApp($bet_numer, "Help not available (db error) ❌");
        return;
    }

    $lines = array();
    $lines[] = "HELP / COMMANDS";
    $lines[] = "Format: COMMAND NUMBERS=AMOUNT";
    $lines[] = "Note: command ke andar space mat do (SPMOTAR ✅, SP MOTAR ❌)";
    $lines[] = "Allowed bets: Single(0-9), Jodi(00-99), Pana";
    $lines[] = "----";

    while ($r = $rows->fetch_assoc()) {
        $aliasStr = isset($r['com_name']) ? $r['com_name'] : '';
        $aliases = explode(',', $aliasStr);
        $primary = '';
        if (isset($aliases[0])) {
            $primary = trim($aliases[0]);
        }
        if ($primary === '') continue;

        $min = (int)$r['com_min_no'];
        $max = (int)$r['com_max_no'];
        $gname = isset($r['game_name']) ? trim($r['game_name']) : '';
        if ($gname === '') $gname = $primary;

        // Prefer display name if present (clean title)
        $title = isset($r['com_display_name']) ? trim($r['com_display_name']) : '';
        if ($title === '') $title = $primary;

        // pick a simple example digits based on min/max
        $digits = '1';
        if ($min >= 4) {
            $digits = '4567';
        } elseif ($min == 3 && $max == 3) {
            $digits = '123';
        } elseif ($min == 2 && $max == 2) {
            $digits = '12';
        }

        $example = $primary . " " . $digits . "=10";

        // Pretty format requested by user:
        // Command name
        // Example
        // Game name
        // blank line
        $lines[] = $title;
        $lines[] = "Ex: " . $example;
        $lines[] = $gname;
        $lines[] = "";
    }

    // Split into multiple WhatsApp messages (avoid very long payload)
    $maxLen = 1400;
    $msgs = array();
    $cur = '';
    foreach ($lines as $ln) {
        $ln = (string)$ln;
        $add = ($cur === '' ? $ln : ($cur . "\n" . $ln));
        if (strlen($add) > $maxLen) {
            if ($cur !== '') $msgs[] = $cur;
            $cur = $ln;
        } else {
            $cur = $add;
        }
    }
    if ($cur !== '') $msgs[] = $cur;

    foreach ($msgs as $m) {
        sendWhatsApp($bet_numer, $m);
    }
}

function detectKeyWordInString($s, $k) {
    return (strpos(strtolower($s), strtolower($k)) !== false);
}

function deletebetByMessageRep($msg, $msg_id, $reply, $g, $o, $num) {
    // DISABLED - This function used MySQL place_bet tables which we don't use in MSSQL version
    // If you need delete functionality, you'll need to implement it using MSSQL TbAKADA table
    // For now, return 0 to disable this feature
    return 0;
    
    /* OLD CODE (commented out - used MySQL place_bet tables):
    if ($reply == '') return 0;
	
    if (!detectKeyWordInString($msg, 'del')) return 0;

    global $conn;

    $r = $conn->query("SELECT wh_id FROM li_whatsapp WHERE wh_mid='$reply' LIMIT 1");
    if ($r->num_rows == 0) return 0;

    $row = $r->fetch_assoc();
    $whid = $row['wh_id'];

    $b = $conn->query("SELECT bet_id FROM place_bet WHERE whats_id=$whid LIMIT 1");
    if ($b->num_rows == 0) return 0;

    $bid = $b->fetch_assoc()['bet_id'];

    $conn->query("DELETE FROM place_bet_child WHERE child_betid=$bid");
    $conn->query("DELETE FROM place_bet WHERE bet_id=$bid");

    return 1;
    */
}


function fetchUserDateBalance($fdate,$tdate,$user_id){
	
	
 
     global $conn ;
     global $b_url ;

$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL => "$b_url/REPORT001/showBalBy_date_new", // Set the URL of the API endpoint
    CURLOPT_RETURNTRANSFER => true, // Return the response as a string
    CURLOPT_POST => true, // Set the request method to POST
    CURLOPT_POSTFIELDS => http_build_query(array('fdate' => $fdate,'tdate' => $tdate, 'user_id' => $user_id)), // Set the POST data as an array
));
$response = curl_exec($curl);

if(curl_errno($curl)){
    echo 'cURL error: ' . curl_error($curl);
}

curl_close($curl);

return $response;
  
     
	
}


function checkforBalanceEnq($bet_numer){
	  // return 0;
	   global $conn ;
    
	 $userid=getUserIDbyBetNo($bet_numer);
	 $bet_numer;

	$lastMonday = strtotime('last Monday');
    $yesterday = strtotime('today');
   // $yesterday = strtotime('yesterday');
    $date = $lastMonday;
	$mess_1date_check = "";
    while ($date <= $yesterday) {
    $formattedDate = date('Y-m-d', $date);
    
     $formattedDate ;
        $q=fetchUserDateBalance($formattedDate,$formattedDate,$userid);
      // $q_ws=fetchUserDateBalance_withoutshare($formattedDate,$userid);
	// die();
	$arraystr = explode('##',$q);
	//$arraystr11 = explode('##',$q_ws);
	 $lenadena='';
	 $lenadena_l='';
	 if ($arraystr[3] > 0) {
	    $lenadena='L' ;	 
	 }else if($arraystr[3] < 0){
		$lenadena='D' ;
	 }else if($arraystr[3] == 0){
		$lenadena='' ;
	 }
	 
	 if ($arraystr[5] > 0) {
	    $lenadena_l='L' ;	 
	 }else if($arraystr[5] < 0){
		$lenadena_l='D' ;
	 }else if($arraystr[5] == 0){
		$lenadena_l='' ;
	 }
	 
	 
	// $mess_1date=date('d-m-Y', strtotime($formattedDate)).'  Credit : '.$arraystr[0].'  Com : '.$arraystr[1].'  Debit : '.$arraystr[2].'  Bal no : '.$arraystr[3].' Sha. : '.$lenadena.'  Sha. : '.$arraystr[4].' Balance : '.$arraystr[5].' '.$lenadena_l;
	// $mess_1date=date('d-m-Y', strtotime($formattedDate)).' ## Credit : '.$arraystr[0].' ## Com : '.$arraystr[1].' ## Debit : '.$arraystr[2].' ## Bal no : '.$arraystr[3].' Sha. : '.$lenadena.' ## Sha. : '.$arraystr[4].'## Balance : '.$arraystr[5].' '.$lenadena_l;

	$mess_1date=date('d-m-Y', strtotime($formattedDate)).' ## Credit : '.$arraystr[0].' ## Com : '.$arraystr[1].' ## Debit : '.$arraystr[2].' ## Bal no : '.$arraystr[3].' ## Purana hisab : '.($arraystr[6]- $arraystr[7]);	
    $mess_1date = str_replace("##", " \r\n ",$mess_1date);  
    $mess_1date_check = $mess_1date_check."\r\n".$mess_1date;	
    // sendWhatsApp($bet_numer,$mess_1date) ;
    // Increment the loop variable by one day
    $date = strtotime('+1 day', $date);

    }
	

	 $f_date = date('Y-m-d', $lastMonday);
	 $t_date = date('Y-m-d', $yesterday);
	 
	$lastbal=fetchUserDateBalance($f_date,$t_date,$userid);
	$arraystr = explode('##',$lastbal);
	//$arraystr11 = explode('##',$q_ws);
	 $lenadena='';
	 $lenadena_l='';
	 if ($arraystr[3] > 0) {
	    $lenadena='L' ;	 
	 }else if($arraystr[3] < 0){
		$lenadena='D' ;
	 }else if($arraystr[3] == 0){
		$lenadena='' ;
	 }
	 
	 
	 if ($arraystr[5] > 0) {
	    $lenadena_l='L' ;	 
	 }else if($arraystr[5] < 0){
		$lenadena_l='D' ;
	 }else if($arraystr[5] == 0){
		$lenadena_l='' ;
	 }
	 
	 
    // $mess_1date='Final ## Credit :'.$arraystr[0].' ## Com : '.$arraystr[1].' ## Debit : '.$arraystr[2].' ## Bal no :  '.$arraystr[3].' Sha.:'.$lenadena.' ## Sha. : '.$arraystr[4].'## Balance :'.$arraystr[5].' '.$lenadena_l;
	
	$mess_1date= $mess_1date_check . "\r\n" .'Final ## Credit :'.$arraystr[0].' ## Com : '.$arraystr[1].' ## Debit : '.$arraystr[2].' ## Bal no :  '.$arraystr[3]. ' ## Purana hisab :  '.($arraystr[6]-$arraystr[7]) ;
	
	
	 $mess_1date = str_replace("##", " \r\n ",$mess_1date);

     sendWhatsApp($bet_numer,$mess_1date) ;
	    // $wh_string_status=1;
        // $wh_overtime_status=0;

       // updateWhatsappTableStatus($message_id,$wh_string_status,$wh_overtime_status) ;
}

function multiexplode($delimiters, $string) {
    $ready = str_replace($delimiters, $delimiters[0], $string);
    $launch = explode($delimiters[0], $ready);
    return $launch;
}

function breakString($s, $a) {
    $chunks = array();
    for ($i = 0; $i < strlen($s); $i += $a) {
        $chunks[] = substr($s, $i, $a);
    }
    return $chunks;
}

function get2DigitCombinations($digits) {
    $length = strlen($digits);
    $combinations = array();
    for ($i = 0; $i < $length - 1; $i++) {
        for ($j = $i + 1; $j < $length; $j++) {
            $combination = $digits[$i] . $digits[$j];
            $combinations[] = $combination;
        }
    }
    return $combinations;
}

function checkStringForCommand($string) {
    global $conn;
    global $is_group;
    global $group_game_name;
    global $groupname;
    // expose last trace to caller
    $GLOBALS['last_command_trace'] = array();

    $originalString = $string; // backup original

    // If user types mixed digits+letters without separators (e.g. "1sp1"),
    // DO NOT delete it (old code caused amount loss + duplicate expansion).
    // Instead, insert spaces between digit/letter boundaries: "1sp1" -> "1 sp 1"
    $string = preg_replace('/(?<=\d)(?=[a-zA-Z])|(?<=[a-zA-Z])(?=\d)/', ' ', $string);
    $string = trim(preg_replace('/\s+/', ' ', $string));

    // IMPORTANT: command matching must run on normalized string (so "1sp1" can match "SP")
    $string_full = strtoupper($string);

    $arraystr_lastChar22 = multiexplode(array("=", "*", "-", "+"), $string);

    // If no explicit operator was used, infer "numbers" and "amount" from numeric tokens.
    // Examples:
    // - "1 sp 1"    -> numbers="1", amount="1"
    // - "12 sp 50"  -> numbers="12", amount="50"
    // - "1 2 3 sp 50" -> numbers="123", amount="50"
    if (!isset($arraystr_lastChar22[1]) || trim((string)$arraystr_lastChar22[1]) === '') {
        $tokens = array();
        if (preg_match_all('/\d+/', $string, $m)) {
            $tokens = $m[0];
        }

        if (count($tokens) >= 2) {
            $amountToken = $tokens[count($tokens) - 1];
            $numberTokens = array_slice($tokens, 0, -1);
            $numbersToken = implode('', $numberTokens);

            $arraystr_lastChar22[0] = $numbersToken;
            $arraystr_lastChar22[1] = $amountToken;
        }
    }

    $arraystr_lastChar22[0] = preg_replace("/\D/", "", (string)$arraystr_lastChar22[0]);
    if (!isset($arraystr_lastChar22[1])) {
        $arraystr_lastChar22[1] = '';
    }

    // Initialize trace
    $GLOBALS['last_command_trace'] = array(
        'input' => $originalString,
        'normalized' => $string,
        'numbers_token' => $arraystr_lastChar22[0],
        'amount_token' => $arraystr_lastChar22[1],
        'matches' => array(),
        'final_processed' => null
    );

    // Include com_display_name for better trace readability
    $sql_command = "SELECT com_display_name,com_name,com_function,game_name,com_min_no,com_max_no,com_code FROM li_com WHERE com_status = 1";
    $result_command = $conn->query($sql_command);

    // Pehle saare matches collect karo, phir LONGEST alias wala use karo (ABR CUT pehle, ABR baad me)
    $bestMatch = null;
    $bestAliasLen = 0;

    while ($row_com = $result_command->fetch_assoc()) {

        $cmd_com = $row_com["com_name"];
        $cmd     = explode(",", $cmd_com);

        foreach ($cmd as $c) {
            $c = trim($c);
            if ($c === "") continue;

            $cUpper = strtoupper($c);
            if (preg_match('/\b' . preg_quote($cUpper, '/') . '\b/', $string_full)) {
                $len = strlen($c);
                if ($len > $bestAliasLen) {
                    $bestAliasLen = $len;
                    $bestMatch = array('row' => $row_com, 'alias' => $c);
                }
            }
        }
    }

    $matchedAnyCommand = ($bestMatch !== null);
    if ($matchedAnyCommand) {
        $row_com = $bestMatch['row'];
        $comand  = $bestMatch['alias'];

        $function_name = $row_com["com_function"];

        $wordCount = strlen($arraystr_lastChar22[0]);

        $group_game_name = $row_com["game_name"];
        $groupname       = $row_com["com_code"];
        $is_group        = true;
        $min_dig         = $row_com["com_min_no"];
        $max_dig         = $row_com["com_max_no"];

        $matchTrace = array(
            'com_display_name' => isset($row_com["com_display_name"]) ? $row_com["com_display_name"] : '',
            'com_code' => $groupname,
            'matched_alias' => $comand,
            'function' => $function_name,
            'min_dig' => $min_dig,
            'max_dig' => $max_dig,
            'numbers_token' => $arraystr_lastChar22[0],
            'amount_token' => $arraystr_lastChar22[1]
        );

        if ($min_dig != $max_dig) {
             if($function_name != "selectGameCommand"){
                 $string = call_user_func($function_name, $arraystr_lastChar22[0]);
             }else{
                 $string = call_user_func($function_name, $string);
             }
            
            if ($string == "") {
                $string = "abc";
            }

            if (
                $wordCount <= $max_dig &&
                $wordCount >= $min_dig &&
                $string != "abc" &&
                trim((string)$arraystr_lastChar22[1]) !== ''
            ) {
                $string = $string . "=" . $arraystr_lastChar22[1];
            } else {
                $string  = "abc";
            }

        } else {

            $string = "";
            $chunks = breakString($arraystr_lastChar22[0], $min_dig);

            foreach ($chunks as $chunk) { 
                $cunkresult = call_user_func($function_name, $chunk);
                $string = $string . "," . $cunkresult;

                if ($cunkresult == "") {
                    $string = "abc";
                    break;
                }
            }

            if ($string != "abc" && trim((string)$arraystr_lastChar22[1]) !== '') {
                $string = ltrim($string, ",");
                $string = $string . "=" . $arraystr_lastChar22[1];
            } else {
                $string = "abc";  // amount missing (e.g. "ABR SP 9" bina amount ke)
            }
        }

        $matchTrace['result_preview'] = (is_string($string) ? substr($string, 0, 120) : '');
        $GLOBALS['last_command_trace']['matches'][] = $matchTrace;
    }
    
    if ($string === '__GAME_SELECTED__') {
        return '';
    }

    // AGAR KISIBHI COMMAND SE MATCH NAHI HUA, ORIGINAL STRING RETURN KARO
    if (!$matchedAnyCommand) {
        $GLOBALS['last_command_trace']['final_processed'] = $originalString;
        return $originalString;
    }

    $GLOBALS['last_command_trace']['final_processed'] = $string;
    return $string;
}

/* =================================================
 * ALL COMMAND FUNCTIONS FROM li_com TABLE
 * ================================================= */

function getMotorSp($number) {
    global $conn;
    $returnStr = "";
    $number = trim($number);
    $sql_user = "SELECT GROUP_CONCAT(`pana` SEPARATOR ',') As li_pana
FROM li_pana
WHERE 
    CONCAT(pana) REGEXP '[[:<:]]' 
    AND (
        (INSTR('$number', SUBSTRING(pana, 1, 1)) > 0)
        AND (INSTR('$number', SUBSTRING(pana, 2, 1)) > 0)
        AND (INSTR('$number', SUBSTRING(pana, 3, 1)) > 0)
    ) And pana_type = 1";
    $result_game = $conn->query($sql_user);
    while ($row_user = $result_game->fetch_assoc()) {
        $returnStr = $returnStr . "," . $row_user["li_pana"];
    }
    if (strpos($returnStr, ",") === 0) {
        $returnStr = ltrim($returnStr, ",");
    }
    return $returnStr;
}

function getMotorDp($number) {
    global $conn;
    $returnStr = "";
    $number = trim($number);
    $sql_user = "SELECT GROUP_CONCAT(`pana` SEPARATOR ',') As li_pana
FROM li_pana
WHERE 
    CONCAT(pana) REGEXP '[[:<:]]' 
    AND (
        (INSTR('$number', SUBSTRING(pana, 1, 1)) > 0)
        AND (INSTR('$number', SUBSTRING(pana, 2, 1)) > 0)
        AND (INSTR('$number', SUBSTRING(pana, 3, 1)) > 0)
    ) And pana_type = 2";
    $result_game = $conn->query($sql_user);
    while ($row_user = $result_game->fetch_assoc()) {
        $returnStr = $returnStr . "," . $row_user["li_pana"];
    }
    if (strpos($returnStr, ",") === 0) {
        $returnStr = ltrim($returnStr, ",");
    }
    return $returnStr;
}

function getMotorCutSp($number) {
    global $conn;
    $returnStr = "";
    $number = trim($number);
    $sql_user = "SELECT GROUP_CONCAT(`pana` SEPARATOR ',') As li_pana
FROM li_pana
WHERE 
    CONCAT(pana) REGEXP '[[:<:]]' 
    AND NOT (
        (INSTR('$number', SUBSTRING(pana, 1, 1)) > 0)
        or (INSTR('$number', SUBSTRING(pana, 2, 1)) > 0)
        or (INSTR('$number', SUBSTRING(pana, 3, 1)) > 0)
    ) And pana_type = 1";
    $result_game = $conn->query($sql_user);
    while ($row_user = $result_game->fetch_assoc()) {
        $returnStr = $returnStr . "," . $row_user["li_pana"];
    }
    if (strpos($returnStr, ",") === 0) {
        $returnStr = ltrim($returnStr, ",");
    }
    return $returnStr;
}

function getMotorCutDp($number) {
    global $conn;
    $returnStr = "";
    $number = trim($number);
    $sql_user = "SELECT GROUP_CONCAT(`pana` SEPARATOR ',') As li_pana
FROM li_pana
WHERE 
    CONCAT(pana) REGEXP '[[:<:]]' 
    AND NOT (
        (INSTR('$number', SUBSTRING(pana, 1, 1)) > 0)
        or (INSTR('$number', SUBSTRING(pana, 2, 1)) > 0)
        or (INSTR('$number', SUBSTRING(pana, 3, 1)) > 0)
    ) And pana_type = 2";
    $result_game = $conn->query($sql_user);
    while ($row_user = $result_game->fetch_assoc()) {
        $returnStr = $returnStr . "," . $row_user["li_pana"];
    }
    if (strpos($returnStr, ",") === 0) {
        $returnStr = ltrim($returnStr, ",");
    }
    return $returnStr;
}

function getCommonSP($number) {
    global $conn;
    $returnStr = "";
    for ($i = 0; $i < strlen($number); $i++) {
        $sql_user = "SELECT GROUP_CONCAT(`pana` SEPARATOR ',') As li_pana FROM  li_pana where pana Like '%$number[$i]%' and pana_type=1";
        $result_game = $conn->query($sql_user);
        while ($row_user = $result_game->fetch_assoc()) {
            $returnStr = $returnStr . "," . $row_user["li_pana"];
        }
    }
    if (strpos($returnStr, ",") === 0) {
        $returnStr = ltrim($returnStr, ",");
    }
    return $returnStr;
}

function getCommonDP($number) {
    global $conn;
    $returnStr = "";
    for ($i = 0; $i < strlen($number); $i++) {
        $sql_user = "SELECT GROUP_CONCAT(`pana` SEPARATOR ',') As li_pana FROM  li_pana where pana Like '%$number[$i]%' and pana_type=2";
        $result_game = $conn->query($sql_user);
        while ($row_user = $result_game->fetch_assoc()) {
            $returnStr = $returnStr . "," . $row_user["li_pana"];
        }
    }
    if (strpos($returnStr, ",") === 0) {
        $returnStr = ltrim($returnStr, ",");
    }
    return $returnStr;
}

function getChipke($number) {
    global $conn;
    $number = trim($number);
    $returnStr = "";
    for ($i = 0; $i < strlen($number); $i++) {
        $sql_user = "SELECT GROUP_CONCAT(`pana` SEPARATOR ',') As li_pana FROM  li_pana where number_main = $number[$i] and check_chipke_bikhre=1";
        $result_game = $conn->query($sql_user);
        while ($row_user = $result_game->fetch_assoc()) {
            $returnStr = $returnStr . "," . $row_user["li_pana"];
        }
    }
    if (strpos($returnStr, ",") === 0) {
        $returnStr = ltrim($returnStr, ",");
    }
    return $returnStr;
}

function getbikhre($number) {
    global $conn;
    $number = trim($number);
    $returnStr = "";
    for ($i = 0; $i < strlen($number); $i++) {
        $sql_user = "SELECT GROUP_CONCAT(`pana` SEPARATOR ',') As li_pana FROM  li_pana where number_main = $number[$i] and check_chipke_bikhre=2";
        $result_game = $conn->query($sql_user);
        while ($row_user = $result_game->fetch_assoc()) {
            $returnStr = $returnStr . "," . $row_user["li_pana"];
        }
    }
    if (strpos($returnStr, ",") === 0) {
        $returnStr = ltrim($returnStr, ",");
    }
    return $returnStr;
}

function getrun($number) {
    global $conn;
    $number = trim($number);
    $returnStr = "";
    for ($i = 0; $i < strlen($number); $i++) {
        $sql_user = "SELECT GROUP_CONCAT(`pana` SEPARATOR ',') As li_pana FROM  li_pana where number_main = $number[$i] and check_run=1";
        $result_game = $conn->query($sql_user);
        while ($row_user = $result_game->fetch_assoc()) {
            $returnStr = $returnStr . "," . $row_user["li_pana"];
        }
    }
    if (strpos($returnStr, ",") === 0) {
        $returnStr = ltrim($returnStr, ",");
    }
    return $returnStr;
}

function getCenter($number) {
    global $conn;
    $number = trim($number);
    $returnStr = "";
    for ($i = 0; $i < strlen($number); $i++) {
        $sql_user = "SELECT GROUP_CONCAT(`pana` SEPARATOR ',') As li_pana FROM  li_pana where check_center = $number[$i] and check_center != ''";
        $result_game = $conn->query($sql_user);
        while ($row_user = $result_game->fetch_assoc()) {
            $returnStr = $returnStr . "," . $row_user["li_pana"];
        }
    }
    if (strpos($returnStr, ",") === 0) {
        $returnStr = ltrim($returnStr, ",");
    }
    return $returnStr;
}

function getforgot($number) {
    global $conn;
    $number = trim($number);
    $returnStr = "";
    for ($i = 0; $i < strlen($number); $i++) {
        $sql_user = "SELECT GROUP_CONCAT(`pana` SEPARATOR ',') As li_pana FROM  li_pana where number_main = $number[$i] and check_forgot=1";
        $result_game = $conn->query($sql_user);
        while ($row_user = $result_game->fetch_assoc()) {
            $returnStr = $returnStr . "," . $row_user["li_pana"];
        }
    }
    if (strpos($returnStr, ",") === 0) {
        $returnStr = ltrim($returnStr, ",");
    }
    return $returnStr;
}

function getcycle($number) {
    global $conn;
    $number = trim($number);
    $number = get2DigitCombinations($number);
    $returnStr = "";
    for ($i = 0; $i < count($number); $i++) {
        $digits = str_split($number[$i]);
        if ($digits[0] == $digits[1]) {
            $sql_user = "SELECT GROUP_CONCAT(`pana` SEPARATOR ',') As li_pana FROM  li_pana where pana Like '%$number[$i]%'";
        } else {
            $sql_user = "SELECT GROUP_CONCAT(`pana` SEPARATOR ',') As li_pana FROM  li_pana where pana Like '%$digits[0]%' and pana Like '%$digits[1]%'";
        }
        $result_game = $conn->query($sql_user);
        while ($row_user = $result_game->fetch_assoc()) {
            $returnStr = $returnStr . "," . $row_user["li_pana"];
        }
    }
    if (strpos($returnStr, ",") === 0) {
        $returnStr = ltrim($returnStr, ",");
    }
    return $returnStr;
}

function getSp($number) {
    global $conn;
    $number = trim($number);
    $returnStr = "";
    for ($i = 0; $i < strlen($number); $i++) {
        $sql_user = "SELECT GROUP_CONCAT(`pana` SEPARATOR ',') As li_pana FROM  li_pana where number_main = $number[$i] and pana_type=1";
        $result_game = $conn->query($sql_user);
        while ($row_user = $result_game->fetch_assoc()) {
            $returnStr = $returnStr . "," . $row_user["li_pana"];
        }
    }
    if (strpos($returnStr, ",") === 0) {
        $returnStr = ltrim($returnStr, ",");
    }
    return $returnStr;
}

function getDp($number) {
    global $conn;
    $number = trim($number);
    $returnStr = "";
    for ($i = 0; $i < strlen($number); $i++) {
        $sql_user = "SELECT GROUP_CONCAT(`pana` SEPARATOR ',') As li_pana FROM  li_pana where number_main = $number[$i] and pana_type=2";
        $result_game = $conn->query($sql_user);
        while ($row_user = $result_game->fetch_assoc()) {
            $returnStr = $returnStr . "," . $row_user["li_pana"];
        }
    }
    if (strpos($returnStr, ",") === 0) {
        $returnStr = ltrim($returnStr, ",");
    }
    return $returnStr;
}

function getSpDp($number) {
    global $conn;
    $number = trim($number);
    $returnStr = "";
    for ($i = 0; $i < strlen($number); $i++) {
        $sql_user = "SELECT GROUP_CONCAT(`pana` SEPARATOR ',') As li_pana FROM  li_pana where number_main = $number[$i] and (pana_type=1 Or pana_type=2) ";
        $result_game = $conn->query($sql_user);
        while ($row_user = $result_game->fetch_assoc()) {
            $returnStr = $returnStr . "," . $row_user["li_pana"];
        }
    }
    if (strpos($returnStr, ",") === 0) {
        $returnStr = ltrim($returnStr, ",");
    }
    return $returnStr;
}

function getSpTp($number) {
    global $conn;
    $number = trim($number);
    $returnStr = "";
    for ($i = 0; $i < strlen($number); $i++) {
        $sql_user = "SELECT GROUP_CONCAT(`pana` SEPARATOR ',') As li_pana FROM  li_pana where number_main = $number[$i] and (pana_type=1 Or pana_type=3) ";
        $result_game = $conn->query($sql_user);
        while ($row_user = $result_game->fetch_assoc()) {
            $returnStr = $returnStr . "," . $row_user["li_pana"];
        }
    }
    if (strpos($returnStr, ",") === 0) {
        $returnStr = ltrim($returnStr, ",");
    }
    return $returnStr;
}

function getSpDpTp($number) {
    global $conn;
    $number = trim($number);
    $returnStr = "";
    for ($i = 0; $i < strlen($number); $i++) {
        $sql_user = "SELECT GROUP_CONCAT(`pana` SEPARATOR ',') As li_pana FROM  li_pana where number_main = $number[$i] and (pana_type=1 or pana_type=2 Or pana_type=3) ";
        $result_game = $conn->query($sql_user);
        while ($row_user = $result_game->fetch_assoc()) {
            $returnStr = $returnStr . "," . $row_user["li_pana"];
        }
    }
    if (strpos($returnStr, ",") === 0) {
        $returnStr = ltrim($returnStr, ",");
    }
    return $returnStr;
}

function getSpStart($number) {
    global $conn;
    $number = trim($number);
    $returnStr = "";
    for ($i = 0; $i < strlen($number); $i++) {
        $sql_user = "SELECT GROUP_CONCAT(`pana` SEPARATOR ',') As li_pana FROM  li_pana where pana Like '$number[$i]%'  and pana_type=1 ";
        $result_game = $conn->query($sql_user);
        while ($row_user = $result_game->fetch_assoc()) {
            $returnStr = $returnStr . "," . $row_user["li_pana"];
        }
    }
    if (strpos($returnStr, ",") === 0) {
        $returnStr = ltrim($returnStr, ",");
    }
    return $returnStr;
}

function getDpStart($number) {
    global $conn;
    $number = trim($number);
    $returnStr = "";
    for ($i = 0; $i < strlen($number); $i++) {
        $sql_user = "SELECT GROUP_CONCAT(`pana` SEPARATOR ',') As li_pana FROM  li_pana where pana Like '$number[$i]%'  and pana_type=2 ";
        $result_game = $conn->query($sql_user);
        while ($row_user = $result_game->fetch_assoc()) {
            $returnStr = $returnStr . "," . $row_user["li_pana"];
        }
    }
    if (strpos($returnStr, ",") === 0) {
        $returnStr = ltrim($returnStr, ",");
    }
    return $returnStr;
}

function getSpEnd($number) {
    global $conn;
    $number = trim($number);
    $returnStr = "";
    for ($i = 0; $i < strlen($number); $i++) {
        $sql_user = "SELECT GROUP_CONCAT(`pana` SEPARATOR ',') As li_pana FROM  li_pana where pana Like '%$number[$i]'  and pana_type=1 ";
        $result_game = $conn->query($sql_user);
        while ($row_user = $result_game->fetch_assoc()) {
            $returnStr = $returnStr . "," . $row_user["li_pana"];
        }
    }
    if (strpos($returnStr, ",") === 0) {
        $returnStr = ltrim($returnStr, ",");
    }
    return $returnStr;
}

function getDpEnd($number) {
    global $conn;
    $number = trim($number);
    $returnStr = "";
    for ($i = 0; $i < strlen($number); $i++) {
        $sql_user = "SELECT GROUP_CONCAT(`pana` SEPARATOR ',') As li_pana FROM  li_pana where pana Like '%$number[$i]'  and pana_type=2 ";
        $result_game = $conn->query($sql_user);
        while ($row_user = $result_game->fetch_assoc()) {
            $returnStr = $returnStr . "," . $row_user["li_pana"];
        }
    }
    if (strpos($returnStr, ",") === 0) {
        $returnStr = ltrim($returnStr, ",");
    }
    return $returnStr;
}

function getDpTp($number) {
    global $conn;
    $number = trim($number);
    $returnStr = "";
    for ($i = 0; $i < strlen($number); $i++) {
        $sql_user = "SELECT GROUP_CONCAT(`pana` SEPARATOR ',') As li_pana FROM  li_pana where number_main = $number[$i] and (pana_type=2 Or pana_type=3) ";
        $result_game = $conn->query($sql_user);
        while ($row_user = $result_game->fetch_assoc()) {
            $returnStr = $returnStr . "," . $row_user["li_pana"];
        }
    }
    if (strpos($returnStr, ",") === 0) {
        $returnStr = ltrim($returnStr, ",");
    }
    return $returnStr;
}

function getMotorSpDp($number) {
    global $conn;
    $returnStr = "";
    $number = trim($number);
    $sql_user = "SELECT GROUP_CONCAT(`pana` SEPARATOR ',') As li_pana
FROM li_pana
WHERE 
    CONCAT(pana) REGEXP '[[:<:]]' 
    AND (
        (INSTR('$number', SUBSTRING(pana, 1, 1)) > 0)
        AND (INSTR('$number', SUBSTRING(pana, 2, 1)) > 0)
        AND (INSTR('$number', SUBSTRING(pana, 3, 1)) > 0)
    ) And (pana_type = 1 or pana_type = 2)";
    $result_game = $conn->query($sql_user);
    while ($row_user = $result_game->fetch_assoc()) {
        $returnStr = $returnStr . "," . $row_user["li_pana"];
    }
    if (strpos($returnStr, ",") === 0) {
        $returnStr = ltrim($returnStr, ",");
    }
    return $returnStr;
}

function getCommonSPDP($number) {
    global $conn;
    $returnStr = "";
    for ($i = 0; $i < strlen($number); $i++) {
        $sql_user = "SELECT GROUP_CONCAT(`pana` SEPARATOR ',') As li_pana FROM  li_pana where pana Like '%$number[$i]%' and (pana_type=1 or pana_type=2)";
        $result_game = $conn->query($sql_user);
        while ($row_user = $result_game->fetch_assoc()) {
            $returnStr = $returnStr . "," . $row_user["li_pana"];
        }
    }
    if (strpos($returnStr, ",") === 0) {
        $returnStr = ltrim($returnStr, ",");
    }
    return $returnStr;
}

function getMotorCutSpDp($number) {
    global $conn;
    $returnStr = "";
    $number = trim($number);
    $sql_user = "SELECT GROUP_CONCAT(`pana` SEPARATOR ',') As li_pana
FROM li_pana
WHERE 
    CONCAT(pana) REGEXP '[[:<:]]' 
    AND NOT (
        (INSTR('$number', SUBSTRING(pana, 1, 1)) > 0)
        or (INSTR('$number', SUBSTRING(pana, 2, 1)) > 0)
        or (INSTR('$number', SUBSTRING(pana, 3, 1)) > 0)
    ) And (pana_type = 1 or pana_type = 2)";
    $result_game = $conn->query($sql_user);
    while ($row_user = $result_game->fetch_assoc()) {
        $returnStr = $returnStr . "," . $row_user["li_pana"];
    }
    if (strpos($returnStr, ",") === 0) {
        $returnStr = ltrim($returnStr, ",");
    }
    return $returnStr;
}

function getSpDpStart($number) {
    global $conn;
    $number = trim($number);
    $returnStr = "";
    for ($i = 0; $i < strlen($number); $i++) {
        $sql_user = "SELECT GROUP_CONCAT(`pana` SEPARATOR ',') As li_pana FROM  li_pana where pana Like '$number[$i]%'  and (pana_type=1 or pana_type=2)";
        $result_game = $conn->query($sql_user);
        while ($row_user = $result_game->fetch_assoc()) {
            $returnStr = $returnStr . "," . $row_user["li_pana"];
        }
    }
    if (strpos($returnStr, ",") === 0) {
        $returnStr = ltrim($returnStr, ",");
    }
    return $returnStr;
}

function getSpDpEnd($number) {
    global $conn;
    $number = trim($number);
    $returnStr = "";
    for ($i = 0; $i < strlen($number); $i++) {
        $sql_user = "SELECT GROUP_CONCAT(`pana` SEPARATOR ',') As li_pana FROM  li_pana where pana Like '%$number[$i]'  and (pana_type=1 or pana_type=2)";
        $result_game = $conn->query($sql_user);
        while ($row_user = $result_game->fetch_assoc()) {
            $returnStr = $returnStr . "," . $row_user["li_pana"];
        }
    }
    if (strpos($returnStr, ",") === 0) {
        $returnStr = ltrim($returnStr, ",");
    }
    return $returnStr;
}

function getSabhiFigurCut($number) {
    global $conn;
    $number = trim($number);
    $returnStr = "";
    $panacut_1 = array(146, 380, 489, 560, 227);
    $panacut_2 = array(138, 156, 237, 570, 499);
    $panacut_3 = array(238, 247, 490, 580, 166);
    $panacut_4 = array(149, 167, 257, 590, 338);
    $panacut_5 = array(168, 249, 267, 348, 500);
    $panacut_6 = array(150, 169, 349, 358, 277);
    $panacut_7 = array(160, 250, 278, 368, 449);
    $panacut_8 = array(279, 350, 378, 459, 116);
    $panacut_9 = array(126, 270, 450, 469, 388);
    $panacut_10 = array(127, 136, 389, 479, 550);
    $pana = array();
    for ($i = 0; $i < strlen($number); $i++) {
        if ($number[$i] == 1) {
            $pana = array_merge($pana, $panacut_1);
        } elseif ($number[$i] == 2) {
            $pana = array_merge($pana, $panacut_2);
        } elseif ($number[$i] == 3) {
            $pana = array_merge($pana, $panacut_3);
        } elseif ($number[$i] == 4) {
            $pana = array_merge($pana, $panacut_4);
        } elseif ($number[$i] == 5) {
            $pana = array_merge($pana, $panacut_5);
        } elseif ($number[$i] == 6) {
            $pana = array_merge($pana, $panacut_6);
        } elseif ($number[$i] == 7) {
            $pana = array_merge($pana, $panacut_7);
        } elseif ($number[$i] == 8) {
            $pana = array_merge($pana, $panacut_8);
        } elseif ($number[$i] == 9) {
            $pana = array_merge($pana, $panacut_9);
        } elseif ($number[$i] == 0) {
            $pana = array_merge($pana, $panacut_10);
        }
        if (isset($pana)) {
            if (is_array($pana)) {
                $returnStr = implode(", ", $pana);
            }
        }
    }
    if (strpos($returnStr, ",") === 0) {
        $returnStr = ltrim($returnStr, ",");
    }
    return $returnStr;
}

function get52Pana($number) {
    global $conn;
    $number = trim($number);
    $returnStr = "";
    $pana52_1 = array(137, 579, 678, 146, 380);
    $pana52_2 = array(246, 480, 345, 237, 570);
    $pana52_3 = array(139, 157, 120, 238, 580);
    $pana52_4 = array(248, 680, 789, 149, 257);
    $pana52_5 = array(159, 357, 456, 258, 780, 230);
    $pana52_6 = array(240, 268, 123, 169, 358);
    $pana52_7 = array(179, 359, 890, 278, 250);
    $pana52_8 = array(260, 468, 567, 378, 350);
    $pana52_9 = array(135, 379, 234, 270, 469);
    $pana52_10 = array(280, 460, 190, 235, 370, 578);
    $pana = array();
    for ($i = 0; $i < strlen($number); $i++) {
        if ($number[$i] == 1) {
            $pana = array_merge($pana, $pana52_1);
        } elseif ($number[$i] == 2) {
            $pana = array_merge($pana, $pana52_2);
        } elseif ($number[$i] == 3) {
            $pana = array_merge($pana, $pana52_3);
        } elseif ($number[$i] == 4) {
            $pana = array_merge($pana, $pana52_4);
        } elseif ($number[$i] == 5) {
            $pana = array_merge($pana, $pana52_5);
        } elseif ($number[$i] == 6) {
            $pana = array_merge($pana, $pana52_6);
        } elseif ($number[$i] == 7) {
            $pana = array_merge($pana, $pana52_7);
        } elseif ($number[$i] == 8) {
            $pana = array_merge($pana, $pana52_8);
        } elseif ($number[$i] == 9) {
            $pana = array_merge($pana, $pana52_9);
        } elseif ($number[$i] == 0) {
            $pana = array_merge($pana, $pana52_10);
        }
        if (isset($pana)) {
            if (is_array($pana)) {
                $returnStr = implode(", ", $pana);
            }
        }
    }
    if (strpos($returnStr, ",") === 0) {
        $returnStr = ltrim($returnStr, ",");
    }
    return $returnStr;
}

function get56Pana($number) {
    global $conn;
    $number = trim($number);
    $returnStr = "";
    $pana56_1 = array(236, 245, 489, 579, 678);
    $pana56_2 = array(237, 246, 345, 589, 679);
    $pana56_3 = array(238, 247, 256, 346, 689);
    $pana56_4 = array(239, 248, 257, 347, 356, 789);
    $pana56_5 = array(249, 258, 267, 348, 456, 357);
    $pana56_6 = array(259, 268, 349, 358, 367, 457);
    $pana56_7 = array(269, 278, 359, 368, 458, 467);
    $pana56_8 = array(279, 369, 378, 459, 468, 567);
    $pana56_9 = array(234, 289, 379, 469, 478, 568);
    $pana56_10 = array(235, 389, 479, 569, 578);
    $pana = array();
    for ($i = 0; $i < strlen($number); $i++) {
        if ($number[$i] == 1) {
            $pana = array_merge($pana, $pana56_1);
        } elseif ($number[$i] == 2) {
            $pana = array_merge($pana, $pana56_2);
        } elseif ($number[$i] == 3) {
            $pana = array_merge($pana, $pana56_3);
        } elseif ($number[$i] == 4) {
            $pana = array_merge($pana, $pana56_4);
        } elseif ($number[$i] == 5) {
            $pana = array_merge($pana, $pana56_5);
        } elseif ($number[$i] == 6) {
            $pana = array_merge($pana, $pana56_6);
        } elseif ($number[$i] == 7) {
            $pana = array_merge($pana, $pana56_7);
        } elseif ($number[$i] == 8) {
            $pana = array_merge($pana, $pana56_8);
        } elseif ($number[$i] == 9) {
            $pana = array_merge($pana, $pana56_9);
        } elseif ($number[$i] == 0) {
            $pana = array_merge($pana, $pana56_10);
        }
        if (isset($pana)) {
            if (is_array($pana)) {
                $returnStr = implode(", ", $pana);
            }
        }
    }
    if (strpos($returnStr, ",") === 0) {
        $returnStr = ltrim($returnStr, ",");
    }
    return $returnStr;
}

function get83Pana($number) {
    global $conn;
    $number = trim($number);
    $returnStr = "";
    $pana83_1 = array(128, 137, 146, 236, 245, 290, 380, 470, 560);
    $pana83_2 = array(138, 147, 156, 237, 246, 390, 480, 570);
    $pana83_3 = array(148, 157, 238, 247, 256, 346, 490, 580, 670);
    $pana83_4 = array(130, 158, 167, 248, 257, 347, 356, 590, 680);
    $pana83_5 = array(140, 168, 230, 258, 267, 348, 357, 690, 780);
    $pana83_6 = array(150, 178, 240, 268, 358, 367, 457, 790);
    $pana83_7 = array(124, 160, 250, 278, 340, 368, 458, 467);
    $pana83_8 = array(125, 134, 170, 260, 350, 378, 468);
    $pana83_9 = array(126, 135, 180, 270, 360, 450, 478, 568);
    $pana83_10 = array(127, 136, 145, 235, 280, 370, 460, 578);
    $pana = array();
    for ($i = 0; $i < strlen($number); $i++) {
        if ($number[$i] == 1) {
            $pana = array_merge($pana, $pana83_1);
        } elseif ($number[$i] == 2) {
            $pana = array_merge($pana, $pana83_2);
        } elseif ($number[$i] == 3) {
            $pana = array_merge($pana, $pana83_3);
        } elseif ($number[$i] == 4) {
            $pana = array_merge($pana, $pana83_4);
        } elseif ($number[$i] == 5) {
            $pana = array_merge($pana, $pana83_5);
        } elseif ($number[$i] == 6) {
            $pana = array_merge($pana, $pana83_6);
        } elseif ($number[$i] == 7) {
            $pana = array_merge($pana, $pana83_7);
        } elseif ($number[$i] == 8) {
            $pana = array_merge($pana, $pana83_8);
        } elseif ($number[$i] == 9) {
            $pana = array_merge($pana, $pana83_9);
        } elseif ($number[$i] == 0) {
            $pana = array_merge($pana, $pana83_10);
        }
        if (isset($pana)) {
            if (is_array($pana)) {
                $returnStr = implode(", ", $pana);
            }
        }
    }
    if (strpos($returnStr, ",") === 0) {
        $returnStr = ltrim($returnStr, ",");
    }
    return $returnStr;
}

function get64Pana($number) {
    global $conn;
    $number = trim($number);
    $returnStr = "";
    $pana64_1 = array(128, 137, 146, 290, 380, 470, 560);
    $pana64_2 = array(129, 138, 147, 156, 390, 480, 570);
    $pana64_3 = array(120, 139, 148, 157, 490, 580, 670);
    $pana64_4 = array(130, 149, 158, 167, 590, 680);
    $pana64_5 = array(140, 159, 168, 230, 690, 780);
    $pana64_6 = array(123, 150, 169, 178, 240, 790);
    $pana64_7 = array(124, 160, 179, 250, 340, 890);
    $pana64_8 = array(125, 134, 170, 189, 260, 350);
    $pana64_9 = array(126, 135, 180, 270, 360, 450);
    $pana64_10 = array(127, 136, 145, 190, 280, 370, 460);
    $pana = array();
    for ($i = 0; $i < strlen($number); $i++) {
        if ($number[$i] == 1) {
            $pana = array_merge($pana, $pana64_1);
        } elseif ($number[$i] == 2) {
            $pana = array_merge($pana, $pana64_2);
        } elseif ($number[$i] == 3) {
            $pana = array_merge($pana, $pana64_3);
        } elseif ($number[$i] == 4) {
            $pana = array_merge($pana, $pana64_4);
        } elseif ($number[$i] == 5) {
            $pana = array_merge($pana, $pana64_5);
        } elseif ($number[$i] == 6) {
            $pana = array_merge($pana, $pana64_6);
        } elseif ($number[$i] == 7) {
            $pana = array_merge($pana, $pana64_7);
        } elseif ($number[$i] == 8) {
            $pana = array_merge($pana, $pana64_8);
        } elseif ($number[$i] == 9) {
            $pana = array_merge($pana, $pana64_9);
        } elseif ($number[$i] == 0) {
            $pana = array_merge($pana, $pana64_10);
        }
        if (isset($pana)) {
            if (is_array($pana)) {
                $returnStr = implode(", ", $pana);
            }
        }
    }
    if (strpos($returnStr, ",") === 0) {
        $returnStr = ltrim($returnStr, ",");
    }
    return $returnStr;
}

function get68Pana($number) {
    global $conn;
    $number = trim($number);
    $returnStr = "";
    $pana68_1 = array(128, 236, 245, 290, 560, 470, 489);
    $pana68_2 = array(129, 138, 147, 156, 390, 589, 679);
    $pana68_3 = array(148, 247, 256, 346, 490, 670, 689);
    $pana68_4 = array(130, 158, 167, 239, 347, 356, 590);
    $pana68_5 = array(140, 168, 249, 267, 690, 348);
    $pana68_6 = array(150, 178, 259, 349, 367, 457, 790);
    $pana68_7 = array(124, 160, 269, 340, 368, 458, 467);
    $pana68_8 = array(125, 134, 170, 189, 279, 459, 369);
    $pana68_9 = array(126, 180, 289, 360, 450, 568, 478);
    $pana68_10 = array(127, 136, 145, 389, 479, 569);
    $pana = array();
    for ($i = 0; $i < strlen($number); $i++) {
        if ($number[$i] == 1) {
            $pana = array_merge($pana, $pana68_1);
        } elseif ($number[$i] == 2) {
            $pana = array_merge($pana, $pana68_2);
        } elseif ($number[$i] == 3) {
            $pana = array_merge($pana, $pana68_3);
        } elseif ($number[$i] == 4) {
            $pana = array_merge($pana, $pana68_4);
        } elseif ($number[$i] == 5) {
            $pana = array_merge($pana, $pana68_5);
        } elseif ($number[$i] == 6) {
            $pana = array_merge($pana, $pana68_6);
        } elseif ($number[$i] == 7) {
            $pana = array_merge($pana, $pana68_7);
        } elseif ($number[$i] == 8) {
            $pana = array_merge($pana, $pana68_8);
        } elseif ($number[$i] == 9) {
            $pana = array_merge($pana, $pana68_9);
        } elseif ($number[$i] == 0) {
            $pana = array_merge($pana, $pana68_10);
        }
        if (isset($pana)) {
            if (is_array($pana)) {
                $returnStr = implode(", ", $pana);
            }
        }
    }
    if (strpos($returnStr, ",") === 0) {
        $returnStr = ltrim($returnStr, ",");
    }
    return $returnStr;
}

function get72Pana($number) {
    global $conn;
    $number = trim($number);
    $returnStr = "";
    $pana72_1 = array(128, 146, 129, 138, 147, 156, 148, 130, 149, 158, 167, 140, 168, 150, 169, 178, 124, 160, 125, 134, 170, 189, 126, 180, 127, 136, 145);
    $pana72_2 = array(128, 236, 245, 290, 129, 237, 238, 247, 256, 239, 257, 230, 249, 258, 267, 259, 124, 250, 269, 278, 125, 279, 126, 270, 289, 235, 127);
    $pana72_3 = array(236, 380, 138, 237, 390, 238, 346, 130, 239, 347, 356, 230, 348, 349, 358, 367, 340, 368, 134, 350, 369, 378, 360, 136, 235, 370, 389);
    $pana72_4 = array(146, 245, 470, 147, 148, 247, 346, 490, 149, 347, 140, 249, 348, 349, 457, 124, 340, 458, 467, 134, 459, 450, 469, 478, 145, 479, 489);
    $pana72_5 = array(245, 560, 570, 156, 589, 256, 580, 158, 257, 356, 590, 258, 150, 259, 358, 457, 250, 458, 125, 350, 459, 450, 568, 145, 235, 569, 578);
    $pana72_6 = array(146, 236, 560, 156, 679, 256, 346, 670, 689, 167, 356, 168, 267, 690, 169, 367, 160, 269, 368, 467, 369, 126, 360, 469, 568, 136, 569);
    $pana72_7 = array(470, 147, 237, 570, 679, 247, 670, 167, 257, 347, 267, 780, 178, 367, 457, 790, 278, 467, 170, 279, 378, 270, 478, 127, 370, 479, 578);
    $pana72_8 = array(128, 380, 489, 138, 589, 148, 238, 580, 689, 158, 168, 258, 348, 780, 178, 358, 278, 368, 458, 189, 378, 180, 289, 478, 568, 389, 578);
    $pana72_9 = array(290, 489, 129, 390, 589, 679, 490, 689, 149, 239, 590, 249, 690, 169, 259, 349, 790, 269, 189, 279, 369, 459, 289, 469, 389, 479, 569);
    $pana72_10 = array(290, 380, 470, 560, 390, 570, 490, 580, 670, 130, 590, 140, 230, 690, 780, 150, 790, 160, 250, 340, 170, 350, 180, 270, 360, 450, 370);
    $pana = array();
    for ($i = 0; $i < strlen($number); $i++) {
        if ($number[$i] == 1) {
            $pana = array_merge($pana, $pana72_1);
        } elseif ($number[$i] == 2) {
            $pana = array_merge($pana, $pana72_2);
        } elseif ($number[$i] == 3) {
            $pana = array_merge($pana, $pana72_3);
        } elseif ($number[$i] == 4) {
            $pana = array_merge($pana, $pana72_4);
        } elseif ($number[$i] == 5) {
            $pana = array_merge($pana, $pana72_5);
        } elseif ($number[$i] == 6) {
            $pana = array_merge($pana, $pana72_6);
        } elseif ($number[$i] == 7) {
            $pana = array_merge($pana, $pana72_7);
        } elseif ($number[$i] == 8) {
            $pana = array_merge($pana, $pana72_8);
        } elseif ($number[$i] == 9) {
            $pana = array_merge($pana, $pana72_9);
        } elseif ($number[$i] == 0) {
            $pana = array_merge($pana, $pana72_10);
        }
        $pana = array_unique($pana);
        if (isset($pana)) {
            if (is_array($pana)) {
                $returnStr = implode(", ", $pana);
            }
        }
    }
    if (strpos($returnStr, ",") === 0) {
        $returnStr = ltrim($returnStr, ",");
    }
    return $returnStr;
}

function get50Pana($number) {
    global $conn;
    $number = trim($number);
    $returnStr = "";
    $pana50_1 = array(290, 380, 470, 560, 100);
    $pana50_2 = array(129, 138, 147, 156, 110);
    $pana50_3 = array(120, 238, 247, 256, 229);
    $pana50_4 = array(130, 239, 347, 356, 338);
    $pana50_5 = array(140, 249, 348, 456, 447);
    $pana50_6 = array(150, 259, 358, 457, 556);
    $pana50_7 = array(160, 269, 368, 467, 566);
    $pana50_8 = array(170, 279, 378, 567, 477);
    $pana50_9 = array(180, 289, 478, 568, 388);
    $pana50_10 = array(190, 389, 479, 569, 299);
    $pana = array();
    for ($i = 0; $i < strlen($number); $i++) {
        if ($number[$i] == 1) {
            $pana = array_merge($pana, $pana50_1);
        } elseif ($number[$i] == 2) {
            $pana = array_merge($pana, $pana50_2);
        } elseif ($number[$i] == 3) {
            $pana = array_merge($pana, $pana50_3);
        } elseif ($number[$i] == 4) {
            $pana = array_merge($pana, $pana50_4);
        } elseif ($number[$i] == 5) {
            $pana = array_merge($pana, $pana50_5);
        } elseif ($number[$i] == 6) {
            $pana = array_merge($pana, $pana50_6);
        } elseif ($number[$i] == 7) {
            $pana = array_merge($pana, $pana50_7);
        } elseif ($number[$i] == 8) {
            $pana = array_merge($pana, $pana50_8);
        } elseif ($number[$i] == 9) {
            $pana = array_merge($pana, $pana50_9);
        } elseif ($number[$i] == 0) {
            $pana = array_merge($pana, $pana50_10);
        }
        if (isset($pana)) {
            if (is_array($pana)) {
                $returnStr = implode(", ", $pana);
            }
        }
    }
    if (strpos($returnStr, ",") === 0) {
        $returnStr = ltrim($returnStr, ",");
    }
    return $returnStr;
}

function getabr30Pana($number) {
    global $conn;
    $number = trim($number);
    $returnStr = "";
    $pana30_1 = array(678, 579, 137);
    $pana30_2 = array(345, 246, 480);
    $pana30_3 = array(120, 139, 157);
    $pana30_4 = array(789, 680, 248);
    $pana30_5 = array(456, 357, 159);
    $pana30_6 = array(123, 240, 268);
    $pana30_7 = array(890, 179, 359);
    $pana30_8 = array(567, 468, 260);
    $pana30_9 = array(234, 135, 379);
    $pana30_10 = array(190, 280, 460);
    $pana = array();
    for ($i = 0; $i < strlen($number); $i++) {
        if ($number[$i] == 1) {
            $pana = array_merge($pana, $pana30_1);
        } elseif ($number[$i] == 2) {
            $pana = array_merge($pana, $pana30_2);
        } elseif ($number[$i] == 3) {
            $pana = array_merge($pana, $pana30_3);
        } elseif ($number[$i] == 4) {
            $pana = array_merge($pana, $pana30_4);
        } elseif ($number[$i] == 5) {
            $pana = array_merge($pana, $pana30_5);
        } elseif ($number[$i] == 6) {
            $pana = array_merge($pana, $pana30_6);
        } elseif ($number[$i] == 7) {
            $pana = array_merge($pana, $pana30_7);
        } elseif ($number[$i] == 8) {
            $pana = array_merge($pana, $pana30_8);
        } elseif ($number[$i] == 9) {
            $pana = array_merge($pana, $pana30_9);
        } elseif ($number[$i] == 0) {
            $pana = array_merge($pana, $pana30_10);
        }
        if (isset($pana)) {
            if (is_array($pana)) {
                $returnStr = implode(", ", $pana);
            }
        }
    }
    if (strpos($returnStr, ",") === 0) {
        $returnStr = ltrim($returnStr, ",");
    }
    return $returnStr;
}

function get40Pana($number) {
    global $conn;
    $number = trim($number);
    $returnStr = "";
    $pana40_1 = array(128, 236, 245, 290);
    $pana40_2 = array(129, 390, 589, 679);
    $pana40_3 = array(256, 346, 670, 689);
    $pana40_4 = array(130, 239, 347, 356);
    $pana40_5 = array(140, 230, 690, 780);
    $pana40_6 = array(178, 367, 457, 790);
    $pana40_7 = array(124, 340, 458, 467);
    $pana40_8 = array(125, 134, 170, 189);
    $pana40_9 = array(180, 289, 478, 568);
    $pana40_10 = array(145, 235, 569, 578);
    $pana = array();
    for ($i = 0; $i < strlen($number); $i++) {
        if ($number[$i] == 1) {
            $pana = array_merge($pana, $pana40_1);
        } elseif ($number[$i] == 2) {
            $pana = array_merge($pana, $pana40_2);
        } elseif ($number[$i] == 3) {
            $pana = array_merge($pana, $pana40_3);
        } elseif ($number[$i] == 4) {
            $pana = array_merge($pana, $pana40_4);
        } elseif ($number[$i] == 5) {
            $pana = array_merge($pana, $pana40_5);
        } elseif ($number[$i] == 6) {
            $pana = array_merge($pana, $pana40_6);
        } elseif ($number[$i] == 7) {
            $pana = array_merge($pana, $pana40_7);
        } elseif ($number[$i] == 8) {
            $pana = array_merge($pana, $pana40_8);
        } elseif ($number[$i] == 9) {
            $pana = array_merge($pana, $pana40_9);
        } elseif ($number[$i] == 0) {
            $pana = array_merge($pana, $pana40_10);
        }
        if (isset($pana)) {
            if (is_array($pana)) {
                $returnStr = implode(", ", $pana);
            }
        }
    }
    if (strpos($returnStr, ",") === 0) {
        $returnStr = ltrim($returnStr, ",");
    }
    return $returnStr;
}

function getkotouchfailPana($number) {
    global $conn;
    $number = trim($number);
    $returnStr = "";
    $bikhre1 = array(128, 137, 146, 236, 245, 290, 470, 489, 560, 579, 678);
    $bikhre2 = array(129, 138, 147, 156, 246, 345, 390, 480, 589, 679);
    $bikhre3 = array(120, 139, 148, 157, 247, 256, 346, 490, 670, 689);
    $bikhre4 = array(130, 149, 158, 167, 239, 248, 347, 356, 590, 680, 789);
    $bikhre5 = array(140, 159, 168, 249, 267, 348, 456, 690);
    $bikhre6 = array(123, 150, 169, 178, 240, 259, 268, 349, 367, 457, 790);
    $bikhre7 = array(124, 160, 179, 269, 340, 359, 368, 458, 467, 890);
    $bikhre8 = array(125, 134, 170, 189, 260, 279, 369, 459, 468, 567);
    $bikhre9 = array(126, 135, 180, 234, 289, 360, 379, 450, 469, 478, 568);
    $bikhre10 = array(127, 136, 145, 190, 389, 460, 479, 569);
    $pana = array();
    for ($i = 0; $i < strlen($number); $i++) {
        if ($number[$i] == 1) {
            $pana = array_merge($pana, $bikhre1);
        } elseif ($number[$i] == 2) {
            $pana = array_merge($pana, $bikhre2);
        } elseif ($number[$i] == 3) {
            $pana = array_merge($pana, $bikhre3);
        } elseif ($number[$i] == 4) {
            $pana = array_merge($pana, $bikhre4);
        } elseif ($number[$i] == 5) {
            $pana = array_merge($pana, $bikhre5);
        } elseif ($number[$i] == 6) {
            $pana = array_merge($pana, $bikhre6);
        } elseif ($number[$i] == 7) {
            $pana = array_merge($pana, $bikhre7);
        } elseif ($number[$i] == 8) {
            $pana = array_merge($pana, $bikhre8);
        } elseif ($number[$i] == 9) {
            $pana = array_merge($pana, $bikhre9);
        } elseif ($number[$i] == 0) {
            $pana = array_merge($pana, $bikhre10);
        }
        if (isset($pana)) {
            if (is_array($pana)) {
                $returnStr = implode(", ", $pana);
            }
        }
    }
    if (strpos($returnStr, ",") === 0) {
        $returnStr = ltrim($returnStr, ",");
    }
    return $returnStr;
}

function getabrcut90Pana($number) {
    global $conn;
    $number = trim($number);
    $returnStr = "";
    $panaabr_1 = array(128, 146, 236, 245, 290, 380, 470, 489, 560);
    $panaabr_2 = array(129, 138, 147, 156, 237, 390, 570, 589, 679);
    $panaabr_3 = array(148, 238, 247, 256, 346, 490, 580, 670, 689);
    $panaabr_4 = array(130, 149, 158, 167, 239, 257, 347, 356, 590);
    $panaabr_5 = array(140, 168, 230, 249, 258, 267, 348, 690, 780);
    $panaabr_6 = array(150, 169, 178, 259, 349, 358, 367, 457, 790);
    $panaabr_7 = array(124, 160, 250, 269, 278, 340, 368, 458, 467);
    $panaabr_8 = array(125, 134, 170, 189, 279, 350, 369, 378, 459);
    $panaabr_9 = array(126, 180, 270, 289, 360, 450, 469, 478, 568);
    $panaabr_10 = array(127, 136, 145, 235, 370, 389, 479, 569, 578);
    $pana = array();
    for ($i = 0; $i < strlen($number); $i++) {
        if ($number[$i] == 1) {
            $pana = array_merge($pana, $panaabr_1);
        } elseif ($number[$i] == 2) {
            $pana = array_merge($pana, $panaabr_2);
        } elseif ($number[$i] == 3) {
            $pana = array_merge($pana, $panaabr_3);
        } elseif ($number[$i] == 4) {
            $pana = array_merge($pana, $panaabr_4);
        } elseif ($number[$i] == 5) {
            $pana = array_merge($pana, $panaabr_5);
        } elseif ($number[$i] == 6) {
            $pana = array_merge($pana, $panaabr_6);
        } elseif ($number[$i] == 7) {
            $pana = array_merge($pana, $panaabr_7);
        } elseif ($number[$i] == 8) {
            $pana = array_merge($pana, $panaabr_8);
        } elseif ($number[$i] == 9) {
            $pana = array_merge($pana, $panaabr_9);
        } elseif ($number[$i] == 0) {
            $pana = array_merge($pana, $panaabr_10);
        }
        if (isset($pana)) {
            if (is_array($pana)) {
                $returnStr = implode(", ", $pana);
            }
        }
    }
    if (strpos($returnStr, ",") === 0) {
        $returnStr = ltrim($returnStr, ",");
    }
    return $returnStr;
}

function getSheet($number) {
    global $conn;
    $returnStr = "";
    $number = trim($number);
    $sql_user = "SELECT GROUP_CONCAT(`comnd_number` SEPARATOR ',') As li_pana FROM  li_family_command where comnd_number Like '%$number%' ";
    $result_game = $conn->query($sql_user);
    while ($row_user = $result_game->fetch_assoc()) {
        $returnStr = $returnStr . "," . $row_user["li_pana"];
    }
    if (strpos($returnStr, ",") === 0) {
        $returnStr = ltrim($returnStr, ",");
    }
    return $returnStr;
}

/**
 * getFamilyJodi: li_family_command se (jodi/2-digit based family)
 */
function getFamilyJodi($number) {
    global $conn;
    $returnStr = "";
    $number = trim($number);

    if ($number === '') {
        return "";
    }

    $num112 = str_split($number);
    if (isset($num112[0]) && isset($num112[1]) && ($num112[0] == '0') && ($num112[1] == '0')) {
        $number = 55;
    }

    $q = $conn->query("
        SELECT comnd_number
        FROM li_family_command
        WHERE comnd_string = '$number'
        AND comnd_status = 1
        LIMIT 1
    ");
    if ($q && $q->num_rows == 0) {
        $q = $conn->query("
            SELECT comnd_number
            FROM li_family_command
            WHERE comnd_number LIKE '%$number%'
            AND comnd_status = 1
            LIMIT 1
        ");
    }
    if ($q) {
        while ($r = $q->fetch_assoc()) {
            $returnStr = $returnStr . "," . $r["comnd_number"];
        }
    }
    if (strpos($returnStr, ",") === 0) {
        $returnStr = ltrim($returnStr, ",");
    }
    return $returnStr;
}

/**
 * getFamily: KBC.php jaisa - li_pana.check_family LIKE, GROUP_CONCAT(pana)
 */
function getFamily($number) {
    global $conn;
    $returnStr = "";
    $number = trim($number);

    $sql_user = "SELECT GROUP_CONCAT(`pana` SEPARATOR ',') As li_pana FROM li_pana where check_family Like '%$number%' ";
    $result_game = $conn->query($sql_user);

    while ($row_user = $result_game->fetch_assoc()) {
        $returnStr = $returnStr . "," . $row_user["li_pana"];
    }
    if (strpos($returnStr, ",") === 0) {
        $returnStr = ltrim($returnStr, ",");
    }
    return $returnStr;
}

function detectBetPatternAndNumbers($strin) {

    $instr = $instr_dp = $instr_sheet = $instr_family = '';
    $strin22 = '';

    // Normalize string
    $strin = strtoupper(trim($strin));

    // Define patterns (KEEP SAME NAMING)
    $pattern_sp     = 'SP';
    $pattern_DP     = 'DP';
    $pattern_SHEET  = 'SHEET';
    $pattern_family = 'FAMILY';

    /* ===============================
     * PATTERN DETECTION
     * =============================== */
    if (strpos($strin, $pattern_sp) !== false) {
        $instr = $strin;
    }

    if (strpos($strin, $pattern_DP) !== false) {
        $instr_dp = $strin;
    }

    if (strpos($strin, $pattern_SHEET) !== false) {
        $instr_sheet = $strin;
    }

    if (strpos($strin, $pattern_family) !== false) {
        $instr_family = $strin;
    }

    /* ===============================
     * NUMBER EXTRACTION (PRIORITY)
     * =============================== */
    if ($instr != '') {
        $strin22 = preg_replace("/[^0-9]/", "", $instr);
        return array('type' => 'SP', 'numbers' => $strin22);
    }

    if ($instr_dp != '') {
        $strin22 = preg_replace("/[^0-9]/", "", $instr_dp);
        return array('type' => 'DP', 'numbers' => $strin22);
    }

    if ($instr_sheet != '') {
        $strin22 = preg_replace("/[^0-9]/", "", $instr_sheet);
        return array('type' => 'SHEET', 'numbers' => $strin22);
    }

    if ($instr_family != '') {
        $strin22 = preg_replace("/[^0-9]/", "", $instr_family);
        return array('type' => 'FAMILY', 'numbers' => $strin22);
    }

    return false;
}


function detectInlinePatternBet($line) {
    $lineOriginal = trim($line);
    $line = strtolower($lineOriginal);
    
    // Pattern detection flags
    $has_sp = (strpos($line, 'sp') !== false);
    $has_dp = (strpos($line, 'dp') !== false);
    $has_sheet = (strpos($line, 'sheet') !== false);
    $has_family = (strpos($line, 'family') !== false);
    
    if (!$has_sp && !$has_dp && !$has_sheet && !$has_family) {
        return false;
    }
    
    // Extract amount: ya to = ke baad, ya bina = ke last number (pehle jaisa: "dp 9 1" = dp 9=1)
    $amount = '';
    $numbers = array();
    if (preg_match('/=\s*(\d+)/', $line, $amtMatch)) {
        $amtVal = (int)$amtMatch[1];
        if ($amtVal <= 0 || $amtVal > 999999) return false;
        $amount = $amtMatch[1];
        $numStr = preg_replace('/[a-zA-Z]/', '', $lineOriginal);
        $delimiters = array('=', '*', '-', '+', ',', '.', ':', ' ');
        $numStrBeforeEq = explode('=', $numStr)[0];
        $numbers = preg_split('/[' . preg_quote(implode('', $delimiters), '/') . ']+/', $numStrBeforeEq);
    } else {
        // bina = : "dp 9 1" → last number = amount, rest = numbers
        preg_match_all('/\d+/', $lineOriginal, $m);
        $tokens = isset($m[0]) ? $m[0] : array();
        if (count($tokens) >= 2) {
            $amount = array_pop($tokens);
            $amtVal = (int)$amount;
            if ($amtVal <= 0 || $amtVal > 999999) return false;
            $numbers = $tokens;
        } else {
            return false;
        }
    }
    
    // Filter empty values
    $numbers = array_filter($numbers, 'strlen');
    $numbers = array_values($numbers);
    
    if (empty($numbers)) {
        return false;
    }
    
    // Determine pattern type (priority: SP > DP > SHEET > FAMILY)
    $pattern = '';
    if ($has_sp) {
        $pattern = 'SP';
    } elseif ($has_dp) {
        $pattern = 'DP';
    } elseif ($has_sheet) {
        $pattern = 'SHEET';
    } elseif ($has_family) {
        $pattern = 'FAMILY';
    }
    
    return array(
        'pattern' => $pattern,
        'numbers' => $numbers,
        'amount'  => $amount
    );
}

function extractBetsWithPatterns($input) {

    $lines = preg_split('/\r\n|\n/', trim($input));
    $normalLines = array();
    $patternBets = array();

    foreach ($lines as $line) {
        $inline = detectInlinePatternBet($line);
        if ($inline !== false) {
            $patternBets[] = $inline;
        } else {
            $normalLines[] = $line;
        }
    }

    return array(
        'normal'  => extractNumberAmountPairs(implode("\n", $normalLines)),
        'pattern' => $patternBets
    );
}



function expandPatternBetToPana($pattern, $numbers, $amount, $conn) {

    $result = array();
    $amtVal = (int)$amount;
    if ($amtVal <= 0 || $amtVal > 999999) return $result;  // invalid amount

    foreach ($numbers as $num) {

        if ($num === '') continue;
        
        // Handle 0 -> 10 conversion
        if ($num == '0' && $num != '00') {
            $num = 10;
        }

        /* ============ FAMILY (KBC style: li_pana.check_family LIKE) ============ */
        if ($pattern === 'FAMILY') {
            $q = $conn->query("
                SELECT pana FROM li_pana WHERE check_family LIKE '%$num%'
            ");
            $added = array();
            if ($q) {
                while ($r = $q->fetch_assoc()) {
                    $p = trim($r['pana']);
                    if ($p != '' && !isset($added[$p])) {
                        $added[$p] = true;
                        $result[] = $p . '=' . $amount;
                    }
                }
            }
            continue;
        }

        /* ============ SHEET ============ */
        if ($pattern === 'SHEET') {

            // SHEET uses first 2 digits of the number
            $sheet = str_split($num);
            if (count($sheet) < 2) {
                continue; // Need at least 2 digits for SHEET
            }
            
            // Only get active pana (status = 1)
            $q = $conn->query("SELECT pana FROM li_pana WHERE status = 1");

            if ($q) {
                while ($r = $q->fetch_assoc()) {
                    $p = str_split($r['pana']);
                    
                    if (count($p) < 3) continue; // Pana must be 3 digits

                    // Match first 2 digits of number with pana digits
                    if (
                        ($p[0]==$sheet[0] && $p[1]==$sheet[1]) ||
                        ($p[1]==$sheet[0] && $p[2]==$sheet[1]) ||
                        ($p[0]==$sheet[0] && $p[2]==$sheet[1])
                    ) {
                        $result[] = $r['pana'].'='.$amount;
                    }
                }
            }
            continue;
        }

        /* ============ SP / DP ============ */
        $type = ($pattern === 'SP') ? 1 : 2;

        $q = $conn->query("
            SELECT pana 
            FROM li_pana 
            WHERE number_main = '$num'
            AND pana_type = $type
            AND status = 1
        ");

        if ($q) {
            while ($r = $q->fetch_assoc()) {

                $d = str_split($r['pana']);
                
                // Safety check: pana must be 3 digits
                if (count($d) < 3) continue;

                // Double-check filtering (matching old code behavior)
                if ($pattern === 'SP') {
                    // SP: all 3 digits must be different
                    if ($d[0]!=$d[1] && $d[1]!=$d[2]) {
                        $result[] = $r['pana'].'='.$amount;
                    }
                } else {
                    // DP: at least 2 digits must be same
                    if ($d[0]==$d[1] || $d[1]==$d[2] || $d[0]==$d[2]) {
                        $result[] = $r['pana'].'='.$amount;
                    }
                }
            }
        }
    }

    return $result; // array of "pana=amount"
}

/* =================================================
 * 🔹 MSSQL FUNCTIONS
 * ================================================= */

function getMSSQLConnection() {
    // MSSQL credentials
    $sqlServer   = getenv('MSSQL_SERVER') ?: "WIN-80G6G21E276\\SQLEXPRESS";
    $sqlDatabase = getenv('MSSQL_DB')     ?: "SHREEDBSQL";
    $sqlUser     = getenv('MSSQL_USER')   ?: "sa";
    $sqlPass     = getenv('MSSQL_PASS')   ?: "sonu@123";

    // Check PDO driver
    if (!in_array('sqlsrv', PDO::getAvailableDrivers())) {
        error_log("PDO sqlsrv driver not installed");
        return null;
    }

    try {
        $pdo = new PDO(
            "sqlsrv:Server={$sqlServer};Database={$sqlDatabase}",
            $sqlUser,
            $sqlPass,
            [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC]
        );
        return $pdo;
    } catch (Exception $e) {
        error_log("MSSQL connect error: " . $e->getMessage());
        return null;
    }
}

/**
 * MySQL li_active_game se current active game + open/close time uthao.
 * Returns: array('mssql_game_id'=>int|null,'game_name'=>string|null,'open_time'=>string|null,'close_time'=>string|null)
 */
function getActiveGameFromMySQL($conn) {
    $out = array('mssql_game_id' => null, 'game_name' => null, 'open_time' => null, 'close_time' => null);
    if (!$conn) return $out;

    // Ensure row exists
    $conn->query("INSERT INTO li_active_game (id, mssql_game_id, game_name, updated_at) VALUES (1, NULL, NULL, NULL) ON DUPLICATE KEY UPDATE id=id");

    $q = $conn->query("SELECT mssql_game_id, game_name, open_time, close_time FROM li_active_game WHERE id=1 LIMIT 1");
    if ($q && $q->num_rows > 0) {
        $r = $q->fetch_assoc();
        $out['mssql_game_id'] = isset($r['mssql_game_id']) && $r['mssql_game_id'] !== null && $r['mssql_game_id'] !== '' ? (int)$r['mssql_game_id'] : null;
        $out['game_name'] = isset($r['game_name']) ? $r['game_name'] : null;
        $out['open_time'] = isset($r['open_time']) ? $r['open_time'] : null;   // TIME like HH:MM:SS
        $out['close_time'] = isset($r['close_time']) ? $r['close_time'] : null; // TIME like HH:MM:SS
    }
    return $out;
}

/**
 * MSSQL TbNewGame me check karo open result declared hai ya nahi.
 * Open result column: N_OpanPana1
 */
function isOpenResultDeclaredMSSQL($pdo, $gameId) {
    if (!$pdo || !is_numeric($gameId) || (int)$gameId <= 0) return false;
    try {
        $stmt = $pdo->prepare("SELECT TOP (1) N_OpanPana1 FROM TbNewGame WHERE N_Id = :id");
        $stmt->execute(array(':id' => (int)$gameId));
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$row) return false;
        $val = isset($row['N_OpanPana1']) ? trim((string)$row['N_OpanPana1']) : '';
        return ($val !== '' && $val !== '0' && $val !== '-');
    } catch (Exception $e) {
        error_log("isOpenResultDeclaredMSSQL error: " . $e->getMessage());
        return false;
    }
}

/**
 * Active game decide + bet type decide (OPEN/CLOSE) based on MySQL times + MSSQL open result.
 *
 * Rules:
 * - Active game must exist in li_active_game.mssql_game_id
 * - If close_time set and now > close_time => time over close bet
 * - If open_time not set OR now < open_time => OPEN
 * - If now >= open_time AND open result NOT declared => time over for open bet
 * - Else => CLOSE (until close_time, if provided)
 *
 * Returns: array($manual_game_id, $gameName, $bettype_opcl_id, $timeOverMsg)
 *   bettype_opcl_id: 1=OPEN, 2=CLOSE
 */
function resolveActiveGameAndBetType($conn, $pdoMSSQL) {
    date_default_timezone_set('Asia/Kolkata');

    $active = getActiveGameFromMySQL($conn);
    $gid = isset($active['mssql_game_id']) ? $active['mssql_game_id'] : null;
    $gname = isset($active['game_name']) ? trim((string)$active['game_name']) : '';
    $openTime = isset($active['open_time']) ? trim((string)$active['open_time']) : '';
    $closeTime = isset($active['close_time']) ? trim((string)$active['close_time']) : '';

    if ($gid === null || (int)$gid <= 0) {
        return array(null, '', 1, 'No active game. Admin se pehle game Start karo.');
    }

    // Build today's timestamps for open/close (if provided)
    $today = date('Y-m-d');
    $nowTs = time();

    $openTs = null;
    if ($openTime !== '') {
        $openTs = strtotime($today . ' ' . substr($openTime, 0, 8));
    }
    $closeTs = null;
    if ($closeTime !== '') {
        $closeTs = strtotime($today . ' ' . substr($closeTime, 0, 8));
    }

    // Close time passed?
    if ($closeTs !== null && $nowTs > $closeTs) {
        return array((int)$gid, $gname, 2, 'Time over for close bet');
    }

    // Before open_time OR open_time not set => OPEN
    if ($openTs === null || $nowTs < $openTs) {
        return array((int)$gid, $gname, 1, '');
    }

    // After open_time: if open result not declared => open time over
    $openDeclared = isOpenResultDeclaredMSSQL($pdoMSSQL, (int)$gid);
    if (!$openDeclared) {
        return array((int)$gid, $gname, 1, 'Time over for open bet');
    }

    // Open declared => CLOSE (until close_time if set)
    return array((int)$gid, $gname, 2, '');
}

function exportTbPartyByMobileMSSQL($mobile) {
    // Normalize mobile (keep digits only)
    $mobile = preg_replace('/\D+/', '', (string)$mobile);
    if ($mobile === '') {
        return array();
    }

    $pdo = getMSSQLConnection();
    if (!$pdo) {
        return array();
    }

    try {
        $sql = "SELECT * FROM TbParty WHERE number = :m";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([':m' => $mobile]);
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        return $rows ? $rows : array();
    } catch (Exception $e) {
        error_log("Query error: " . $e->getMessage());
        return array();
    }
}

function getRateFromPartyData($partyData, $child_num) {
    global $conn; // MySQL connection for li_pana query
    
    // Default rate
    $rate = 9;
    
    if (empty($partyData) || !isset($partyData[0])) {
        error_log("getRateFromPartyData: No party data provided, using default rate 9");
        return $rate;
    }
    
    $party = $partyData[0];
    $numLen = strlen($child_num);

    // Return first valid positive numeric rate from given keys
    $pickRate = function($row, $keys, $defaultRate) {
        foreach ($keys as $k) {
            if (isset($row[$k]) && $row[$k] !== '' && is_numeric($row[$k])) {
                $v = (float)$row[$k];
                if ($v > 0) {
                    return $v;
                }
            }
        }
        return $defaultRate;
    };
    
    if ($numLen == 1) {
        // AKD - use p_rakd
        $rate = $pickRate($party, array('p_rakd'), 9);
        error_log("getRateFromPartyData: AKD rate from p_rakd = $rate");
        
    } elseif ($numLen == 2) {
        // Jodi - PRIMARY p_rjodi, fallback p_rpati
        $rate = $pickRate($party, array('p_rjodi', 'p_rpati'), 9);
        error_log("getRateFromPartyData: Jodi rate = $rate");
        
    } elseif ($numLen == 3) {
        // Pana - need to check if SP, DP, or TP by querying li_pana table (MySQL)
        if ($conn) {
            try {
                $pana_detais = "SELECT pana_type FROM li_pana WHERE pana='$child_num' LIMIT 1";
                $get_panad = $conn->query($pana_detais);
                
                if ($get_panad && $get_panad->num_rows > 0) {
                    $ftpana = $get_panad->fetch_assoc();
                    $pana_type = (int)$ftpana['pana_type'];
                    
                    if ($pana_type == 1) {
                        // SP - use p_rsp
                        $rate = $pickRate($party, array('p_rsp'), 9);
                        error_log("getRateFromPartyData: SP rate from p_rsp = $rate");
                    } elseif ($pana_type == 2) {
                        // DP - use p_rdp
                        $rate = $pickRate($party, array('p_rdp'), 9);
                        error_log("getRateFromPartyData: DP rate from p_rdp = $rate");
                    } elseif ($pana_type == 3) {
                        // TP - use p_rtp
                        $rate = $pickRate($party, array('p_rtp'), 9);
                        error_log("getRateFromPartyData: TP rate from p_rtp = $rate");
                    } else {
                        // Default Pana rate
                        $rate = $pickRate($party, array('p_rpati'), 9);
                        error_log("getRateFromPartyData: Unknown pana_type ($pana_type), using default = $rate");
                    }
                } else {
                    // Pana not found in li_pana, use default
                    $rate = $pickRate($party, array('p_rpati'), 9);
                    error_log("getRateFromPartyData: Pana not found in li_pana, using default = $rate");
                }
            } catch (Exception $e) {
                error_log("getRateFromPartyData: Error checking pana_type: " . $e->getMessage());
                $rate = $pickRate($party, array('p_rpati'), 9);
            }
        } else {
            // No MySQL connection, use default Pana rate
            $rate = $pickRate($party, array('p_rpati'), 9);
            error_log("getRateFromPartyData: No MySQL connection for Pana check, using default = $rate");
        }
    }
    
    return $rate;
}

function insertBetToMSSQL($pdo, $child_num, $child_amount, $A_Mode, $A_AKD, $A_Party, $mobile, $partyData = array()) {
    
    // Determine A_Type based on number length
    $A_Type = '';
    $numLen = strlen($child_num);
    
    if ($numLen == 1) {
        $A_Type = 'AKD';
    } elseif ($numLen == 2) {
        $A_Type = 'Jodi';
    } elseif ($numLen == 3) {
        $A_Type = 'Pana';
    } else {
        $A_Type = 'AKD'; // Default fallback
    }
    
    // Get dynamic rate from TbParty data
    $A_Rate = getRateFromPartyData($partyData, $child_num);
    
    // Default values (matching ciProjFunction.txt)
    $A_KL = '';
    $A_Balan = 0;
    $A_Yes = 0;
    $A_No = 0;
    $A_Delete = 0;
    $A_CheckEntry = 0;
    $A_Pass = '0';
    $A_Resalt = '0';
    $On_ID = $A_AKD; // Game ID
    $A_Modify = '0';
    
    try {
        $pdo->beginTransaction();
        
        // Compute next A_Sr for the given A_AKD
        $stmt = $pdo->prepare("SELECT ISNULL(MAX(ISNULL(A_Sr,0)),0) + 1 AS next_sr FROM TbAKADA WHERE A_AKD = :A_AKD");
        $stmt->execute([':A_AKD' => $A_AKD]);
        $row = $stmt->fetch();
        $A_Sr = $row ? (int)$row['next_sr'] : 1;
        
        // Insert into TbAKADA table
        $insertSql = "
            INSERT INTO TbAKADA
            ([A_AKD],[A_Sr],[A_Party],[A_Mode],[A_KL],[A_Type],[A_Rate],[A_Amount],[A_AKDNo],[A_Balan],[A_Yes],[A_No],[A_Delete],[A_Modify],[A_CheckEntry],[A_Date],[A_time],[A_Pass],[A_Resalt],[On_ID])
            VALUES
            (:A_AKD, :A_Sr, :A_Party, :A_Mode, :A_KL, :A_Type, :A_Rate, :A_Amount, :A_AKDNo, :A_Balan, :A_Yes, :A_No, :A_Delete, :A_Modify, :A_CheckEntry, CAST(GETDATE() AS DATE), CONVERT(VARCHAR(8), GETDATE(), 108), :A_Pass, :A_Resalt, :On_ID)
        ";
        
        $stmt = $pdo->prepare($insertSql);
        $stmt->execute(array(
            ':A_AKD' => $A_AKD,
            ':A_Sr' => $A_Sr,
            ':A_Party' => $A_Party,
            ':A_Mode' => $A_Mode,
            ':A_KL' => $A_KL,
            ':A_Type' => $A_Type,
            ':A_Rate' => $A_Rate,
            ':A_Amount' => $child_amount,
            ':A_AKDNo' => $child_num,
            ':A_Balan' => $A_Balan,
            ':A_Yes' => $A_Yes,
            ':A_No' => $A_No,
            ':A_Delete' => $A_Delete,
            ':A_Modify' => $A_Modify,
            ':A_CheckEntry' => $A_CheckEntry,
            ':A_Pass' => $A_Pass,
            ':A_Resalt' => $A_Resalt,
            ':On_ID' => $On_ID
        ));
        
        $pdo->commit();
        return true;
        
    } catch (Exception $e) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        error_log("MSSQL insert error: " . $e->getMessage());
        return false;
    }
}