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


     <main class="flex-1 px-2 py-2 md:p-4 pb-20 md:pb-6 overflow-hidden">
            <div class="bg-gradient-to-b from-[#1A1428] to-[#0F0A1F]">
    <div class="w-full mx-auto px-2 sm:px-6 lg:px-8 py-6">
        <div>
<!--[if BLOCK]><![endif]--><!--[if ENDBLOCK]><![endif]-->
</div>

    <div>
<!--[if BLOCK]><![endif]--><!--[if ENDBLOCK]><![endif]-->
</div>

        <!-- Signal Trading Header -->
        <div class="flex flex-col md:flex-row md:items-center md:justify-between mb-8">
            <div class="flex items-center">
                <div class="w-12 h-12 rounded-full bg-[#2FE6DE]/10 flex items-center justify-center mr-3">
                    <i class="fas fa-robot text-[#2FE6DE] text-xl"></i>
                </div>
                <div>
                    <h1 class="text-2xl font-bold text-white">AI Trading Signals</h1>
                    <p class="text-gray-400 mt-1">Let our AI-powered Signals trade for you</p>
                </div>
            </div>
            <div class="mt-4 md:mt-0 flex space-x-3">
                <a href="trade.php" class="px-4 py-2.5 bg-[#2A243B] text-white rounded-lg hover:bg-[#382f50] transition-colors flex items-center focus:outline-none focus:ring-2 focus:ring-gray-600/50">
                    <i class="fas fa-chart-line mr-2"></i> Manual Trade
                </a>
                <a href="#available-bots" class="px-4 py-2.5 bg-[#2FE6DE] text-black font-medium rounded-lg hover:bg-[#27c5be] transition-colors flex items-center focus:outline-none focus:ring-2 focus:ring-[#2FE6DE]/50">
                    <i class='fas fa-robot text-[#0F0A1F] text-2xl'></i> Signals Trade
                </a>
            </div>
        </div>

        <!-- Stats Overview -->
        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
            
            
            
           <?php
// =======================
// Trading stats (PDO)
// =======================
$log_id = $_SESSION['SESS_USERID'] ?? 0; // adjust if your session key is different
if (!$log_id) {
    echo "User not logged in.";
    return;
}

// 1) Active Signals: count trades where expirytime is still in the future
$stmt = $pdo->prepare("SELECT COUNT(*) FROM trade WHERE log_id = :log_id AND status = 1");
$stmt->execute([':log_id' => $log_id]);
$active_signals = (int)$stmt->fetchColumn();

