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

// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Get trade ID
$tradeId = $_GET['id'] ?? null;
if (!$tradeId) {
    die("<p style='color: red; text-align:center;'>Trade ID not provided</p>");
}

// Fetch trade
$stmt = $pdo->prepare("SELECT * FROM trade WHERE id = :id LIMIT 1");
$stmt->execute(['id' => $tradeId]);
$trade = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$trade) {
    die("<p style='color: red; text-align:center;'>Trade not found</p>");
}

// Values
$investment = (float)$trade['invested'];
$entryRate  = (float)$trade['entryrate'];
$closeRate  = (float)$trade['closerate'];
$returnR    = (float)$trade['returnr'];
$wrate      = (float)$trade['Wrate'];
$currency   = $trade['user_cur'] ?? '$';
$optionr    = $trade['optionr'];
$asset      = $trade['asset'];
$plan       = $trade['plan'];  // Trading Type
$signa      = $trade['signa'];
$status     = $trade['status'];
$entryTime  = $trade['entrytime'];
$expiryTime = $trade['expirytime'];
$duration   = htmlspecialchars($trade['duratn']); // duration field

// Profit/loss calculations
$profitLoss = $returnR - $investment;
$roi = $investment > 0 ? ($profitLoss / $investment) * 100 : 0;

// Status text for display
if ($status == 1) {
    $statusText = "Active";
    $resultText = "Pending Trade";
    $resultColor = "text-yellow-400";
} else {
    $statusText = "Completed";
    $resultText = $profitLoss >= 0 ? "Win Trade" : "Loss Trade";
    $resultColor = $profitLoss >= 0 ? "text-green-400" : "text-red-400";
}

$entryDate = $entryTime ? date("M d, Y H:i:s", strtotime($entryTime)) : "N/A";
$exitDate  = $expiryTime ? date("M d, Y H:i:s", strtotime($expiryTime)) : "N/A";
?>

