<?php 
require("header.php");

// Get signal ID from URL
$signalId = isset($_GET['id']) ? (int)$_GET['id'] : 0;

// Fetch user currency info
$logId   = $_SESSION['log_id'] ?? null;
$curRate   = htmlspecialchars($user['cur_rate'] ?? '');
$curSymbol = htmlspecialchars($user['cur_symbol'] ?? '');
if ($logId) {
    $rateStmt = $pdo->prepare("SELECT cur_rate, cur_symbol FROM logins WHERE id = ?");
    $rateStmt->execute([$logId]);
    $user = $rateStmt->fetch(PDO::FETCH_ASSOC);
    if ($user) {
        $curRate   = (float)($user['cur_rate'] ?? 1);
        $curSymbol = htmlspecialchars($user['cur_symbol'] ?? '$');
    }
}

// Fetch signal from signals table
$stmt = $pdo->prepare("SELECT * FROM signals WHERE id = ? LIMIT 1");
$stmt->execute([$signalId]);
$signal = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$signal) {
    echo "<div class='text-white p-4'>Signal not found.</div>";
    require("footer.php");
    exit;
}

// Map variables
$signalName    = htmlspecialchars($signal['name']);
$ownerName     = htmlspecialchars($signal['owner']);
$ownerPhoto    = htmlspecialchars($signal['owner_photo']);
$winRate       = number_format((float)($signal['Wrate'] ?? 0), 2);
$signalPercent = (float)($signal['signal_p'] ?? 0);
$minAmt        = number_format((float)($signal['min'] ?? 0) * $curRate, 2);
$maxAmt        = number_format((float)($signal['max'] ?? 0) * $curRate, 2);
$Prate         = htmlspecialchars($signal['Prate']);
$Pfee          = htmlspecialchars($signal['Pfee']);
$NPrate        = htmlspecialchars($signal['NPrate']);
$riskL         = htmlspecialchars($signal['riskL']);
$strategy      = htmlspecialchars($signal['strategy']);

// Fetch all active pairs
$pairsStmt = $pdo->query("SELECT symbol FROM pairs WHERE status = '1'");
$pairs = $pairsStmt->fetchAll(PDO::FETCH_COLUMN);

// Fetch historical signal power for chart
$period = $_GET['period'] ?? 7;
$historyStmt = $pdo->prepare("SELECT power FROM signal_history WHERE signal_id=? AND day <= ? ORDER BY day ASC");
$historyStmt->execute([$signal['signal_id'], $period]);
$history = $historyStmt->fetchAll(PDO::FETCH_COLUMN);

// Fill missing days with last known power
$last = $history[count($history)-1] ?? $signalPercent;
for($i=count($history);$i<$period;$i++){
    $history[] = $last;
}
$sparklineData = implode(',', $history);
?>