// 2) Total Profit: sum of `returnr` (and also sum of numeric user_iprofit just in case)
$stmt = $pdo->prepare("SELECT COALESCE(SUM(returnr),0) AS sum_returnr, COALESCE(SUM(user_iprofit),0) AS sum_user_iprofit
                       FROM trade WHERE log_id = :log_id");
$stmt->execute([':log_id' => $log_id]);
$profitRow = $stmt->fetch(PDO::FETCH_ASSOC);
$total_profit_returnr = (float)$profitRow['sum_returnr'];
$total_profit_iprofit = (float)$profitRow['sum_user_iprofit'];

// 3) Completed trades stats (completed = expirytime <= NOW())
$stmt = $pdo->prepare("
    SELECT 
      COUNT(*) AS completed_count,
      SUM(CASE WHEN user_iprofit > 0 THEN 1 ELSE 0 END) AS wins,
      COALESCE(AVG(`Wrate`),0) AS avg_wrate
    FROM trade
    WHERE log_id = :log_id AND expirytime <= NOW()
");
$stmt->execute([':log_id' => $log_id]);
$completedRow = $stmt->fetch(PDO::FETCH_ASSOC);
$completed_count = (int)$completedRow['completed_count'];
$wins = (int)$completedRow['wins'];
$avg_wrate = (float)$completedRow['avg_wrate'];

// Defensive: avoid division by zero
$win_percentage = $completed_count > 0 ? ($wins / $completed_count) * 100 : 0.0;

// Format for display
$active_signals_display = $active_signals;
$total_profit_display = number_format($total_profit_returnr, 2);          // primary as returnr
$total_profit_alt = number_format($total_profit_iprofit, 2);              // alternative using user_iprofit
$win_percentage_display = number_format($win_percentage, 1);             // e.g. 85.0
$avg_wrate_display = number_format($avg_wrate, 4);                       // keep precision

?>

<!-- Active Signals -->
<div class="bg-[#0F0A1F] rounded-xl p-5 border border-gray-800/30 shadow-lg">
    <div class="flex items-center justify-between">
        <div>
            <p class="text-gray-400 text-sm">Active Signals</p>
            <h3 class="text-2xl font-bold text-white mt-1"><?= $active_signals_display ?></h3>
        </div>
        <div class="w-10 h-10 rounded-full bg-blue-500/10 flex items-center justify-center">
            <i class="fas fa-robot text-blue-400"></i>
        </div>
    </div>
    <div class="mt-2 text-xs text-gray-400">
        <?php if ($active_signals > 0): ?>
            <span><i class="fas fa-bolt"></i> <?= $active_signals ?> active signal<?= $active_signals>1 ? 's' : '' ?></span>
        <?php else: ?>
            <span><i class="fas fa-circle-notch"></i> No active signals</span>
        <?php endif; ?>
    </div>
</div>

<!-- Total Profit -->
<div class="bg-[#0F0A1F] rounded-xl p-5 border border-gray-800/30 shadow-lg mt-4">
    <div class="flex items-center justify-between">
        <div>
            <p class="text-gray-400 text-sm">Total Profit</p>
            <h3 class="text-2xl font-bold text-white mt-1"><?php echo $cur_symbol ?><?= $total_profit_display ?></h3>
        </div>
        <div class="w-10 h-10 rounded-full bg-green-500/10 flex items-center justify-center">
            <i class="fas fa-chart-line text-green-400"></i>
        </div>
    </div>
    <div class="mt-2 text-xs text-gray-400">
        <i class="fas fa-info-circle"></i>
        Calculated from `returnr`. (alt: user_iprofit = <?php echo $cur_symbol ?><?= $total_profit_alt ?>)
    </div>
</div>

<!-- Win Rate -->
<div class="bg-[#0F0A1F] rounded-xl p-5 border border-gray-800/30 shadow-lg mt-4">
    <div class="flex items-center justify-between">
       <?php
// Fetch total Wrate (sum of all percentages) for this user
$wrateStmt = $pdo->prepare("SELECT SUM(Wrate) as totalWrate FROM trade WHERE log_id = :log_id");
$wrateStmt->execute(['log_id' => $userId]);
$totalWrate = $wrateStmt->fetch(PDO::FETCH_ASSOC)['totalWrate'] ?? 0;
?>

<div>
    <p class="text-gray-400 text-sm">Win Rate</p>
    <h3 class="text-2xl font-bold text-white mt-1">
        <?= number_format($totalWrate, 2) ?>%
    </h3>
</div>

        <div class="w-10 h-10 rounded-full bg-purple-500/10 flex items-center justify-center">
            <i class="fas fa-trophy text-purple-400"></i>
        </div>
    </div>
    <div class="mt-2 text-xs text-gray-400">
        Based on <?= $completed_count ?> completed trade<?= $completed_count!==1 ? 's' : '' ?> • Avg Wrate: <?= $avg_wrate_display ?>
    </div>
</div>

            
            <div class="bg-[#0F0A1F] rounded-xl p-5 border border-gray-800/30 shadow-lg">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-gray-400 text-sm">Available Balance</p>
                        <h3 class="text-2xl font-bold text-white mt-1"><?php echo $cur_symbol ?><?php echo $balc ?></h3>
                    </div>
                    <div class="w-10 h-10 rounded-full bg-[#2FE6DE]/10 flex items-center justify-center">
                        <i class="fas fa-wallet text-[#2FE6DE]"></i>
                    </div>
                </div>
                <div class="mt-2">
                    <a href="deposit.php" class="text-xs text-[#2FE6DE] hover:underline focus:outline-none focus:ring-2 focus:ring-[#2FE6DE]/50 rounded px-1">
                        <i class="fas fa-plus-circle"></i> Add funds
                    </a>
                </div>
            </div>
        </div>








<!-- Active Bot Trades -->
        <div class="bg-[#0F0A1F] rounded-xl p-4 mb-8 border border-gray-800/30 shadow-lg">
            <div class="flex items-center mb-4">
                <div class="w-8 h-8 rounded-full bg-[#2FE6DE]/10 flex items-center justify-center mr-2">
                    <i class="fas fa-bolt text-[#2FE6DE]"></i>
                </div>
                <h2 class="text-xl font-semibold text-white">Your Active Signal Trades</h2>
            </div>
                
<div class="overflow-x-auto scrollbar-hide md:block">
                <table class="w-full min-w-[800px]" id="active-trades-table">
                       
                        <tbody >
                            <tr><td colspan="7" class="text-center text-gray-400 py-4">Loading...</td></tr>
                        </tbody>
                    </table>
                </div></div>

<script>
function loadActiveTrades() {
    fetch("active_trades_section.php", { credentials: 'same-origin' })
        .then(res => res.text())
        .then(html => {
            document.getElementById("active-trades-table").innerHTML = html;

            // re-bind countdown timers
            document.querySelectorAll('.countdown-timer').forEach(function(el) {
                let end = new Date(el.dataset.endTime).getTime();
                let now = new Date().getTime();
                let diff = end - now;
                if (diff > 0) {
                    let mins = Math.floor((diff % (1000*60*60)) / (1000*60));
                    let secs = Math.floor((diff % (1000*60)) / 1000);
                    el.innerText = (mins<10?"0":"")+mins+":"+(secs<10?"0":"")+secs;
                } else {
                    el.innerText = "Expired";
                }
            });
        })
        .catch(err => {
            console.error("Error loading active trades:", err);
            document.getElementById("active-trades-table").innerHTML = '<tr><td colspan="7" class="text-center text-red-500 py-4">Error loading trades</td></tr>';
        });
}


// Initial load
loadActiveTrades();

// Refresh every 10s
setInterval(loadActiveTrades, 10000);

// Update countdowns every second
setInterval(function() {
    document.querySelectorAll('.countdown-timer').forEach(function(el) {
        let end = new Date(el.dataset.endTime).getTime();
        let now = new Date().getTime();
        let diff = end - now;
        el.innerText = diff > 0 ? 
            (Math.floor(diff/60000).toString().padStart(2,'0') + ":" + Math.floor((diff%60000)/1000).toString().padStart(2,'0')) 
            : "Expired";
    });
}, 1000);
</script>




                    
                    
                    
                    
                    
          <!-- Recent Completed Trades -->
<div class="bg-[#0F0A1F] rounded-xl p-4 mb-8 border border-gray-800/30 shadow-lg">
    <div class="flex items-center justify-between mb-4">
        <div class="flex items-center">
            <div class="w-8 h-8 rounded-full bg-[#2FE6DE]/10 flex items-center justify-center mr-2">
                <i class="fas fa-history text-[#2FE6DE]"></i>
            </div>
            <h2 class="text-xl font-semibold text-white">Recent Trades</h2>
        </div>
        <a href="trade_logs.php" class="text-[#2FE6DE] text-sm hover:underline flex items-center">
            View all <i class="fas fa-arrow-right ml-1"></i>
        </a>
    </div>

<?php
// Fetch last 8 trades for this user
$stmt = $pdo->prepare("SELECT * FROM trade WHERE log_id = :log_id ORDER BY id DESC LIMIT 1000");
$stmt->execute(['log_id' => $userId]);
$trades = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<div class="bg-[#0F0A1F] rounded-xl p-6 border border-gray-800/30 shadow-lg">

    <!-- Desktop View -->
    <div class="hidden md:block overflow-x-auto scrollbar-hide">
        <table class="w-full min-w-[900px]">
            <thead>
                <tr class="text-left text-gray-400 text-sm border-b border-gray-800/50">
                    <th class="pb-4 pl-2">Signal</th>
                    <th class="pb-4">Trading Pair</th>
                    <th class="pb-4">Trading Type</th>
                    <th class="pb-4">Amount</th>
                    <th class="pb-4">Direction</th>
                    <th class="pb-4">Entry/Close</th>
                    <th class="pb-4">Time</th>
                    <th class="pb-4">Status</th>
                    <th class="pb-4">Result</th>
                    <th class="pb-4">Profit/Loss</th>
                    <th class="pb-4 text-right pr-2">Details</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($trades as $trade): 
                    $direction = strtolower($trade['optionr']) === 'buy' ? 'Buy' : 'Sell';
                    $directionColor = $direction === 'Buy' ? 'green-400' : 'red-400';
                    $statusText = $trade['status'] == 1 ? 'Pending' : 'Completed';
                    $statusColor = $trade['status'] == 1 ? 'yellow-400' : 'green-400';

                    // Result logic based on returnr
                    $result = ($trade['returnr'] > 1) ? 'Win' : 'Trading..';
                    $resultColor = ($trade['returnr'] > 1) ? 'green-400' : 'red-400';

                    // Profit/Loss shows returnr
                    $profitLoss = (float)$trade['returnr'];
                    $wrate = $trade['Wrate'] ?? 0;
                ?>
                <tr class="border-b border-gray-800/30 text-white hover:bg-[#191023]/50 transition-colors">
                    <td class="py-4 pl-2">
                        <div class="flex items-center">
                            <div class="w-8 h-8 rounded-full bg-[#2A243B] flex items-center justify-center mr-2">
                                <i class="fas fa-robot text-[#2FE6DE]"></i>
                            </div>
                            <span class="font-medium"><?= htmlspecialchars($trade['signa']) ?></span>
                        </div>
                    </td>
                    <td class="py-4"><?= htmlspecialchars($trade['asset']) ?></td>
                    <td class="py-4"><?= htmlspecialchars($trade['plan']) ?></td>
                    <td class="py-4"><?= htmlspecialchars($trade['user_cur']) ?><?= number_format($trade['invested'], 2) ?></td>
                    <td class="py-4">
                        <span class="px-2 py-1 rounded-full text-xs bg-<?= $directionColor ?>/20 text-<?= $directionColor ?>">
                            <i class="fas fa-arrow-<?= $direction === 'Buy' ? 'up' : 'down' ?> mr-1"></i>
                            <?= $direction ?>
                        </span>
                    </td>
                    <td class="py-4">
                        <div class="text-sm"><?= $trade['user_cur'] ?><?= number_format($trade['entryrate'], 2) ?></div>
                        <div class="text-xs text-green-400"><?= $trade['user_cur'] ?><?= number_format($trade['closerate'], 2) ?></div>
                    </td>
                    <td class="py-4">
                        <div class="text-sm"><?= date("M d, Y H:i", strtotime($trade['entrytime'])) ?></div>
                        <div class="text-xs text-gray-400"><?= date("M d, Y H:i", strtotime($trade['expirytime'])) ?></div>
                    </td>
                    <td class="py-4">
                        <span class="px-2 py-1 rounded-full text-xs bg-<?= $statusColor ?>/20 text-<?= $statusColor ?>">
                            <i class="fas fa-check-circle mr-1"></i> <?= $statusText ?>
                        </span>
                    </td>
                    <td class="py-4">
                        <span class="px-2 py-1 rounded-full text-xs bg-<?= $resultColor ?>/20 text-<?= $resultColor ?>">
                            <i class="fas fa-trophy mr-1"></i> <?= $result ?>
                        </span>
                    </td>
                    <td class="py-4">
                        <?php if ($trade['status'] == 1): ?>
                            <span class="text-yellow-400 font-medium">-- --</span>
                        <?php else: ?>
                            <span class="text-<?= $resultColor ?> font-medium">
                                <?= $trade['user_cur'] ?><?= number_format($profitLoss, 2) ?>
                                <span class="text-xs opacity-75">(<?= number_format($wrate, 2) ?>%)</span>
                            </span>
                        <?php endif; ?>
                    </td>
                    <td class="py-4 text-right pr-2">
                        <a href="trade_details.php?id=<?= $trade['id'] ?>" class="px-3 py-1.5 bg-[#2A243B] text-[#2FE6DE] rounded-lg hover:bg-[#382f50] transition-colors inline-flex items-center">
                            <i class="fas fa-eye mr-1.5"></i> Details
                        </a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>

   <!-- Mobile horizontal scrollable table -->
<div id="scrollableTable" class="md:hidden overflow-x-auto scrollbar-thick scrollbar-thumb-[#2FE6DE] scrollbar-track-[#0F0A1F] rounded-lg border border-gray-800/30">
    <table class="min-w-[800px] w-full text-white text-sm border-collapse">
        <thead>
            <tr class="bg-[#191023] border-b border-gray-800/50 text-left">
                <th class="px-4 py-2 whitespace-nowrap">Signal</th>
                <th class="px-4 py-2 whitespace-nowrap">Type</th>
                <th class="px-4 py-2 whitespace-nowrap">Pair</th>
                <th class="px-4 py-2 whitespace-nowrap">Amount</th>
                <th class="px-4 py-2 whitespace-nowrap">Direction</th>
                <th class="px-4 py-2 whitespace-nowrap">Entry Price</th>
                <th class="px-4 py-2 whitespace-nowrap">Close Price</th>
                <th class="px-4 py-2 whitespace-nowrap">Time</th>
                <th class="px-4 py-2 whitespace-nowrap">Duration</th>
                <th class="px-4 py-2 whitespace-nowrap">Status</th>
                <th class="px-4 py-2 whitespace-nowrap">Result</th>
                <th class="px-4 py-2 whitespace-nowrap">Profit/Loss</th>
                <th class="px-4 py-2 whitespace-nowrap">Details</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($trades as $trade):
                $direction = strtolower($trade['optionr']) === 'buy' ? 'Buy' : 'Sell';
                $directionColor = $direction === 'Buy' ? 'green-400' : 'red-400';
                $statusText = $trade['status'] == 1 ? 'Pending' : 'Completed';
                $statusColor = $trade['status'] == 1 ? 'yellow-400' : 'green-400';

                $result = ($trade['returnr'] > 1) ? 'Win' : 'Loss';
                $resultColor = ($trade['returnr'] > 1) ? 'green-400' : 'red-400';

                $profitLoss = (float)$trade['returnr'];
                $wrate = $trade['Wrate'] ?? 0;

                // Duration calculation
                $entryTime = new DateTime($trade['entrytime']);
                $expiryTime = new DateTime($trade['expirytime']);
                $interval = $entryTime->diff($expiryTime);
                $durationStr = '';
                if ($interval->d > 0) $durationStr .= $interval->d . 'd ';
                if ($interval->h > 0) $durationStr .= $interval->h . 'h ';
                if ($interval->i > 0) $durationStr .= $interval->i . 'm';
                $durationStr = trim($durationStr);
                if ($durationStr === '') $durationStr = '0m';
            ?>
            <tr class="border-b border-gray-800/30 hover:bg-[#191023]/60 transition-colors">
                <td class="px-4 py-2 whitespace-nowrap flex items-center">
                    <div class="w-6 h-6 rounded-full bg-[#2A243B] flex items-center justify-center mr-2">
                        <i class="fas fa-robot text-[#2FE6DE]"></i>
                    </div>
                    <?= htmlspecialchars($trade['signa']) ?>
                </td>
                 <td class="px-4 py-2 whitespace-nowrap"><?= htmlspecialchars($trade['plan']) ?></td>
                 <td class="px-4 py-2 whitespace-nowrap"><?= htmlspecialchars($trade['asset']) ?></td>
                <td class="px-4 py-2 whitespace-nowrap"><?= htmlspecialchars($trade['user_cur']) ?><?= number_format($trade['invested'], 2) ?></td>
                <td class="px-4 py-2 whitespace-nowrap">
                    <span class="px-2 py-0.5 rounded-full text-xs bg-<?= $directionColor ?>/20 text-<?= $directionColor ?>">
                        <i class="fas fa-arrow-<?= $direction === 'Buy' ? 'up' : 'down' ?> mr-1"></i> <?= $direction ?>
                    </span>
                </td>
                <td class="px-4 py-2 whitespace-nowrap"><?= $trade['user_cur'] ?><?= number_format($trade['entryrate'], 2) ?></td>
                <td class="px-4 py-2 whitespace-nowrap text-green-400"><?= $trade['user_cur'] ?><?= number_format($trade['closerate'], 2) ?></td>
                <td class="px-4 py-2 whitespace-nowrap"><?= date("M d, Y H:i", strtotime($trade['entrytime'])) ?></td>
                <td class="px-4 py-2 whitespace-nowrap"><?= $durationStr ?></td>
                <td class="px-4 py-2 whitespace-nowrap">
                    <span class="px-2 py-0.5 rounded-full text-xs bg-<?= $statusColor ?>/20 text-<?= $statusColor ?>">
                        <?= $statusText ?>
                    </span>
                </td>
                <td class="px-4 py-2 whitespace-nowrap">
                    <span class="px-2 py-0.5 rounded-full text-xs bg-<?= $resultColor ?>/20 text-<?= $resultColor ?>">
                        <?= $result ?>
                    </span>
                </td>
                <td class="px-4 py-2 whitespace-nowrap font-medium">
                    <?php if ($trade['status'] == 1): ?>
                        <span class="text-yellow-400">-- --</span>
                    <?php else: ?>
                        <span class="text-<?= $resultColor ?>">
                            <?= $trade['user_cur'] ?><?= number_format($profitLoss, 2) ?>
                            <span class="text-xs opacity-75">(<?= number_format($wrate, 2) ?>%)</span>
                        </span>
                    <?php endif; ?>
                </td>
                <td class="px-4 py-2 whitespace-nowrap">
                    <a href="trade_details.php?id=<?= $trade['id'] ?>" class="px-3 py-1 bg-[#2A243B] text-[#2FE6DE] rounded-lg hover:bg-[#382f50] transition-colors inline-flex items-center">
                        <i class="fas fa-eye mr-1"></i> Details
                    </a>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

<script>
  document.addEventListener("DOMContentLoaded", function() {
    const container = document.getElementById('scrollableTable');
    if (!container) return;

    let direction = 1; // 1 = right, -1 = left
    const speed = 0.5; // pixels per frame
    let animationId;

    function scrollStep() {
      container.scrollLeft += direction * speed;

      // Reverse direction when reaching scroll ends
      if (container.scrollLeft + container.clientWidth >= container.scrollWidth) {
        direction = -1;
      } else if (container.scrollLeft <= 0) {
        direction = 1;
      }

      animationId = requestAnimationFrame(scrollStep);
    }

    // Intersection Observer to start scrolling only when visible
    const observer = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          if (!animationId) animationId = requestAnimationFrame(scrollStep);
        } else {
          if (animationId) {
            cancelAnimationFrame(animationId);
            animationId = null;
          }
        }
      });
    }, { threshold: 0.1 });

    observer.observe(container);
  });
