<?php
session_start();

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if (!isset($_SESSION['user_id'])) {
    header("Location: ../login.php");
    exit; 
}

require_once "include/db.php";
mysqli_set_charset($conn, "utf8mb4");

$userId = intval($_SESSION['user_id']);

// Fetch User Data for Theme
$sql = "SELECT * FROM users WHERE id = $userId LIMIT 1";
$result = mysqli_query($conn, $sql);
$currentUser = ($result && mysqli_num_rows($result) > 0) ? mysqli_fetch_assoc($result) : null;

if (!$currentUser) {
    header("Location: ../login.php");
    exit;
}

$dbTheme = $_SESSION['theme'] ?? ($currentUser['theme'] ?? '#3b82f6'); // Default Digital Blue

// ==========================================
// 🔴 LIVE TRADING DATA FROM DATABASE
// Using the provided schema: `trade_type`, `entry_price`, `exit_price`, etc.
// ==========================================

$tradeData = [];
$totalTrades = 0;
$wonTrades = 0;
$lostTrades = 0;
$netPnL = 0;

// Fetch live trades for this specific user
$tradeQuery = mysqli_query($conn, "SELECT `id`, `user_id`, `asset`, `trade_type`, `amount`, `entry_price`, `exit_price`, `pnl`, `status`, `created_at`, `expires_at`, `closed_at`, `duration`, `market` FROM `trades` WHERE `user_id` = $userId ORDER BY `created_at` DESC");

if ($tradeQuery && mysqli_num_rows($tradeQuery) > 0) {
    while ($row = mysqli_fetch_assoc($tradeQuery)) {
        // Format the data for the Alpine.js frontend
        $tradeData[] = [
            'id'          => 'TRD-' . $row['id'],
            'asset'       => $row['asset'],
            'type'        => ucfirst($row['trade_type']), // e.g., Long or Short
            'amount'      => number_format((float)$row['amount'], 2),
            'duration'    => $row['duration'],
            'market'      => $row['market'],
            'open_price'  => number_format((float)$row['entry_price'], 4),
            'close_price' => $row['exit_price'] ? number_format((float)$row['exit_price'], 4) : null,
            'pnl'         => (float)$row['pnl'],
            'status'      => strtolower($row['status']), // 'open', 'won', 'lost'
            'date'        => date('M d, Y', strtotime($row['created_at'])),
            'time'        => date('h:i A', strtotime($row['created_at']))
        ];

        // Tally up statistics
        $totalTrades++;
        if (strtolower($row['status']) === 'won') { 
            $wonTrades++; 
            $netPnL += (float)$row['pnl']; 
        }
        if (strtolower($row['status']) === 'lost') { 
            $lostTrades++; 
            $netPnL += (float)$row['pnl']; 
        }
    }
}

// Calculate overall Win Rate safely
$totalClosed = $wonTrades + $lostTrades;
$winRate = ($totalClosed > 0) ? round(($wonTrades / $totalClosed) * 100, 1) : 0;

// --- DYNAMIC PNL CHART GENERATOR ---
$pnlChartData = [0]; // Chart always starts at 0 baseline
$cumulativePnL = 0;
$pnlLabels = ['Start'];

// Reverse trade data so the chart flows chronologically (Left to Right)
$chronologicalTrades = array_reverse($tradeData);

foreach ($chronologicalTrades as $trd) {
    // Only chart closed trades (won/lost)
    if ($trd['status'] !== 'open') {
        $cumulativePnL += $trd['pnl'];
        $pnlChartData[] = round($cumulativePnL, 2);
        $pnlLabels[] = $trd['date']; // Use trade date as x-axis label
    }
}

// Fallback if there are no closed trades yet
if (count($pnlChartData) === 1) {
    $pnlChartData = [0, 0, 0, 0, 0];
    $pnlLabels = ['', '', '', '', ''];
}
?>

<?php include "include/header.php"?>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>