<main class="flex-1 px-2 py-2 md:p-4 pb-20 md:pb-6 overflow-hidden">
    <div class="min-h-screen bg-gradient-to-b from-[#1A1428] to-[#0F0A1F]">
        <div class="w-full mx-auto px-2 sm:px-4 lg:px-4 py-6">
            <div class="flex items-center mb-6">
                <a href="buy_signal.php" class="mr-3 text-gray-400 hover:text-white transition-colors flex items-center">
                    <i class="fas fa-arrow-left mr-2"></i>
                    <span class="hidden sm:inline">Back to Signals</span>
                </a>
                <h1 class="text-2xl font-bold text-white">Setup Signal Trade</h1>
            </div>

            <div class="bg-[#0F0A1F] rounded-xl overflow-hidden border border-gray-800/30 shadow-lg mb-6">
                <div class="p-4">
                    <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-4">
                        <div class="flex items-center">
                            <div class="w-12 h-12 rounded-full bg-[#2A243B] flex items-center justify-center mr-3 shadow-lg shadow-[#2FE6DE]/10">
                                <i class="fas fa-robot text-[#2FE6DE] text-2xl"></i>
                            </div>
                            <div>
                                <h2 class="text-xl font-semibold text-white"><?= $signalName ?></h2>
                                <div class="flex items-center">
                                    <span class="px-2 py-0.5 rounded-full text-xs bg-blue-500/20 text-blue-400 mr-2">
                                        <?= $ownerName ?>
                                    </span>
                                    <div class="flex justify-center mb-4">
                <img src="../<?= $ownerPhoto ?>" 
                     alt="Owner Photo" 
                     class="w-10 h-10 md:w-10 md:h-10 rounded-full object-cover border-2 border-[#2FE6DE] shadow-md"/>
            </div>
                                    <span class="text-gray-400 text-sm flex items-center">
                                        <i class="fas fa-trophy text-yellow-500 mr-1"></i>
                                        <?= $winRate ?>% Win Rate
                                    </span>
                                </div>
                            </div>
                        </div>
                        <div class="flex items-center gap-3">
                            <div class="bg-[#1A1428] px-3 py-2 rounded-lg">
                                <span class="text-gray-400 text-xs block">Min Signal Cost</span>
                                <span class="text-white font-medium"><?= $curSymbol ?><?= $minAmt ?></span>
                            </div>
                            <div class="bg-[#1A1428] px-3 py-2 rounded-lg">
                                <span class="text-gray-400 text-xs block">Max Signal Cost</span>
                                <span class="text-white font-medium"><?= $curSymbol ?><?= $maxAmt ?></span>
                            </div>
                        </div>
                    </div>
                    
                    <p class="text-gray-300 mb-5">This is a Signal pro</p>
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                        <div class="bg-[#1A1428] p-4 rounded-lg border border-gray-800/30">
                            <h3 class="text-white font-medium mb-3 flex items-center">
                                <i class="fas fa-chart-line text-[#2FE6DE] mr-2"></i>
                                Signal Performance
                            </h3>
                            <div class="space-y-3">
                                <div>
                                    <div class="flex justify-between mb-1">
                                        <span class="text-gray-400">Win Rate</span>
                                        <span class="text-white"><?= $winRate ?>%</span>
                                    </div>
                                    <div class="w-full bg-gray-800/50 rounded-full h-1.5">
                                        <div class="bg-gradient-to-r from-green-500 to-[#2FE6DE] h-1.5 rounded-full" style="width: <?= $winRate ?>%"></div>
                                    </div>
                                </div>
                                <div class="flex justify-between">
                                    <span class="text-gray-400">Profit on Win:</span>
                                    <span class="text-green-400">+<?= $Prate ?>%</span>
                                </div>
                                <div class="flex justify-between">
                                    <span class="text-gray-400">Platform Fee:</span>
                                    <span class="text-white"><?= $Pfee ?>%</span>
                                </div>
                                <div class="flex justify-between">
                                    <span class="text-gray-400">Net Profit Rate:</span>
                                    <span class="text-[#2FE6DE]"><?= $NPrate ?>%</span>
                                </div>
                            </div>
                        </div>
                        
                        <div class="bg-[#1A1428] p-4 rounded-lg border border-gray-800/30">
                            <h3 class="text-white font-medium mb-3 flex items-center">
                                <i class="fas fa-cog text-[#2FE6DE] mr-2"></i>
                                Strategy Details
                            </h3>
                            <div class="space-y-3">
                                <div class="flex justify-between">
                                    <span class="text-gray-400">Risk Level:</span>
                                    <span class="px-2 py-0.5 rounded-full text-xs bg-green-500/20 text-green-400"><?= $riskL ?></span>
                                </div>
                                <div class="flex justify-between">
                                    <span class="text-gray-400">Trading Strategy:</span>
                                    <span class="text-white"><?= $strategy ?></span>
                                </div>
                                <div class="flex justify-between">
                                    <span class="text-gray-400">Supported Pairs:</span>
                                    <span class="text-white"><?= count($pairs) ?> Pairs</span>
                                </div>
                                
                                
                                <div class="flex justify-between">
                                    <span class="text-gray-400"> Available Durations:</span>
                                    <span class="text-white">7 Options</span>
                                </div>
                                
                                
                                
                                
                                
       


                            </div>
                        </div>
                    </div>
                </div>

                <!-- Performance Chart -->
                <div class="bg-[#191023] border-t border-gray-800/30 p-4">
                    <div class="flex items-center justify-between mb-3">
                        <h3 class="text-white font-medium">Historical Performance</h3>
                        <div class="flex items-center space-x-2">
                            <?php foreach([7,30,90] as $p): ?>
                                <button class="time-period-btn px-2 py-1 text-xs rounded-lg <?= $p==$period?'bg-[#2FE6DE]/10 text-[#2FE6DE]':'bg-[#0F0A1F]/50 text-gray-400' ?>" data-period="<?= $p ?>"><?= $p ?>D</button>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <div class="w-full bg-gray-800/50 h-1.5 rounded-full mb-3">
                        <div class="bg-gradient-to-r from-green-500 to-[#2FE6DE] h-1.5 rounded-full" style="width: <?= $sparklineData ?>%"></div>
                    </div>
                    <div class="h-40" id="performance-chart" data-values="<?= $sparklineData ?>"></div>
                </div>
            </div>
        

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-sparklines/2.1.2/jquery.sparkline.min.js"></script>
<script>
$(function(){
    // Render sparkline
    function renderChart(){
        const chartEl = $("#performance-chart");
        const values = chartEl.data('values').split(',').map(Number);
        chartEl.sparkline(values,{
            type:'line',
            width:'100%',
            height:'100%',
            lineColor:'#2FE6DE',
            fillColor:'rgba(47,230,222,0.2)',
            spotRadius:3,
            minSpotColor:'#ff0000',
            maxSpotColor:'#00ff00',
            highlightSpotColor:'#ffffff',
            highlightLineColor:'#ffffff'
        });
    }
    renderChart();

    $(".time-period-btn").click(function(){
        const period = $(this).data('period');
        const url = new URL(window.location.href);
        url.searchParams.set('period', period);
        window.location.href = url.href;
    });
});
</script>



        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        <!-- Trading Pair Chart -->
        <!--<div class="bg-[#0F0A1F] rounded-xl overflow-hidden border border-gray-800/30 shadow-lg mb-6">-->
        <!--    <div class="p-4 border-b border-gray-800/30 flex flex-col sm:flex-row sm:items-center justify-between gap-3">-->
        <!--        <div class="flex items-center">-->
        <!--            <div id="pair-icon-container" class="w-8 h-8 rounded-full bg-[#2A243B] flex items-center justify-center mr-2 overflow-hidden">-->
        <!--                <i class="fas fa-chart-line text-[#2FE6DE]" id="default-pair-icon"></i>-->
        <!--                <img id="pair-icon" class="w-full h-full object-cover hidden" src="/placeholder.svg" alt="Trading Pair">-->
        <!--            </div>-->
        <!--            <div>-->
        <!--                <h3 class="text-white font-medium" id="chart-pair-name">Select a Trading Pair</h3>-->
        <!--                <div id="price-container" class="hidden">-->
        <!--                    <span class="text-[#2FE6DE] font-mono" id="current-price">$0.00</span>-->
        <!--                    <span id="price-change" class="ml-2 text-xs px-2 py-0.5 rounded-md bg-green-500/10 text-green-400">+0.00%</span>-->
        <!--                </div>-->
        <!--            </div>-->
        <!--        </div>-->
                
        <!--        <div class="flex items-center gap-2 overflow-x-auto scrollbar-hide pb-2">-->
        <!--            <button type="button" data-days="1" class="timeframe-btn px-3 py-1.5 rounded-lg text-sm transition-colors whitespace-nowrap bg-[#2FE6DE]/10 text-[#2FE6DE] border border-[#2FE6DE]/30">1D</button>-->
        <!--            <button type="button" data-days="7" class="timeframe-btn px-3 py-1.5 rounded-lg text-sm transition-colors whitespace-nowrap text-gray-400 hover:text-white border border-gray-800/30 hover:border-gray-600">7D</button>-->
        <!--            <button type="button" data-days="30" class="timeframe-btn px-3 py-1.5 rounded-lg text-sm transition-colors whitespace-nowrap text-gray-400 hover:text-white border border-gray-800/30 hover:border-gray-600">30D</button>-->
        <!--            <button type="button" data-days="90" class="timeframe-btn px-3 py-1.5 rounded-lg text-sm transition-colors whitespace-nowrap text-gray-400 hover:text-white border border-gray-800/30 hover:border-gray-600">90D</button>-->
        <!--        </div>-->
        <!--    </div>-->
            
        <!--    <div id="pair-chart-container" class="h-[300px] sm:h-[400px] bg-[#0F0A1F] flex items-center justify-center">-->
        <!--        <div id="no-pair-selected" class="text-center p-4">-->
        <!--            <div class="w-16 h-16 mx-auto mb-4 rounded-full bg-[#2A243B] flex items-center justify-center">-->
        <!--                <i class="fas fa-chart-line text-[#2FE6DE] text-2xl"></i>-->
        <!--            </div>-->
        <!--            <p class="text-gray-300 font-medium">Select a trading pair to view chart</p>-->
        <!--            <p class="text-sm text-gray-500 mt-2">The chart will help you analyze the market before setting up your Signal</p>-->
        <!--        </div>-->
        <!--        <div id="pair-chart" class="w-full h-full hidden"></div>-->
        <!--    </div>-->
        <!--</div>-->
        
        
        
        
        
        
        
        
    