</script>
</div>

        
        
        
        
        
        
        
        
        
        <!-- Available Signals -->
        <div id="available-bots" class="mb-8">
            <div class="flex items-center mb-6">
                <div class="w-8 h-8 rounded-full bg-[#2FE6DE]/10 flex items-center justify-center mr-2">
                    <i class="fas fa-robot text-[#2FE6DE]"></i>
                </div>
                <h2 class="text-xl font-semibold text-white">Available Trading Signals</h2>
            </div>
            
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">    




<?php
$logId = $_SESSION['log_id'] ?? null;

$curRate   = htmlspecialchars($user['cur_rate'] ?? '');
$curSymbol = htmlspecialchars($user['cur_symbol'] ?? '');
if ($logId) {
    $rateStmt = $pdo->prepare("SELECT cur_rate FROM logi8ns WHERE id = ?");
    $rateStmt->execute([$logId]);
    $curRate = (float)($rateStmt->fetchColumn() ?: 1);
}

$signalsStmt = $pdo->query("SELECT * FROM signals WHERE status = '1' ORDER BY id DESC");
$signals = $signalsStmt->fetchAll(PDO::FETCH_ASSOC);

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

foreach ($signals as $signal):
    $signalId      = (int)$signal['id'];
    $signalName    = htmlspecialchars($signal['name'] ?? 'No Signal');
    $winRate       = number_format((float)($signal['Wrate'] ?? 0), 2);
    $signalPercent = (float)($signal['signal_p'] ?? 0);
    $ownerName     = htmlspecialchars($signal['owner'] ?? 'Unknown');
    $ownerPhoto    = htmlspecialchars($signal['owner_photo'] ?? 'assets/default.png');

    $minAmtRaw = (float)($signal['min'] ?? 0) * $curRate;
    $maxAmtRaw = (float)($signal['max'] ?? 0) * $curRate;
    $minAmt    = number_format($minAmtRaw, 2);
    $maxAmt    = number_format($maxAmtRaw, 2);

    // Generate sparkline values
    $sparklineValues = [];
    for ($i = 0; $i < 25; $i++) {
        $sparklineValues[] = max(0, min(100, $signalPercent + rand(-10, 10)));
    }
    $sparklineData = implode(',', $sparklineValues);