<style>
    :root {
        --primary-theme: <?php echo htmlspecialchars($dbTheme, ENT_QUOTES, 'UTF-8'); ?>;
        --primary-rgb: <?php 
            $hex = ltrim($dbTheme, '#');
            $r = hexdec(substr($hex, 0, 2));
            $g = hexdec(substr($hex, 2, 2));
            $b = hexdec(substr($hex, 4, 2));
            echo "$r, $g, $b";
        ?>;
    }
    
    .text-theme { color: var(--primary-theme) !important; }
    .bg-theme { background-color: var(--primary-theme) !important; }
    .border-theme { border-color: var(--primary-theme) !important; }
    
    .glass-card {
        background: rgba(255, 255, 255, 0.8);
        backdrop-filter: blur(12px);
        border: 1px solid rgba(0, 0, 0, 0.05);
    }
    .dark .glass-card {
        background: rgba(15, 23, 42, 0.6);
        border: 1px solid rgba(255, 255, 255, 0.05);
    }

    .filter-btn { transition: all 0.3s ease; }
    .filter-btn.active {
        background: var(--primary-theme);
        color: white;
        box-shadow: 0 4px 15px -3px rgba(var(--primary-rgb), 0.4);
    }
    
    .trade-row { transition: all 0.2s ease; }
    .trade-row:hover {
        background: rgba(var(--primary-rgb), 0.03);
    }
    
    /* Table specific styling for mobile scrolling */
    .table-container {
        scrollbar-width: thin;
        scrollbar-color: rgba(var(--primary-rgb), 0.3) transparent;
    }
    .table-container::-webkit-scrollbar { height: 6px; }
    .table-container::-webkit-scrollbar-thumb { background: rgba(var(--primary-rgb), 0.3); border-radius: 10px; }

    @media print {
        .no-print { display: none !important; }
        body { background: white !important; color: black !important; }
        .glass-card { border: 1px solid #eee !important; box-shadow: none !important; }
    }
</style>

<?php include "include/nav.php"?>

<div class="flex min-h-screen bg-slate-50 dark:bg-[#070b14] transition-colors duration-300" 
     x-data='{ 
        filter: "all", 
        currentPage: 1,
        itemsPerPage: 5,
        trades: <?= json_encode($tradeData, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>,
        
        get filteredTrades() {
            if (this.filter === "all") return this.trades;
            return this.trades.filter(t => t.status === this.filter);
        },
        
        get totalPages() {
            return Math.max(1, Math.ceil(this.filteredTrades.length / this.itemsPerPage));
        },
        
        get paginatedTrades() {
            let start = (this.currentPage - 1) * this.itemsPerPage;
            let end = start + this.itemsPerPage;
            return this.filteredTrades.slice(start, end);
        },
        
        changeFilter(newFilter) {
            this.filter = newFilter;
            this.currentPage = 1;
        }
     }'>
  
  <?php include "include/sidebar.php"?>
  
  <main class="flex-1 min-w-0 md:ml-72 pb-24 md:pb-8">
    <div class="max-w-screen-2xl mx-auto px-4 sm:px-6 py-8">

      <div class="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-8">
        <div>
          <h1 class="text-3xl font-black text-slate-900 dark:text-white tracking-tight">
            Trading <span class="text-theme">Logbook</span>
          </h1>
          <p class="text-sm text-slate-500 dark:text-slate-400 mt-1">Analyze your market performance and historical trades.</p>
        </div>
        <div class="no-print flex gap-3">
            <a href="trade_terminal.php" class="px-5 py-2.5 bg-theme text-white font-bold uppercase tracking-widest rounded-xl text-xs hover:brightness-110 transition-all flex items-center gap-2 shadow-theme">
                <i data-lucide="line-chart" class="w-4 h-4"></i> Trade Now
            </a>
            <button onclick="window.print()" class="px-5 py-2.5 bg-slate-200 dark:bg-slate-800 text-slate-700 dark:text-slate-300 font-bold uppercase tracking-widest rounded-xl text-xs hover:bg-slate-300 dark:hover:bg-slate-700 transition-all flex items-center gap-2">
                <i data-lucide="download" class="w-4 h-4"></i> Export
            </button>
        </div>
      </div>

      <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8">
        
        <div class="glass-card rounded-[2rem] p-5 shadow-sm border-t-2 border-t-theme">
            <p class="text-[9px] font-black uppercase tracking-widest text-slate-400 mb-1">Win Rate</p>
            <h3 class="text-2xl font-black text-slate-900 dark:text-white"><?= $winRate ?>%</h3>
        </div>

        <div class="glass-card rounded-[2rem] p-5 shadow-sm border-t-2 border-t-emerald-500">
            <p class="text-[9px] font-black uppercase tracking-widest text-slate-400 mb-1">Net PnL</p>
            <h3 class="text-2xl font-black <?= $netPnL >= 0 ? 'text-emerald-500' : 'text-rose-500' ?>">
                <?= $netPnL >= 0 ? '+' : '' ?>$<?= number_format($netPnL, 2) ?>
            </h3>
        </div>

        <div class="glass-card rounded-[2rem] p-5 shadow-sm">
            <p class="text-[9px] font-black uppercase tracking-widest text-slate-400 mb-1">Won Trades</p>
            <h3 class="text-2xl font-black text-slate-900 dark:text-white"><?= $wonTrades ?></h3>
        </div>

        <div class="glass-card rounded-[2rem] p-5 shadow-sm">
            <p class="text-[9px] font-black uppercase tracking-widest text-slate-400 mb-1">Lost Trades</p>
            <h3 class="text-2xl font-black text-slate-900 dark:text-white"><?= $lostTrades ?></h3>
        </div>

      </div>

      <div class="grid grid-cols-1 xl:grid-cols-3 gap-8">
        
        <div class="glass-card rounded-[2.5rem] p-6 shadow-xl border border-slate-200 dark:border-slate-800 flex flex-col no-print">
            <h3 class="text-xs font-black uppercase tracking-widest text-slate-400 mb-4">Cumulative PnL Curve</h3>
            <div id="pnlChart" class="w-full flex-1 min-h-[250px]"></div>
        </div>

        <div class="xl:col-span-2 glass-card rounded-[2.5rem] border border-slate-200 dark:border-slate-800 shadow-xl overflow-hidden flex flex-col">
            
            <div class="p-6 border-b border-slate-200 dark:border-slate-800/50 flex flex-wrap gap-2 bg-slate-50/50 dark:bg-slate-900/20 no-print">
                <button @click="changeFilter('all')" :class="filter === 'all' ? 'active' : 'bg-slate-200 dark:bg-slate-800 text-slate-600 dark:text-slate-400'" class="filter-btn px-5 py-2 rounded-xl text-[10px] font-black uppercase tracking-widest">
                    All
                </button>
                <button @click="changeFilter('open')" :class="filter === 'open' ? 'active' : 'bg-slate-200 dark:bg-slate-800 text-slate-600 dark:text-slate-400'" class="filter-btn px-5 py-2 rounded-xl text-[10px] font-black uppercase tracking-widest">
                    Open Positions
                </button>
                <button @click="changeFilter('won')" :class="filter === 'won' ? 'active bg-emerald-500' : 'bg-slate-200 dark:bg-slate-800 text-slate-600 dark:text-slate-400'" class="filter-btn px-5 py-2 rounded-xl text-[10px] font-black uppercase tracking-widest">
                    Profits
                </button>
                <button @click="changeFilter('lost')" :class="filter === 'lost' ? 'active bg-rose-500' : 'bg-slate-200 dark:bg-slate-800 text-slate-600 dark:text-slate-400'" class="filter-btn px-5 py-2 rounded-xl text-[10px] font-black uppercase tracking-widest">
                    Losses
                </button>
            </div>

            <div class="table-container overflow-x-auto w-full p-2">
                <table class="w-full text-left whitespace-nowrap">
                    <thead>
                        <tr class="text-[9px] font-black uppercase tracking-widest text-slate-400 border-b border-slate-200 dark:border-slate-800">
                            <th class="p-4">Asset / ID</th>
                            <th class="p-4">Position</th>
                            <th class="p-4">Open / Close Price</th>
                            <th class="p-4 text-right">Result (PnL)</th>
                            <th class="p-4 text-right">Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr x-show="filteredTrades.length === 0" style="display: none;">
                            <td colspan="5" class="text-center py-12">
                                <i data-lucide="inbox" class="w-10 h-10 text-slate-300 mx-auto mb-3 opacity-50"></i>
                                <p class="text-xs font-bold text-slate-500 uppercase tracking-widest">No trades found.</p>
                            </td>
                        </tr>

                        <template x-for="trade in paginatedTrades" :key="trade.id">
                            <tr class="trade-row border-b border-slate-100 dark:border-slate-800/50 last:border-0">
                                
                                <td class="p-4">
                                    <div class="flex items-center gap-3">
                                        <div class="w-8 h-8 rounded-lg bg-theme/10 flex items-center justify-center text-theme flex-shrink-0">
                                            <i data-lucide="candlestick-chart" class="w-4 h-4"></i>
                                        </div>
                                        <div>
                                            <p class="text-sm font-black text-slate-900 dark:text-white" x-text="trade.asset"></p>
                                            <p class="text-[9px] font-bold text-slate-400 tracking-widest mt-0.5" x-text="trade.id + ' • ' + trade.date"></p>
                                        </div>
                                    </div>
                                </td>

                                <td class="p-4">
                                    <span class="px-2 py-1 rounded text-[9px] font-black uppercase tracking-widest"
                                          :class="trade.type === 'Long' || trade.type === 'Buy' ? 'bg-emerald-500/10 text-emerald-500' : 'bg-rose-500/10 text-rose-500'"
                                          x-text="trade.type + ' - $' + trade.amount">
                                    </span>
                                </td>

                                <td class="p-4">
                                    <p class="text-xs font-bold text-slate-900 dark:text-white" x-text="'O: ' + trade.open_price"></p>
                                    <p class="text-[10px] font-medium text-slate-500 mt-0.5" x-text="trade.close_price ? 'C: ' + trade.close_price : 'C: --'"></p>
                                </td>

                                <td class="p-4 text-right">
                                    <p class="text-sm font-black"
                                       :class="{
                                           'text-emerald-500': trade.pnl > 0 && trade.status !== 'open',
                                           'text-rose-500': trade.pnl < 0 && trade.status !== 'open',
                                           'text-slate-400': trade.status === 'open'
                                       }"
                                       x-text="trade.pnl > 0 ? '+$' + parseFloat(trade.pnl).toFixed(2) : '-$' + Math.abs(trade.pnl).toFixed(2)">
                                    </p>
                                </td>

                                <td class="p-4 text-right">
                                    <span class="px-3 py-1 rounded-full text-[9px] font-black uppercase tracking-widest"
                                          :class="{
                                              'bg-emerald-500/10 text-emerald-500 border border-emerald-500/20': trade.status === 'won',
                                              'bg-amber-500/10 text-amber-500 border border-amber-500/20': trade.status === 'open',
                                              'bg-rose-500/10 text-rose-500 border border-rose-500/20': trade.status === 'lost',
                                          }"
                                          x-text="trade.status">
                                    </span>
                                </td>

                            </tr>
                        </template>
                    </tbody>
                </table>
            </div>

            <div x-show="totalPages > 1" style="display: none;" class="p-6 border-t border-slate-200 dark:border-slate-800 bg-slate-50/50 dark:bg-slate-900/20 mt-auto no-print">
                <div class="flex items-center justify-between">
                    <button @click="currentPage--" :disabled="currentPage === 1" 
                            class="px-4 py-2 rounded-xl text-xs font-bold bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-slate-600 dark:text-slate-400 disabled:opacity-50 hover:bg-slate-50 dark:hover:bg-slate-700 transition-colors">
                        Prev
                    </button>
                    
                    <span class="text-[10px] font-black tracking-widest uppercase text-slate-400">
                        Page <span x-text="currentPage" class="text-slate-900 dark:text-white"></span> / <span x-text="totalPages" class="text-slate-900 dark:text-white"></span>
                    </span>

                    <button @click="currentPage++" :disabled="currentPage === totalPages" 
                            class="px-4 py-2 rounded-xl text-xs font-bold bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-slate-600 dark:text-slate-400 disabled:opacity-50 hover:bg-slate-50 dark:hover:bg-slate-700 transition-colors">
                        Next
                    </button>
                </div>
            </div>

        </div>

      </div>

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