<?php
// Get signal ID from URL (passed when user clicks "Start Trade")
$signalId = isset($_GET['id']) ? (int)$_GET['id'] : 0;

// User info from session
$logId      = $_SESSION['log_id'] ?? null;
$curRate    = htmlspecialchars($user['cur_rate'] ?? '');
$userBal    = $user_bal;
$curSymbol  = htmlspecialchars($user['cur_symbol'] ?? '');
$user_email = $_SESSION['email'] ?? "guest@example.com";
$user_id    = $user['id']; // from session/login

// Fetch active pairs
$pairsStmt = $pdo->query("SELECT * FROM pairs WHERE status=1 ORDER BY symbol ASC");
$pairs = $pairsStmt->fetchAll(PDO::FETCH_ASSOC);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email     = $user_email;
    $user_cur  = $_POST['user_cur'] ?? '';
    $user_rate  = $_POST['user_rate'] ?? '';
    $plan      = strtoupper($_POST['plan'] ?? 'BUY');
    $asset     = $_POST['asset'] ?? '';
    $amount    = (float) ($_POST['amount'] ?? 0);
    $duratn    = $_POST['time'] ?? '1m';
    $date      = date("Y-m-d H:i:s");
    $entrytime = date('Y-m-d H:i:s');

    // expirytime
    $expirytime = match($duratn) {
        '1m'  => date('Y-m-d H:i:s', strtotime('+1 minute')),
        '5m'  => date('Y-m-d H:i:s', strtotime('+5 minutes')),
        '15m' => date('Y-m-d H:i:s', strtotime('+15 minutes')),
        '30m' => date('Y-m-d H:i:s', strtotime('+30 minutes')),
        '1h'  => date('Y-m-d H:i:s', strtotime('+1 hour')),
        '4h'  => date('Y-m-d H:i:s', strtotime('+4 hours')),
        '1d'  => date('Y-m-d H:i:s', strtotime('+1 day')),
        default => date('Y-m-d H:i:s', strtotime('+1 minute')),
    };

    // random lot
    // function randomLot($min = 0.001, $max = 1000, $decimals = 3) {
    //     $scale = pow(10, $decimals);
    //     return mt_rand($min * $scale, $max * $scale) / $scale;
    // }
    // $lot = randomLot();

    // Get entryrate from Binance API
    $apiSymbol = strtoupper(str_replace(["/", ":"], "", $asset));
    $tickerUrl = "https://api.binance.com/api/v3/ticker/price?symbol={$apiSymbol}";

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $tickerUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    $tickerJson = curl_exec($ch);
    $httpCode   = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    // $entryrate = 0.0;
    // if ($httpCode == 200 && $tickerJson !== false) {
    //     $ticker = json_decode($tickerJson, true);
    //     if (isset($ticker['price'])) {
    //         $entryrate = (float)$ticker['price'];
    //     }
    // }

    // Fetch the specific signal by ID
    $sigStmt = $pdo->prepare("SELECT * FROM signals WHERE id = :id AND status=1 LIMIT 1");
    $sigStmt->execute([':id' => $signalId]);
    $signal = $sigStmt->fetch(PDO::FETCH_ASSOC);

    if (!$signal) {
        echo "<div class='p-4 bg-red-700 text-white rounded'>❌ Signal not found or inactive</div>";
        exit;
    }

    $signalName = $signal['name'];
    $minAmt     = (float) $signal['min']*($curRate);
    $maxAmt     = (float) $signal['max']*($curRate);

    // Validate trading amount
    if ($amount < $minAmt || $amount > $maxAmt) {
        echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
        <script>
        Swal.fire({
          icon: 'error',
          title: 'Invalid Amount',
          text: 'Trading amount must be between {$curSymbol}" . number_format($minAmt, 2) . " and {$curSymbol}" . number_format($maxAmt, 2) . "',
          confirmButtonText: 'OK',
          confirmButtonColor: '#E02424',
          background: '#1A1428',
          color: '#ffffff',
        }).then(() => { window.location.href = ''; });
        </script>";
        exit;
    }

    // Get user balance
    // $balStmt = $pdo->prepare("SELECT balance FROM logins WHERE id = :id");
    // $balStmt->execute([':id' => $user_id]);
    // $userBal = (float) $balStmt->fetchColumn();
    
    

    if ($userBal < $amount) {
        echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
        <script>
        Swal.fire({
          icon: 'error',
          title: 'Insufficient Balance',
          text: 'Your balance is too low to trade with {$curSymbol}{$amount}',
          confirmButtonText: 'OK',
          confirmButtonColor: '#E02424',
          background: '#1A1428',
          color: '#ffffff',
        }).then(() => { window.location.href = ''; });
        </script>";
        exit;
    }

    // Calculate new balance
    $newBalance = (($userBal - $amount)/$curRate);