?>

<div class="bg-[#0F0A1F] rounded-xl overflow-hidden border border-gray-800/30 shadow-lg hover:border-[#2FE6DE]/30 transition-all hover:shadow-[#2FE6DE]/5 hover:shadow-xl">
    <div class="p-4">
        <div class="flex items-center justify-between mb-4">
            <div class="flex items-center">
                <div class="w-10 h-10 rounded-full bg-[#2A243B] flex items-center justify-center mr-3">
                    <i class="fas fa-robot text-[#2FE6DE]"></i>
                </div>
                <h3 class="text-lg font-semibold text-white"><?= $signalName ?></h3>
            </div>
            <span class="px-3 py-1 rounded-full text-xs bg-blue-500/20 text-blue-400 font-medium">
                <?= $ownerName ?>
            </span>
        </div>

        <p class="text-gray-400 text-sm mb-5">This Signal was built by <?= $ownerName ?></p>

        <div class="flex justify-center mb-4">
            <img src="../<?= $ownerPhoto ?>" alt="Owner Photo" class="w-10 h-10 rounded-full object-cover border-2 border-[#2FE6DE] shadow-md" />
        </div>

        <div class="grid grid-cols-2 gap-4 mb-5">
            <div class="bg-[#1A1428] p-3 rounded-lg">
                <div class="flex items-center justify-between mb-2">
                    <p class="text-gray-400 text-xs">Win Rate</p>
                    <span class="text-xs px-2 py-0.5 rounded bg-green-500/10 text-green-400">
                        <i class="fas fa-chart-line mr-1"></i> <?= $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: <?= min(100, max(0, (float)$signal['Wrate'])) ?>%"></div>
                </div>
            </div>
            <div class="bg-[#1A1428] p-3 rounded-lg">
                <p class="text-gray-400 text-xs mb-1">Min Cost</p>
                <p class="text-white font-medium text-sm"><?= $curSymbol ?><?= $minAmt ?></p>
                <p class="text-gray-400 text-xs mb-1">Max Cost</p>
                <p class="text-white font-medium text-sm"><?= $curSymbol ?><?= $maxAmt ?></p>
            </div>
        </div>

        <div class="mb-4">
            <p class="text-gray-400 text-xs mb-2">Available Pairs</p>
            <div class="flex flex-wrap gap-2">
                <?php
                $displayPairs = count($pairs) > 3 ? array_map(fn($k) => $pairs[$k], (array)array_rand($pairs, 3)) : $pairs;
                foreach ($displayPairs as $pair):
                ?>
                    <span class="px-2 py-1 bg-[#1A1428] rounded-lg text-xs text-white"><?= htmlspecialchars($pair) ?></span>
                <?php endforeach; ?>
            </div>
        </div>

        <div class="bg-[#1A1428] p-3 rounded-lg mb-4">
            <div class="flex items-center justify-between mb-1">
                <p class="text-gray-400 text-xs">Signal Strength (last 30d)</p>
                <span class="text-xs px-2 py-0.5 rounded bg-[#2FE6DE]/10 text-[#2FE6DE]">+<?= $signalPercent ?>%</span>
            </div>
            <div class="h-10 w-full">
                <div id="sparkline-<?= $signalId ?>" class="sparkline-chart" data-values="<?= $sparklineData ?>"></div>
            </div>
        </div>
    </div>

    <div class="p-4 bg-[#191023] border-t border-gray-800/30">
        <a href="signal_details.php?id=<?= $signal['id'] ?>" class="w-full block text-center px-4 py-3 bg-gradient-to-r from-[#2FE6DE] to-[#2FE6DE]/80 text-black rounded-lg font-medium hover:brightness-110 transition-all shadow-lg shadow-[#2FE6DE]/10">
            <i class="fas fa-play-circle mr-2"></i> Start Trading
        </a>
    </div>