<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-8 py-6">

      <!-- Header -->
      <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6">
        <div class="flex items-center">
          <a href="trade_logs.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 History</span>
          </a>
          <h1 class="text-2xl font-bold text-white">Trade #<?= $trade['id'] ?></h1>
        </div>
      </div>

      <!-- Status -->
      <div class="bg-[#0F0A1F] rounded-xl overflow-hidden border border-gray-800/30 shadow-lg mb-6">
        <div class="relative">
          <div class="absolute top-0 right-0 px-4 py-2 <?= $resultColor ?>/20 backdrop-blur-sm rounded-bl-xl">
            <div class="flex items-center">
              <i class="fas fa-trophy <?= $resultColor ?> mr-2"></i>
              <span class="<?= $resultColor ?> font-medium"><?= $resultText ?></span>
            </div>
          </div>

          <div class="p-4 pt-14">
            <!-- Summary -->
            <div class="grid grid-cols-2 sm:grid-cols-4 gap-4 mb-6">
              <div class="bg-[#1A1428] p-4 rounded-lg border border-gray-800/30 shadow-sm">
                <p class="text-gray-400 text-sm">Investment</p>
                <p class="text-white text-xl font-bold"><?= $currency . number_format($investment, 2) ?></p>
              </div>
              <div class="bg-[#1A1428] p-4 rounded-lg border border-gray-800/30 shadow-sm">
                <p class="text-gray-400 text-sm">Direction</p>
                <p class="text-xl font-bold <?= (strtolower($optionr) == 'buy') ? 'text-green-400' : 'text-red-400' ?>">
                  <?= htmlspecialchars($optionr) ?>
                </p>
              </div>
              <div class="bg-[#1A1428] p-4 rounded-lg border border-gray-800/30 shadow-sm">
                <p class="text-gray-400 text-sm">Status</p>
                <p class="text-xl font-bold text-white"><?= $statusText ?></p>
              </div>
              <div class="bg-[#1A1428] p-4 rounded-lg border border-gray-800/30 shadow-sm">
                <p class="text-gray-400 text-sm">Profit/Loss</p>
                <p class="text-xl font-bold <?= $resultColor ?>">
                  <?= $status == 1 ? '-- --' : $currency . number_format($profitLoss, 2) ?>
                </p>
                <p class="text-sm <?= $resultColor ?>/70">
                  <?= $status == 1 ? '-- --' : round($roi, 2) . '% ROI' ?>
                </p>
              </div>
            </div>

            <!-- Chart -->
            <div class="bg-[#1A1428] p-5 rounded-lg border border-gray-800/30 shadow-sm mb-6">
              <h3 class="text-lg font-semibold text-white mb-3">Price Simulation</h3>
              <div id="tradeChart" class="w-full h-64"></div>
            </div>

            <!-- Details -->
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-4">
              <div class="bg-[#1A1428] rounded-lg p-5 border border-gray-800/30 shadow-sm">
                <h3 class="text-lg font-semibold text-white mb-3">Trade Details</h3>
                <div class="space-y-3">
                  <div class="flex justify-between"><span class="text-gray-400">Trading Pair</span><span class="text-white font-medium"><?= htmlspecialchars($asset) ?></span></div>
                  <div class="flex justify-between"><span class="text-gray-400">Trading Type</span><span class="text-white"><?= htmlspecialchars($plan) ?></span></div>
                  <div class="flex justify-between"><span class="text-gray-400">Signal</span><span class="text-white"><?= htmlspecialchars($signa) ?></span></div>
                  <div class="flex justify-between"><span class="text-gray-400">Entry Rate</span><span class="text-white"><?= number_format($entryRate, 5) ?></span></div>
                  <div class="flex justify-between"><span class="text-gray-400">Close Rate</span><span class="text-white"><?= number_format($closeRate, 5) ?></span></div>
                  <div class="flex justify-between"><span class="text-gray-400">Return</span>
                    <span class="text-white">
                      <?= $status == 1 ? '-- --' : $currency . number_format($returnR, 2) ?>
                    </span>
                  </div>
                  <div class="flex justify-between"><span class="text-gray-400">Win Rate</span>
                    <span class="text-white">
                      <?= $status == 1 ? '-- --' : round($wrate, 2) . '%' ?>
                    </span>
                  </div>
                  <div class="flex justify-between"><span class="text-gray-400">Duration</span><span class="text-white"><?= $duration ?></span></div>
                  <div class="flex justify-between"><span class="text-gray-400">Start Time</span><span class="text-white"><?= $entryDate ?></span></div>
                  <div class="flex justify-between"><span class="text-gray-400">End Time</span><span class="text-white"><?= $exitDate ?></span></div>
                </div>
              </div>

              <div class="bg-[#1A1428] rounded-lg p-5 border border-gray-800/30 shadow-sm">
                <h3 class="text-lg font-semibold text-white mb-3">Signal Analysis</h3>
                <p class="text-gray-500 text-sm">Signal analysis not available for this trade.</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</main>

<!-- ApexCharts -->
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
<script>
document.addEventListener("DOMContentLoaded", function () {
  let entry = <?= $entryRate ?>;
  let close = <?= $closeRate ?>;
  let steps = 10;
  let data = [];
  for (let i = 0; i <= steps; i++) {
    let progress = i / steps;
    let value = entry + (close - entry) * progress;
    value += (Math.random() - 0.5) * (value * 0.02);
    data.push(parseFloat(value.toFixed(5)));
  }

  var options = {
    chart: {
      type: 'line',
      height: 300,
      background: 'transparent',
      toolbar: { show: false }
    },
    series: [{
      name: "Price",
      data: data
    }],
    xaxis: {
      categories: Array.from({length: steps+1}, (_,i) => "Step " + i),
      labels: { style: { colors: "#9CA3AF" } }
    },
    yaxis: {
      labels: { style: { colors: "#9CA3AF" } }
    },
    stroke: {
      curve: 'smooth',
      width: 3
    },
    colors: ['#2FE6DE'],
    markers: {
      size: 4,
      colors: ['#fff'],
      strokeColors: '#2FE6DE'
    },
    grid: {
      borderColor: "#1F2937",
      strokeDashArray: 4
    },
    tooltip: {
      theme: 'dark',
      style: {
        fontSize: '13px',
        color: '#FFFFFF'
      },
      x: {
        show: true
      },
      y: {
        formatter: function (val) {
          return val.toFixed(5);
        }
      }
    }
  };

  new ApexCharts(document.querySelector("#tradeChart"), options).render();
});
</script>

<?php require("footer.php"); ?>