// Random entry rate between 0.000001 and 10,000,000
$entry = mt_rand(1, 99999) / 1000; 

// Random close rate between 0.000001 and 10,000,000
$close = mt_rand(1, 99999) / 1000;

// Clamp just to be safe (though not really needed with this logic)
$entryrate = max(0.01, min($entry, 10000));
$closerate = max(0.01, min($close, 10000));



// Decide Buy/Sell based on rates
if ($closerate > $entryrate) {
    $optionr = "BUY";
} else {
    $optionr = "SELL";
}

// Random lot size
$lot = mt_rand(1, 10000) / 1000;


// Return calculation (irregular, based on rates & lot)
$returnr = ((($entryrate + $closerate )/1000) * $lot * ($amount))+$amount;
$return = ((($entryrate + $closerate )/1000) * $lot * ($amount));

    try {
        $pdo->beginTransaction();

        // Insert trade
        $stmt = $pdo->prepare("
            INSERT INTO trade 
            (log_id, email, invest_id, plan, asset, signa, status, istatus, optionr,
             lot, invested, user_iprofit, user_bal, user_cur, Wrate, user_rate,
             entryrate, closerate, entrytime, expirytime, duratn, returnr, date)
            VALUES
            (:log_id, :email, :invest_id, :plan, :asset, :signa, :status, :istatus, :optionr,
             :lot, :invested, :user_iprofit, :user_bal, :user_cur, :Wrate, :user_rate,
             :entryrate, :closerate, :entrytime, :expirytime, :duratn, :returnr, :date)
        ");
        
      


        $stmt->execute([
            ':log_id'       => $user_id,
            ':email'        => $email,
            ':invest_id'    => 0,
            ':plan'         => $plan,
            ':asset'        => $asset,
            ':signa'        => $signalName,
            ':status'       => 1,
            ':istatus'      => 0,
            ':optionr'      => $optionr,
            ':lot'          => $lot,
            ':invested'     => $amount,
            ':user_iprofit' => 0,
            ':user_bal'     => $newBalance,
            ':user_cur'     => $user_cur,
            ':Wrate'        => 0,
            ':user_rate'    => $user_rate,
            ':entryrate'    => $entryrate,
            ':closerate'    => 0,
            ':entrytime'    => $entrytime,
            ':expirytime'   => $expirytime,
            ':duratn'       => $duratn,
            ':returnr'      => 0,
            ':date'         => $date,
        ]);

        // Update balance
        $update = $pdo->prepare("UPDATE logins SET balance = :bala, trade_amt = :tamount WHERE id = :id");
        $update->execute([
            ':bala'    => $newBalance,
            ':tamount' => ($amount/$curRate),
            ':id'      => $user_id
        ]);

        $pdo->commit();

        // Success popup
        echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
        <script>
        Swal.fire({
          icon: 'success',
          title: 'Trade Started',
          text: 'Signal trade started successfully!',
          confirmButtonText: 'OK',
          confirmButtonColor: '#00E0C6',
          background: '#1A1428',
          color: '#ffffff',
        }).then(() => { window.location.href = 'buy_signal.php'; });
        </script>";
        exit;

    } catch (PDOException $e) {
        $pdo->rollBack();
        echo "<div class='p-4 bg-red-700 text-white rounded'>
                ❌ SQL Error: " . htmlspecialchars($e->getMessage()) . "
              </div>";
    }
}
?>