<?php if(file_exists('include/footer.php')) include "include/footer.php"; ?>

<script src="https://unpkg.com/lucide@latest"></script>
<script>
    document.addEventListener('DOMContentLoaded', () => {
        lucide.createIcons();

        // Check if dark mode is active for chart theming
        const isDark = document.documentElement.classList.contains('dark');
        const textColor = isDark ? '#94a3b8' : '#64748b'; 

        // Load dynamic chart data populated from PHP
        const dynamicPnL = <?= json_encode($pnlChartData) ?>;
        const dynamicLabels = <?= json_encode($pnlLabels) ?>;

        // Ensure the chart line color matches your overall profit or loss baseline
        const finalPnL = dynamicPnL[dynamicPnL.length - 1];
        const lineColor = finalPnL >= 0 ? '#10b981' : '#f43f5e'; // Emerald or Rose

        // ApexCharts Line Chart
        var options = {
            series: [{
                name: 'Net PnL',
                data: dynamicPnL
            }],
            chart: {
                type: 'area',
                height: 250,
                fontFamily: 'inherit',
                background: 'transparent',
                toolbar: { show: false }
            },
            colors: [lineColor], 
            fill: {
                type: 'gradient',
                gradient: {
                    shadeIntensity: 1,
                    opacityFrom: 0.4,
                    opacityTo: 0.05,
                    stops: [0, 100]
                }
            },
            dataLabels: { enabled: false },
            stroke: { curve: 'smooth', width: 3 },
            xaxis: {
                categories: dynamicLabels,
                axisBorder: { show: false },
                axisTicks: { show: false },
                labels: {
                    show: false, // Hide labels to keep chart clean, visible on tooltip
                    style: { colors: textColor, fontSize: '10px', fontWeight: 700 }
                }
            },
            yaxis: {
                labels: {
                    style: { colors: textColor, fontSize: '10px', fontWeight: 700 },
                    formatter: (value) => { return '$' + value }
                }
            },
            grid: {
                borderColor: isDark ? '#1e293b' : '#f1f5f9',
                strokeDashArray: 4,
                yaxis: { lines: { show: true } }
            },
            tooltip: {
                theme: isDark ? 'dark' : 'light',
                y: { formatter: function (val) { return "$" + val } }
            }
        };

        var chart = new ApexCharts(document.querySelector("#pnlChart"), options);
        chart.render();
    });

    // Re-initialize Lucide icons when Alpine paginates or filters
    document.addEventListener('alpine:initialized', () => {
        Alpine.effect(() => {
            setTimeout(() => { lucide.createIcons(); }, 10);
        });
    });
</script>

</body>
</html> 