<?php

// Telegram Bot Token
$botToken = '8320212005:AAHuf25AqokFy-UteVmaZxQA7-Z3EA_MBh0';

// Get update from Telegram (using polling for simplicity; in production, use webhook)
$update = json_decode(file_get_contents('php://input'), true);

// Check if there's a message
if (isset($update['message'])) {
    $chatId = $update['message']['chat']['id'];
    $messageText = trim($update['message']['text']);

    // Parse the input message
    $lines = explode("\n", $messageText);
    $entries = [];
    $extremePrice = null;

 // No filtering of empty lines here, we keep them for logic
// Last line is extreme price (must have exactly one number)
$lastLine = trim($lines[count($lines)-1]);
$lastParts = preg_split('/\s+/', $lastLine);
if (count($lastParts) == 1) {
    $extremePrice = floatval($lastParts[0]);
} else {
    sendMessage($chatId, "خط آخر باید فقط یک عدد (قیمت حد سود) باشه!");
    exit;
}

// Check for empty line presence (the new mode trigger)
$hasEmptyLine = in_array('', $lines) || in_array(' ', $lines); // Check for both completely empty and space-only lines

    if (count($lines) < 2) {
        sendMessage($chatId, "لطفاً حداقل دو خط وارد کنید:\nقیمت1 [حجم1]\n...\nقیمت_حد_ضرر");
        exit;
    }

    // Last line is extreme price (must have exactly one number)
    $lastLine = trim($lines[count($lines)-1]);
    $lastParts = preg_split('/\s+/', $lastLine);
    if (count($lastParts) == 1) {
        $extremePrice = floatval($lastParts[0]);
    } else {
        sendMessage($chatId, "خط آخر باید فقط یک عدد (قیمت حد ضرر) باشه!");
        exit;
    }

    // Process all lines except the last one as entries
    for ($i = 0; $i < count($lines) - 1; $i++) {
        $line = trim($lines[$i]);
        $parts = preg_split('/\s+/', $line);
        if (count($parts) >= 1) {
            $price = floatval($parts[0]);
            $volume = (count($parts) > 1) ? floatval($parts[1]) : 0.01; // Default volume: 0.01
            $entries[] = ['price' => $price, 'volume' => $volume];
        }
    }

    // Validate input
    if (empty($entries) || $extremePrice === null) {
        
        sendMessage($chatId, "لطفاً ورودی رو درست وارد کنید:\nقیمت1 [حجم1]\n...\nقیمت_حد_ضرر");
        exit;
    }
    
    //*****************************************************
    // Validate input
if (empty($entries) || $extremePrice === null) {
    
    sendMessage($chatId, "لطفاً ورودی رو درست وارد کنید:\nقیمت1 [حجم1]\n...\nقیمت_حد_ضرر");
    exit;
}
//*****************************************************

// **اینجا منطق جدید (حالت خط خالی) را اضافه کنید**
if ($hasEmptyLine) {
    
    $entries = [];
    $linesToProcess = array_slice($lines, 0, count($lines) - 1); // Exclude last line (TP)

    // Process all lines except the last one as entries
    foreach ($linesToProcess as $line) {
        $line = trim($line);
        if ($line === '') continue; // Skip the single empty line

        $parts = preg_split('/\s+/', $line);
        if (count($parts) >= 1) {
            $price = floatval($parts[0]);
            $volume = (count($parts) > 1) ? floatval($parts[1]) : 0.01; // Default volume: 0.01
            $entries[] = ['price' => $price, 'volume' => $volume];
        }
    }

    if (count($entries) < 2) {
        sendMessage($chatId, "در حالت سطر خالی، باید حداقل دو قیمت ورود و یک قیمت حد سود (جمعاً حداقل 3 خط) وارد کنید.");
        exit;
    }

    // Determine direction based on first two non-empty prices
    $price1 = $entries[0]['price'];
    $price2 = $entries[1]['price'];
    
    $direction = '';
    if ($price1 < $price2) {
        $direction = 'فروش (Short)';
    } elseif ($price1 > $price2) {
        $direction = 'خرید (Long)';
    } else {
        sendMessage($chatId, "دو قیمت اول برابرند، جهت معامله مشخص نیست.");
        exit;
    }

    // TP is the last line (stored in $extremePrice)
    $targetPrice = $extremePrice;

    // Calculate total profit
    $totalProfit = 0;
    foreach ($entries as $entry) {
        $volume = $entry['volume'];
        $entryPrice = $entry['price'];

        if ($direction === 'خرید (Long)') {
            $profit = $volume * 100 * ($targetPrice - $entryPrice);
        } else { // فروش (Short)
            $profit = $volume * 100 * ($entryPrice - $targetPrice);
        }
        $totalProfit += $profit;
    }

    // Calculate total volume and weighted average (for break-even)
    $totalVolume = 0;
    $weightedSum = 0;
    foreach ($entries as $entry) {
        $totalVolume += $entry['volume'];
        $weightedSum += $entry['volume'] * $entry['price'];
    }
    $averageEntry = $weightedSum / $totalVolume;

    // Send response
    $response = "📊 معامله: $direction (حالت سطر خالی)\n";
    $response .= "🔢 تعداد: " . count($entries) . "\n";
    $response .= "📈 میانگین ورود: " . number_format($averageEntry, 2) . "\n";
    $response .= "🎯 قیمت حد سود (TP): " . number_format($targetPrice, 2) . "\n";
    $response .= "\n💰 سود کل در TP: " . number_format($totalProfit, 2) . " دلار";
    $response .= "\n📌 قیمت سربه‌سر: " . number_format($averageEntry, 2);
    
    sendMessage($chatId, $response);
    exit;
}
    // Check if first line is 3 digits or less, treat it as target profit
if (strlen(trim($lines[0])) <= 3 && is_numeric($lines[0])) {
    $targetProfit = floatval($lines[0]);
    $extremePrice = null; // No extreme price in this case
    $entries = [];
    
    // Process all lines except the first one as entries
    for ($i = 1; $i < count($lines); $i++) {
        $line = trim($lines[$i]);
        $parts = preg_split('/\s+/', $line);
        if (count($parts) >= 1) {
            $price = floatval($parts[0]);
            $volume = (count($parts) > 1) ? floatval($parts[1]) : 0.01;
            $entries[] = ['price' => $price, 'volume' => $volume];
        }
    }
    
    // Calculate total volume and weighted sum
    $totalVolume = 0;
    $weightedSum = 0;
    foreach ($entries as $entry) {
        $totalVolume += $entry['volume'];
        $weightedSum += $entry['volume'] * $entry['price'];
    }
    
    if ($totalVolume == 0) {
        sendMessage($chatId, "حجم کل نمی‌تونه صفر باشه!");
        exit;
    }
    
    $averageEntry = $weightedSum / $totalVolume;
    
    // Determine direction based on current price assumption
    $direction = 'خرید (Long)'; // Default to long
    $exitPrice = $averageEntry + $targetProfit / (100 * $totalVolume);
    
    // Send response
    $response = "📊 معامله: $direction\n";
    $response .= "🔢 تعداد: " . count($entries) . "\n";
    $response .= "📈 میانگین ورود: " . number_format($averageEntry, 2) . "\n";
    $response .= "🎯 هدف سود: " . number_format($targetProfit, 2) . " دلار\n";
    $response .= "\n📌 قیمت اصلی: " . number_format($exitPrice, 2);
    $response .= "\n📌 قیمت سربه‌سر: " . number_format($averageEntry, 2);
    
    sendMessage($chatId, $response);
    exit;
}
//************************************************

  $totalVolume = 0;
    $weightedSum = 0;

    foreach ($entries as $entry) {
        $totalVolume += $entry['volume'];
        $weightedSum += $entry['volume'] * $entry['price'];
    }

    if ($totalVolume == 0) {
        sendMessage($chatId, "حجم کل نمی‌تونه صفر باشه!");
        exit;
    }

    $averageEntry = $weightedSum / $totalVolume;

    // Determine direction and calculate PnL at extreme price
    $pnlAtExtreme = 0;
    $direction = '';

    if ($extremePrice < $averageEntry) {
        // Assume long (buy) position
        $direction = 'خرید (Long)';
        foreach ($entries as $entry) {
            $pnlAtExtreme += $entry['volume'] * 100 * ($extremePrice - $entry['price']);
        }
    } elseif ($extremePrice > $averageEntry) {
        // Assume short (sell) position
        $direction = 'فروش (Short)';
        foreach ($entries as $entry) {
            $pnlAtExtreme += $entry['volume'] * 100 * ($entry['price'] - $extremePrice);
        }
    } else {
        sendMessage($chatId, "قیمت حد ضرر برابر با میانگین ورود هست، ضرری وجود نداره.");
        exit;
    }

    // Max drawdown amount (positive value)
    $maxDrawdown = - $pnlAtExtreme; // Should be positive if direction correct

    if ($maxDrawdown <= 0) {
        sendMessage($chatId, "قیمت حد ضرر باعث ضرر نمی‌شه (جهت معامله اشتباه تشخیص داده شده یا ضرری نیست).");
        exit;
    }

    // Target profit equals max drawdown
    $targetProfit = $maxDrawdown;

    // Calculate exit price
    $exitPrice = 0;
    if ($direction === 'خرید (Long)') {
        $exitPrice = $averageEntry + $targetProfit / (100 * $totalVolume);
    } elseif ($direction === 'فروش (Short)') {
        $exitPrice = $averageEntry - $targetProfit / (100 * $totalVolume);
    }

    // Send response
   $response = "📊 معامله: $direction\n";
$response .= "🔢 تعداد: " . count($entries) . "\n";
$response .= "📈 میانگین ورود: " . number_format($averageEntry, 2) . "\n";
$response .= "📉 بیشترین ضرر: " . number_format($maxDrawdown, 2) . " دلار\n";
$response .= "\n📌 قیمت اصلی: " . number_format($exitPrice, 2);
$response .= "\n📌 قیمت سربه‌سر: " . number_format($averageEntry, 2);

    sendMessage($chatId, $response);
}

// Function to send message
function sendMessage($chatId, $text) {
    global $botToken;
    $url = "https://api.telegram.org/bot$botToken/sendMessage?chat_id=$chatId&text=" . urlencode($text);
    file_get_contents($url);
}
?>