<!-- Setup Form -->
<div class="bg-[#0F0A1F] rounded-xl p-4 border border-gray-800/30 shadow-lg">
    <h2 class="text-xl font-semibold text-white mb-4 flex items-center">
        <i class="fas fa-sliders-h text-[#2FE6DE] mr-2"></i>
        Configure Your Trade
    </h2>
    
    <form action="" method="POST">
        <!-- Hidden Inputs -->
        <input type="hidden" name="asset" id="hidden-asset">
        <input type="hidden" name="plan" id="hidden-plan">
        <input type="hidden" name="status" value="0">
        <input type="hidden" name="returnr" value="0.0">
        <input type="hidden" name="date" value="<?= date("jS F Y g.iA"); ?>" readonly>
         <!--<input type="hidden" name="optionr" value="pick sell/buy randoml">-->
        
        
        <input type="hidden" name="user_iprofit" value="<?= htmlspecialchars($iprofit); ?>">
        <input type="hidden" name="user_cur" value="<?= htmlspecialchars($cur_symbol); ?>">
        
        <input type="hidden" name="user_rate" value="<?= htmlspecialchars($cur_rate); ?>">
        
       
    
   
    <input type="hidden" name="status" value="0">
    <input type="hidden" name="returnr" value="0.0">
    <input type="hidden" name="date" value="<?= date("jS F Y g.iA"); ?>" readonly>
    
    
        
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <!-- Trading Pair Selection -->
            <div class="mb-4">
                <label for="pair" class="block text-gray-400 mb-2 flex items-center">
                    <i class="fas fa-exchange-alt mr-2 text-[#2FE6DE]"></i>
                    Select Trading Pair (Symbol)
                </label>
                <div class="relative">
                    <select id="pair" class="w-full bg-[#1A1428] text-white border border-gray-700 rounded-lg px-4 py-3 focus:outline-none focus:ring-2 focus:ring-[#2FE6DE]/50 appearance-none">
                        <option value="">Select a pair</option>
                        <?php foreach ($pairs as $pair): ?>
                            <option 
                                value="<?= htmlspecialchars($pair['symbol']); ?>"
                                data-type="<?= htmlspecialchars($pair['type']); ?>"
                                data-icon="<?= htmlspecialchars($pair['icon']); ?>"
                            >
                                <?= htmlspecialchars($pair['symbol']); ?> (<?= htmlspecialchars($pair['type']); ?>)
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <div class="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
                        <i class="fas fa-chevron-down text-gray-400"></i>
                    </div>
                </div>
            </div>

            <!-- Investment Amount -->
            <div class="mb-4">
                <label for="amount" class="block text-gray-400 mb-2 flex items-center">
                    <i class="fas fa-dollar-sign mr-2 text-[#2FE6DE]"></i>
                    Investment Amount
                </label>
                <div class="relative">
                    <div class="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
                        <span class="text-gray-400"><?= $curSymbol ?></span>
                    </div>
                    <input 
                        type="number" 
                        name="amount" 
                        id="amount" 
                        min="<?= $minAmt ?>"
                        max="<?= $maxAmt ?>"
                        step="0.01"
                        value="10.00"
                        class="w-full bg-[#1A1428] text-white border border-gray-700 rounded-lg pl-8 pr-4 py-3 focus:outline-none focus:ring-2 focus:ring-[#2FE6DE]/50"
                        placeholder="Enter amount"
                    >
                </div>
                <div class="flex justify-between mt-1">
                    <p class="text-gray-500 text-sm"><?= $curSymbol ?><?= $minAmt ?></p>
                    <p class="text-gray-500 text-sm"><?= $curSymbol ?><?= $maxAmt ?></p>
                </div>
            </div>
        </div>
        
        <!-- Trade Duration -->
        <div class="mb-6">
            <label class="block text-gray-400 mb-2 flex items-center">
                <i class="fas fa-clock mr-2 text-[#2FE6DE]"></i>
                Trade Duration
            </label>
            <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-7 gap-3">
                <?php
                $durations = ['1m','5m','15m','30m','1h','4h','1d'];
                foreach ($durations as $i => $dur) {
                    $checked = $i === 0 ? 'checked' : '';
                    echo "
                    <div>
                        <input type='radio' name='time' id='duration_$dur' value='$dur' class='peer hidden' $checked>
                        <label for='duration_$dur' class='block text-center py-3 px-2 rounded-lg bg-[#1A1428] border border-gray-700 cursor-pointer text-gray-400 hover:bg-[#2A243B] peer-checked:bg-[#2FE6DE]/20 peer-checked:border-[#2FE6DE] peer-checked:text-[#2FE6DE] transition-all'>
                            $dur
                        </label>
                    </div>";
                }
                ?>
            </div>
        </div>
        
        <!-- Balance Info and Start Button -->
        <div class="flex flex-col sm:flex-row justify-between items-center gap-4 mt-6">
            <div class="bg-[#1A1428] p-4 rounded-lg flex items-center w-full sm:w-auto border border-gray-800/30">
                <div class="w-10 h-10 rounded-full bg-[#2FE6DE]/10 flex items-center justify-center mr-3">
                    <i class="fas fa-wallet text-[#2FE6DE]"></i>
                </div>
                <div>
                    <span class="text-gray-400 text-sm">Available Balance:</span>
                    <span class="text-white font-medium block"><?= $cur_symbol . $balc ?></span>
                </div>
            </div>
            
            <button type="submit" class="w-full sm:w-auto bg-gradient-to-r from-[#2FE6DE] to-[#2FE6DE]/80 text-black font-bold py-3 px-4 rounded-lg hover:brightness-110 transition-all shadow-lg shadow-[#2FE6DE]/10 flex items-center justify-center">
                <i class="fas fa-robot mr-2"></i>
                Start Signal Trade
            </button>
        </div>
    </form>
</div>

<!-- Script to sync dropdown with hidden inputs -->
<script>
const pairSelect = document.getElementById('pair');
const hiddenAsset = document.getElementById('hidden-asset');
const hiddenPlan  = document.getElementById('hidden-plan');

pairSelect.addEventListener('change', () => {
    const selected = pairSelect.selectedOptions[0];
    hiddenAsset.value = selected.value || '';
    hiddenPlan.value  = selected.dataset.type || '';
});
</script>

    </div>
</div>




<style>
.scrollbar-hide::-webkit-scrollbar {
    display: none;
}
.scrollbar-hide {
    -ms-overflow-style: none;
    scrollbar-width: none;
}
</style>

























