<?php
session_start();
require "../config.php";

$user_email = $_SESSION['email'] ?? null;
if (!$user_email) {
    echo "<tr><td colspan='7' class='text-center text-red-500 py-4'>Not logged in</td></tr>";
    exit;
}

$stmt = $pdo->prepare("SELECT * FROM trade WHERE email=:email AND status IN (1) ORDER BY id DESC");
$stmt->execute([':email' => $user_email]);
$activeTrades = $stmt->fetchAll(PDO::FETCH_ASSOC);

if ($activeTrades):
    foreach ($activeTrades as $trade):
        $endTime = strtotime($trade['expirytime']);
        $now = time();
        $remaining = $endTime - $now;

        // Default status
        $statusText = "Processing";
        $statusClass = "bg-yellow-500/20 text-yellow-400";

        if ($remaining <= 0) {
            $statusText = "Completing";
            $statusClass = "bg-orange-500/20 text-orange-400";

            if ($remaining <= -10 && $trade['status'] == 1) {
                // Random rates and lot
                $entry = mt_rand(1, 99999) / 1000;
                $close = mt_rand(1, 99999) / 1000;

                $entryrate = max(0.01, min($entry, 10000));
                $closerate = max(0.01, min($close, 10000));
                $lot       = mt_rand(1, 10000) / 1000;

                $amount    = (float)$trade['invested'];
                $cur_rate  = isset($trade['user_rate']) ? (float)$trade['user_rate'] : 1;

               
            // ✅ Return calculation divided by cur_rate 

              $returnr = (((($entryrate + $closerate) / 1000) * $lot * $amount) + $amount) / $cur_rate;

              $returnr2 = (((($entryrate + $closerate) / 1000) * $lot * $amount) + $amount);
              
              // ✅ Calculate Wrate percentage
                $Wrate = 0;
                if ($amount > 0) {
                $Wrate = (($returnr2 - $amount) / $amount) * 100;
                     }


                // Update trade
                $upd = $pdo->prepare("
                    UPDATE trade 
                    SET status=2,  Wrate=:Wrate, closerate=:closerate, returnr=:returnr
                    WHERE id=:id
                ");
                $upd->execute([
                    ':Wrate' => $Wrate,
                    ':closerate' => $closerate,
                    ':returnr'   => $returnr2,
                    ':id'        => $trade['id']
                ]);

                // Update user profits
                $updUser = $pdo->prepare("UPDATE logins SET iprofit = iprofit + :amt WHERE email=:email");
                $updUser->execute([
                    ':amt'   => $returnr,
                    ':email' => $user_email
                ]);

                $statusText  = "Completed";
                $statusClass = "bg-green-500/20 text-green-400";
            }
        }
        ?>

        <style>
        /* Animated dots */
        .dots::after {
          content: '';
          display: inline-block;
          width: 1ch;
          animation: dots 1.5s steps(3, end) infinite;
        }
        @keyframes dots {
          0%   { content: ''; }
          33%  { content: '.'; }
          66%  { content: '..'; }
          100% { content: '...'; }
        }
        </style>

            <thead>
                <tr class="text-left text-gray-400 text-sm border-b border-gray-800/50">
                    <th class="pb-3 pl-2">Signal</th>
                    <th class="pb-3">Pair</th>
                    <th class="pb-3">Amount</th>
                    <th class="pb-3">Entry Price</th>
                    <th class="pb-3">Time Remaining</th>
                    <th class="pb-3">Direction</th>
                    <th class="pb-3">Status</th>
                </tr>
            </thead>
            <tbody>
                <tr class="border-b border-gray-800/30 text-white">
                    <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['user_cur']) ?><?= number_format($trade['invested'], 2) ?></td>
                    <td class="py-4"><?= htmlspecialchars($trade['user_cur']) ?><?= number_format($trade['entryrate'], 2) ?></td>
                    <td class="py-4">
                        <span class="countdown-timer font-mono font-medium"
                              data-end-time="<?= htmlspecialchars($trade['expirytime']) ?>">
                            <?= $remaining > 0 ? gmdate("i:s", $remaining) : "Expired" ?>
                        </span>
                    </td>
                    <td class="py-4">
                        <?php if ($trade['optionr'] == "BUY"): ?>
                            <span class="px-2 py-1 rounded-full text-xs bg-green-500/20 text-green-400">
                                <i class="fas fa-arrow-up mr-1"></i> Buy
                            </span>
                        <?php else: ?>
                            <span class="px-2 py-1 rounded-full text-xs bg-red-500/20 text-red-400">
                                <i class="fas fa-arrow-down mr-1"></i> Sell
                            </span>
                        <?php endif; ?>
                    </td>
                    <td class="py-4">
                        <?php if ($statusText === "Processing"): ?>
                            <div class="px-4 py-2 rounded-xl bg-yellow-400/10 text-yellow-400 text-sm flex items-center gap-2">
                                <i class="fas fa-spinner fa-spin"></i> <span class="dots">Processing</span>
                            </div>
                        <?php else: ?>
                            <span class="px-2 py-1 rounded-full text-xs <?= $statusClass ?>">
                                <?= $statusText ?>
                            </span>
                        <?php endif; ?>
                    </td>
                </tr>
            </tbody>

    <?php
    endforeach;
else:
    echo "
        <div class='text-center py-10'>
            <div class='w-16 h-16 rounded-full bg-[#2A243B] flex items-center justify-center mx-auto mb-4'>
                <i class='fas fa-robot text-[#2FE6DE] text-2xl'></i>
            </div>
            <h3 class='text-xl font-semibold text-white mb-2'>No Active Signal Trades</h3>
            <p class='text-gray-400 mb-6'>Start a new trade to see your active Signals here</p>
            <a href='#available-bots' class='mt-4 inline-block px-6 py-2.5 bg-[#2FE6DE] text-black rounded-lg font-medium hover:bg-[#27c5be] transition-colors focus:outline-none focus:ring-2 focus:ring-[#2FE6DE]/50'>
                Get Started
            </a>
        </div>
    ";
endif;