</div>

<?php endforeach; ?>

<!-- Include ApexCharts -->
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>

<script>
document.addEventListener("DOMContentLoaded", function () {
    document.querySelectorAll('.sparkline-chart').forEach(function (el) {
        const values = el.dataset.values.split(',').map(Number);
        const chart = new ApexCharts(el, {
            chart: {
                type: 'line',
                height: 80,
                sparkline: { enabled: true },
                toolbar: { show: false },
                background: 'transparent'
            },
            series: [{
                name: 'Signal Strength',
                data: values
            }],
            stroke: {
                curve: 'smooth',
                width: 2
            },
            colors: ['#2FE6DE'],
            tooltip: {
                theme: 'dark',
                style: {
                    fontSize: '12px',
                    color: '#fff'
                },
                y: {
                    formatter: function (val) {
                        return val + '%';
                    },
                    title: {
                        formatter: function () {
                            return 'Strength';
                        }
                    }
                },
                x: { show: false }
            }
        });

        chart.render();
    });
});
</script>

                            
                            
                            
                            
                            
                            
                            
                            
        </div></div>
        
        
        
        
        
        
        
        
        
        
        
        <!-- Signal Trading Guide -->
        <div class="bg-[#0F0A1F] rounded-xl p-4 border border-gray-800/30 shadow-lg">
            <div class="flex items-center mb-4">
                <div class="w-8 h-8 rounded-full bg-[#2FE6DE]/10 flex items-center justify-center mr-2">
                    <i class="fas fa-lightbulb text-[#2FE6DE]"></i>
                </div>
                <h2 class="text-xl font-semibold text-white">How Signal Trading Works</h2>
            </div>
            
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div class="bg-[#191023] p-5 rounded-lg border border-gray-800/30">
                    <div class="w-12 h-12 rounded-full bg-blue-500/10 flex items-center justify-center mb-3">
                        <i class="fas fa-robot text-blue-400 text-xl"></i>
                    </div>
                    <h3 class="text-lg font-medium text-white mb-2">1. Choose a Signal</h3>
                    <p class="text-gray-400 text-sm">Select from our range of AI-powered trading Signals, each with different strategies and performance metrics.</p>
                </div>
                
                <div class="bg-[#191023] p-5 rounded-lg border border-gray-800/30">
                    <div class="w-12 h-12 rounded-full bg-purple-500/10 flex items-center justify-center mb-3">
                        <i class="fas fa-cog text-purple-400 text-xl"></i>
                    </div>
                    <h3 class="text-lg font-medium text-white mb-2">2. Configure Settings</h3>
                    <p class="text-gray-400 text-sm">Set your investment amount, select trading pairs, and customize risk parameters to match your trading goals.</p>
                </div>
                
                <div class="bg-[#191023] p-5 rounded-lg border border-gray-800/30">
                    <div class="w-12 h-12 rounded-full bg-[#2FE6DE]/10 flex items-center justify-center mb-3">
                        <i class="fas fa-chart-line text-[#2FE6DE] text-xl"></i>
                    </div>
                    <h3 class="text-lg font-medium text-white mb-2">3. Earn Profits</h3>
                    <p class="text-gray-400 text-sm">Let the Signal analyze market conditions and execute trades automatically while you monitor performance.</p>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.scrollbar-hide::-webkit-scrollbar {
    display: none;
}
.scrollbar-hide {
    -ms-overflow-style: none;
    scrollbar-width: none;
}
.pulse-animation {
    animation: pulse 2s infinite;
}
@keyframes pulse {
    0% {
        box-shadow: 0 0 0 0 rgba(52, 211, 153, 0.7);
    }
    70% {
        box-shadow: 0 0 0 6px rgba(52, 211, 153, 0);
    }
    100% {
        box-shadow: 0 0 0 0 rgba(52, 211, 153, 0);
    }
}
</style>