<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // Form elements
        const pairSelect = document.getElementById('pair');
        const amountInput = document.getElementById('amount');
        const durationRadios = document.querySelectorAll('input[name="duration"]');
        
        // Chart and price display elements
        const pairChart = document.getElementById('pair-chart');
        const chartPairName = document.getElementById('chart-pair-name');
        const currentPrice = document.getElementById('current-price');
        const priceChange = document.getElementById('price-change');
        const priceContainer = document.getElementById('price-container');
        const noPairSelected = document.getElementById('no-pair-selected');
        const pairIcon = document.getElementById('pair-icon');
        const defaultPairIcon = document.getElementById('default-pair-icon');
        
        // ROI calculator elements
        const winReturnElement = document.getElementById('win-return');
        const lossReturnElement = document.getElementById('loss-return');
        const expectedValueElement = document.getElementById('expected-value');
        const roiPercentageElement = document.getElementById('roi-percentage');
        const roiBarElement = document.getElementById('roi-bar');
        
        // Signal settings
        const winRate = 100.00;
        const lossRate = 100 - winRate;
        const winPercentage = 85;
        const platformFee = 0.00;
        
        // Current chart settings
        let currentCoinId = '';
        let currentDays = 1; // Default to 1 day for faster loading
        let currentPriceInfo = null;
        let chartDataCache = {}; // Cache for chart data to prevent redundant API calls
        
        // Initialize performance chart
        let performanceChart = new ApexCharts(document.getElementById('performance-chart'), {
            series: [{
                name: 'signal power',
                data: [65, 68, 71, 69, 72, 74, 76, 100.00]
            }],
            chart: {
                type: 'area',
                height: '100%',
                toolbar: {
                    show: false
                },
                animations: {
                    enabled: true,
                    easing: 'easeinout',
                    speed: 800,
                },
                background: 'transparent'
            },
            colors: ['#2FE6DE'],
            stroke: {
                curve: 'smooth',
                width: 3
            },
            fill: {
                type: 'gradient',
                gradient: {
                    shadeIntensity: 1,
                    opacityFrom: 0.3,
                    opacityTo: 0.1,
                    stops: [0, 100]
                }
            },
            grid: {
                borderColor: 'rgba(255, 255, 255, 0.1)',
                row: {
                    colors: ['transparent'],
                    opacity: 0.1
                },
                xaxis: {
                    lines: {
                        show: false
                    }
                }
            },
            dataLabels: {
                enabled: false
            },
            xaxis: {
                categories: ['Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jan'],
                labels: {
                    style: {
                        colors: '#9ca3af'
                    }
                },
                axisBorder: {
                    show: false
                },
                axisTicks: {
                    show: false
                }
            },
            yaxis: {
                labels: {
                    style: {
                        colors: '#9ca3af'
                    },
                    formatter: function(val) {
                        return val.toFixed(0) + '%';
                    }
                }
            },
            tooltip: {
                theme: 'dark',
                y: {
                    formatter: function(val) {
                        return val + '% signal Rate';
                    }
                }
            }
        });
        performanceChart.render();
        
        // Time period buttons for performance chart
        document.querySelectorAll('.time-period-btn').forEach(button => {
            button.addEventListener('click', function() {
                // Update active button styling
                document.querySelectorAll('.time-period-btn').forEach(btn => {
                    btn.classList.remove('bg-[#2FE6DE]/10', 'text-[#2FE6DE]', 'border-[#2FE6DE]/30');
                    btn.classList.add('bg-[#0F0A1F]/50', 'text-gray-400', 'border-gray-800/30');
                });
                this.classList.remove('bg-[#0F0A1F]/50', 'text-gray-400', 'border-gray-800/30');
                this.classList.add('bg-[#2FE6DE]/10', 'text-[#2FE6DE]', 'border-[#2FE6DE]/30');
                
                // Get the time period
                const period = this.getAttribute('data-period');
                
                // Update chart data based on period
                let newData, newCategories;
                
                if (period === '7') {
                    newData = [72, 74, 73, 75, 76, 77, 100.00];
                    newCategories = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
                } else if (period === '30') {
                    newData = [68, 70, 71, 69, 72, 74, 73, 75, 76, 74, 75, 100.00];
                    newCategories = ['Week 1', 'Week 2', 'Week 3', 'Week 4'];
                } else if (period === '90') {
                    newData = [62, 65, 67, 69, 71, 73, 75, 100.00];
                    newCategories = ['Month 1', 'Month 2', 'Month 3'];
                }
                
                performanceChart.updateOptions({
                    series: [{
                        data: newData
                    }],
                    xaxis: {
                        categories: newCategories
                    }
                });
            });
        });
        
        // Initialize pair chart (will be populated when a pair is selected)
        let pairChartObj;
        
        // Function to fetch real cryptocurrency data from Huobi API with caching
        async function fetchCryptoPrices(symbol, period = '1day', size = 7) {
            try {
                if (!symbol) {
                    throw new Error('No trading symbol provided');
                }
                
                // Convert symbol format from BTC/USDT to btcusdt for Huobi API
                const huobiSymbol = symbol.replace('/', '').toLowerCase();
                
                // Check cache first
                const cacheKey = `price_${huobiSymbol}_${period}_${size}`;
                const cachedData = localStorage.getItem(cacheKey);
                if (cachedData) {
                    try {
                        const parsed = JSON.parse(cachedData);
                        const now = new Date().getTime();
                        // Cache valid for 5 minutes
                        if (now - parsed.timestamp < 5 * 60 * 1000) {
                            console.log('Using cached price data');
                            return parsed.data;
                        }
                    } catch (e) {
                        console.warn('Invalid cache data, fetching fresh data');
                    }
                }
                
                // Set up timeout for the API call (3 seconds)
                const controller = new AbortController();
                const timeoutId = setTimeout(() => controller.abort(), 3000);
                
                // Format: https://api.huobi.pro/market/history/kline?symbol=btcusdt&period=1day&size=7
                const url = `https://api.huobi.pro/market/history/kline?symbol=${huobiSymbol}&period=${period}&size=${size}`;
                
                const response = await fetch(url, { signal: controller.signal });
                clearTimeout(timeoutId);
                
                const data = await response.json();
                
                if (response.ok && data.status === 'ok') {
                    // Cache the result in localStorage
                    localStorage.setItem(cacheKey, JSON.stringify({
                        timestamp: new Date().getTime(),
                        data: data.data
                    }));
                    
                    return data.data;
                } else {
                    console.error('Failed to fetch price data:', data);
                    return null;
                }
            } catch (error) {
                if (error.name === 'AbortError') {
                    console.warn('Fetch timeout for price data');
                } else {
                    console.error('Error fetching price data:', error);
                }
                return null;
            }
        }
        
        // Function to prepare chart data from Huobi response
        function prepareChartData(klineData) {
            if (!klineData || !Array.isArray(klineData) || klineData.length === 0) {
                return [];
            }
            
            // Process into OHLC format that ApexCharts needs
            const chartData = [];
            // Huobi provides full OHLC data in kline response
            for (let i = 0; i < klineData.length; i++) {
                const candle = klineData[i];
                chartData.push({
                    x: new Date(candle.id * 1000).getTime(), // Convert timestamp to milliseconds
                    y: [candle.open, candle.high, candle.low, candle.close]
                });
            }
            
            return chartData;
        }
        
        // Function to initialize the chart with real data (simplified and optimized)
        async function initPairChart(symbol, days = 1) {
            if (!symbol || !pairChart) return;
            
            try {
                // Show loading indicator immediately for better UX
                pairChart.innerHTML = '<div class="flex justify-center items-center h-64"><i class="fas fa-spinner fa-spin text-[#2FE6DE] text-xl"></i></div>';
                
                // Save the current days setting
                currentDays = days;
                
                // Use Promise.all to run both requests in parallel
                const huobiSymbol = symbol.replace('/', '').toLowerCase();
                
                // Check if we have current price info in localStorage
                const priceCacheKey = `current_price_${huobiSymbol}`;
                let hasCachedPrice = false;
                
                try {
                    const cachedPrice = localStorage.getItem(priceCacheKey);
                    if (cachedPrice) {
                        const parsed = JSON.parse(cachedPrice);
                        const now = new Date().getTime();
                        // Use cached price if less than 1 minute old
                        if (now - parsed.timestamp < 60 * 1000) {
                            currentPriceInfo = parsed.data;
                            hasCachedPrice = true;
                        }
                    }
                } catch (e) {
                    console.warn('Invalid price cache');
                }
                
                // Fetch price data
                const priceData = await fetchCryptoPrices(symbol, '1day', days);
                
                // If we don't have cached price, fetch it (but don't wait if chart data is ready)
                if (!hasCachedPrice) {
                    // Fetch current price data with timeout
                    try {
                        const controller = new AbortController();
                        const timeoutId = setTimeout(() => controller.abort(), 3000);
                        
                        const priceUrl = `https://api.huobi.pro/market/detail/merged?symbol=${huobiSymbol}`;
                        const priceResponse = await fetch(priceUrl, { signal: controller.signal });
                        clearTimeout(timeoutId);
                        
                        if (priceResponse.ok) {
                            const priceData = await priceResponse.json();
                            if (priceData.status === 'ok') {
                                const tick = priceData.tick;
                                const closePrice = tick.close;
                                const openPrice = tick.open;
                                const priceChange24h = ((closePrice - openPrice) / openPrice) * 100;
                                
                                currentPriceInfo = {
                                    price: closePrice,
                                    price_change_24h: closePrice - openPrice,
                                    price_change_24h_percentage: priceChange24h
                                };
                                
                                // Cache the current price
                                localStorage.setItem(priceCacheKey, JSON.stringify({
                                    timestamp: new Date().getTime(),
                                    data: currentPriceInfo
                                }));
                            }
                        }
                    } catch (e) {
                        console.warn('Could not fetch current price, continuing with chart only');
                    }
                }
                
                // Check if we have the chart data
                if (!priceData || priceData.length === 0) {
                    pairChart.innerHTML = '<div class="flex justify-center items-center h-64 text-gray-400"><i class="fas fa-exclamation-circle mr-2"></i> No price data available</div>';
                    return;
                }
                
                // Prepare the chart data
                const seriesData = prepareChartData(priceData);
                
                // Clear previous chart
                if (pairChartObj) {
                    pairChartObj.destroy();
                }
                
                // Create new chart with optimized settings
                pairChartObj = new ApexCharts(pairChart, {
                    series: [{
                        name: 'Price',
                        data: seriesData
                    }],
                    chart: {
                        type: 'candlestick',
                        height: '100%',
                        toolbar: {
                            show: true,
                            tools: {
                                download: false,
                                selection: false, // Disable selection for performance
                                zoom: true,
                                zoomin: false,  // Simplify toolbar
                                zoomout: false, // Simplify toolbar
                                pan: true,
                                reset: true
                            }
                        },
                        animations: {
                            enabled: false  // Disable animations for better performance
                        },
                        background: 'transparent'
                    },
                    plotOptions: {
                        candlestick: {
                            colors: {
                                upward: '#26a69a',
                                downward: '#ef5350'
                            },
                            wick: {
                                useFillColor: true,
                            }
                        }
                    },
                    xaxis: {
                        type: 'datetime',
                        labels: {
                            style: {
                                colors: '#9ca3af'
                            },
                            datetimeFormatter: {
                                year: 'yyyy',
                                month: "MMM 'yy",
                                day: 'dd MMM',
                                hour: 'HH:mm'
                            }
                        },
                        axisBorder: {
                            show: false
                        },
                        axisTicks: {
                            show: false
                        }
                    },
                    yaxis: {
                        labels: {
                            style: {
                                colors: '#9ca3af'
                            },
                            formatter: function(val) {
                                return '$' + formatPrice(val);
                            }
                        },
                        tooltip: {
                            enabled: true
                        }
                    },
                    grid: {
                        borderColor: 'rgba(255, 255, 255, 0.1)',
                        strokeDashArray: 3
                    },
                    tooltip: {
                        theme: 'dark',
                        x: {
                            format: 'MMM dd HH:mm'
                        }
                    }
                });
                
                pairChartObj.render();
                
                // Update price info
                if (currentPrice && priceChange && currentPriceInfo) {
                    currentPrice.textContent = '$' + currentPriceInfo.price.toFixed(2);
                    priceChange.textContent = (currentPriceInfo.price_change_24h_percentage >= 0 ? '+' : '') + 
                                             currentPriceInfo.price_change_24h_percentage.toFixed(2) + '%';
                    
                    if (currentPriceInfo.price_change_24h_percentage >= 0) {
                        priceChange.className = 'ml-2 text-xs px-2 py-0.5 rounded-md bg-green-500/10 text-green-400';
                    } else {
                        priceChange.className = 'ml-2 text-xs px-2 py-0.5 rounded-md bg-red-500/10 text-red-400';
                    }
                }
            } catch (error) {
                console.error('Error initializing chart:', error);
                pairChart.innerHTML = `<div class="flex items-center justify-center h-full text-red-400"><i class="fas fa-exclamation-circle mr-2"></i> Error loading chart</div>`;
            }
        }
        
        // Format price based on its value
        function formatPrice(price) {
            if (price >= 1000) {
                return price.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
            } else if (price >= 1) {
                return price.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 4 });
            } else if (price >= 0.01) {
                return price.toLocaleString('en-US', { minimumFractionDigits: 4, maximumFractionDigits: 6 });
            } else {
                return price.toLocaleString('en-US', { minimumFractionDigits: 6, maximumFractionDigits: 8 });
            }
        }
        
        // Handle timeframe buttons
        document.querySelectorAll('.timeframe-btn').forEach(button => {
            button.addEventListener('click', function() {
                if (!currentCoinId) return;
                
                // Update active button styling
                document.querySelectorAll('.timeframe-btn').forEach(btn => {
                    btn.classList.remove('bg-[#2FE6DE]/10', 'text-[#2FE6DE]', 'border-[#2FE6DE]/30');
                    btn.classList.add('text-gray-400', 'hover:text-white', 'border-gray-800/30', 'hover:border-gray-600');
                });
                this.classList.remove('text-gray-400', 'hover:text-white', 'border-gray-800/30', 'hover:border-gray-600');
                this.classList.add('bg-[#2FE6DE]/10', 'text-[#2FE6DE]', 'border-[#2FE6DE]/30');
                
                // Get the days parameter
                const days = parseInt(this.getAttribute('data-days'));
                
                // Update chart with new timeframe
                initPairChart(currentCoinId, days);
            });
        });
        
        function updateReturns() {
            const amount = parseFloat(amountInput.value) || 0;
            
            // Calculate win return (subtract platform fee)
            const winProfit = amount * (winPercentage / 100);
            const fee = winProfit * (platformFee / 100);
            const netWinProfit = winProfit - fee;
            
            // Loss is always the full amount
            const lossAmount = amount;
            
            // Expected value calculation
            const expectedValue = ((amount + netWinProfit) * (winRate / 100)) - (lossAmount * (lossRate / 100));
            
            // ROI calculation
            const roi = (expectedValue / amount) * 100;
            
            // Update the UI
            winReturnElement.textContent = `+$${netWinProfit.toFixed(2)}`;
            lossReturnElement.textContent = `-$${lossAmount.toFixed(2)}`;
            expectedValueElement.textContent = `$${expectedValue.toFixed(2)}`;
            roiPercentageElement.textContent = `${roi.toFixed(2)}%`;
            
            // Update ROI bar
            // Map ROI from -100% to +100% to 0% to 100% width
            const roiBarWidth = Math.min(Math.max((roi + 100) / 2, 0), 100);
            roiBarElement.style.width = `${roiBarWidth}%`;
            
            // Add color class to expected value
            if (expectedValue > 0) {
                expectedValueElement.classList.remove('text-red-400');
                expectedValueElement.classList.add('text-[#2FE6DE]');
            } else {
                expectedValueElement.classList.remove('text-[#2FE6DE]');
                expectedValueElement.classList.add('text-red-400');
            }
            
            // Add color class to ROI percentage
            if (roi > 0) {
                roiPercentageElement.classList.remove('text-red-400');
                roiPercentageElement.classList.add('text-[#2FE6DE]');
            } else {
                roiPercentageElement.classList.remove('text-[#2FE6DE]');
                roiPercentageElement.classList.add('text-red-400');
            }
        }
        
        // Update on amount change
        amountInput.addEventListener('input', updateReturns);
        
        // Initial calculation
        updateReturns();
        
        // Handle trading pair selection
        if (pairSelect) {
            pairSelect.addEventListener('change', function() {
                const selectedOption = this.options[this.selectedIndex];
                const symbol = this.value; // e.g., BTC/USDT
                const coinName = selectedOption.dataset.name || symbol;
                const coinIcon = selectedOption.dataset.icon || 'default-coin.png';
                
                if (symbol) {
                    // Update chart title (using the existing chartPairName element)
                    if (chartPairName) {
                        chartPairName.textContent = `${coinName} (${symbol})`;
                    }
                    
                    // Update the price chart
                    initPairChart(symbol);
                    
                    // Show price container
                    priceContainer.classList.remove('hidden');
                    
                    // Update icon
                    if (coinIcon) {
                        defaultPairIcon.classList.add('hidden');
                        pairIcon.src = coinIcon;
                        pairIcon.alt = coinName;
                        pairIcon.classList.remove('hidden');
                    } else {
                        pairIcon.classList.add('hidden');
                        defaultPairIcon.classList.remove('hidden');
                    }
                    
                    // Show chart, hide placeholder
                    noPairSelected.classList.add('hidden');
                    pairChart.classList.remove('hidden');
                } else {
                    // Reset to default state
                    chartPairName.textContent = 'Select a Trading Pair';
                    priceContainer.classList.add('hidden');
                    pairIcon.classList.add('hidden');
                    defaultPairIcon.classList.remove('hidden');
                    noPairSelected.classList.remove('hidden');
                    pairChart.classList.add('hidden');
                }
            });
        }
        
        // Convert any pair to Huobi-compatible format
        function formatHuobiSymbol(symbol) {
            // Extract the trading pair and convert to Huobi format (e.g., BTC/USDT to btcusdt)
            return symbol.replace('/', '').toLowerCase();
        }
    });
</script>
        </main>
    <?php require ("footer.php") ?>