<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // Update countdown timers every second
        const countdownTimers = document.querySelectorAll('.countdown-timer');
        let serverTimeOffset = 0;
        
        // Get server time to calculate offset
        function getServerTimeOffset() {
            fetch('/api/server-time')
                .then(response => response.json())
                .then(data => {
                    const serverTime = new Date(data.server_time);
                    const clientTime = new Date();
                    serverTimeOffset = serverTime - clientTime;
                    console.log('Server time offset:', serverTimeOffset, 'ms');
                    // Update timers immediately after getting the offset
                    updateTimers();
                })
                .catch(error => {
                    console.error('Error fetching server time:', error);
                    // If we can't get server time, continue with client time
                    updateTimers();
                });
        }
        
        // Initialize by getting server time offset
        getServerTimeOffset();
        
        function updateTimers() {
            countdownTimers.forEach(timer => {
                const endTimeAttr = timer.getAttribute('data-end-time') || timer.parentElement.getAttribute('data-end-time');
                if (!endTimeAttr) return;
                
                // Parse the date - we're now using ISO8601 format which includes timezone
                let endTime;
                try {
                    // Parse as ISO8601 format
                    endTime = new Date(endTimeAttr);
                    
                    // Check if date is valid
                    if (isNaN(endTime.getTime())) {
                        console.error('Invalid date format:', endTimeAttr);
                        timer.innerHTML = '<span class="text-yellow-400">Invalid time</span>';
                        return;
                    }
                } catch (e) {
                    console.error('Error parsing date:', e);
                    timer.innerHTML = '<span class="text-yellow-400">Invalid time</span>';
                    return;
                }
                
                // Use server time by applying the offset to client time
                const now = new Date(Date.now() + serverTimeOffset);
                const diff = endTime - now;
                
                if (diff <= 0) {
                    timer.innerHTML = '<span class="text-[#2FE6DE]">Completing...</span>';
                    // Add a refresh trigger after a short delay if trade is completing
                    if (!timer.hasAttribute('data-refresh-triggered')) {
                        timer.setAttribute('data-refresh-triggered', 'true');
                        setTimeout(() => {
                            location.reload();
                        }, 60000); 
                    }
                } else {
                    const hours = Math.floor(diff / (1000 * 60 * 60));
                    const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
                    const seconds = Math.floor((diff % (1000 * 60)) / 1000);
                    
                    timer.innerHTML = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
                }
            });
        }
        
        // Initialize sparklines
        document.querySelectorAll('.sparkline').forEach(function(sparklineElement) {
            const values = sparklineElement.getAttribute('data-values').split(',').map(Number);
            
            const options = {
                series: [{
                    data: values
                }],
                chart: {
                    type: 'area',
                    height: '100%',
                    sparkline: {
                        enabled: true
                    },
                    animations: {
                        enabled: true,
                        easing: 'easeinout',
                        speed: 800,
                    }
                },
                stroke: {
                    curve: 'smooth',
                    width: 2,
                },
                fill: {
                    type: 'gradient',
                    gradient: {
                        shadeIntensity: 1,
                        opacityFrom: 0.3,
                        opacityTo: 0.1,
                        stops: [0, 100]
                    }
                },
                colors: ['#2FE6DE'],
                tooltip: {
                    fixed: {
                        enabled: false
                    },
                    x: {
                        show: false
                    },
                    y: {
                        formatter: function(value) {
                            return value + '%';
                        }
                    },
                    marker: {
                        show: false
                    }
                }
            };
            
            const chart = new ApexCharts(sparklineElement, options);
            chart.render();
        });
        
        // Initial update
        updateTimers();
        
        // Update every second
        setInterval(updateTimers, 1000);
    });
</script>
        </main>
    
    
    
    <?php require ("footer.php") ?>