<?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 and Balance
$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');
$userBalance = (float)($currentUser['balance'] ?? 0);

// ==========================================
// 🔴 LIVE PORTFOLIO DATA FROM DATABASE
// ==========================================
$investedBalance = 0; 
$totalProfit = 0;
$activeAssets = [];

// Arrays to populate the Javascript Chart dynamically
$chartLabels = [];
$chartSeries = [];

// Fetch user's held assets
$assetQuery = mysqli_query($conn, "SELECT * FROM user_assets WHERE user_id = $userId ORDER BY current_price * amount DESC");

if ($assetQuery && mysqli_num_rows($assetQuery) > 0) {
    while ($row = mysqli_fetch_assoc($assetQuery)) {
        $amount = (float)$row['amount'];
        $buyPrice = (float)$row['buy_price'];
        $currentPrice = (float)$row['current_price'];
        
        $totalCost = $amount * $buyPrice;
        $currentValue = $amount * $currentPrice;
        $pnlValue = $currentValue - $totalCost;
        
        // Calculate Percentage
        $pnlPercentage = ($totalCost > 0) ? ($pnlValue / $totalCost) * 100 : 0;
        $status = ($pnlValue >= 0) ? 'profit' : 'loss';
        $pnlFormatted = ($pnlValue >= 0 ? '+' : '') . number_format($pnlPercentage, 2) . '%';

        // Add to global totals
        $investedBalance += $currentValue;
        $totalProfit += $pnlValue;

        $activeAssets[] = [
            'name'   => $row['name'],
            'symbol' => $row['symbol'],
            'icon'   => $row['icon'],
            'color'  => $row['color'],
            'amount' => rtrim(rtrim(number_format($amount, 4, '.', ''), '0'), '.'), // Removes trailing zeros
            'value'  => $currentValue,
            'pnl'    => $pnlFormatted,
            'status' => $status
        ];

        // Push data to chart arrays
        $chartLabels[] = $row['name'];
        $chartSeries[] = round($currentValue, 2);
    }
}

$totalValue = $userBalance + $investedBalance;

// Add Available Cash to the Chart Data
if ($userBalance > 0 || empty($chartSeries)) {
    $chartLabels[] = 'Available Cash';
    $chartSeries[] = round($userBalance, 2);
}
// Fallback if absolutely no funds exist
if (empty($chartSeries) || array_sum($chartSeries) == 0) {
    $chartLabels = ['No Funds'];
    $chartSeries = [1]; 
}

// Overall Portfolio Percentage
$totalCostBasis = $investedBalance - $totalProfit;
$overallPercent = ($totalCostBasis > 0) ? ($totalProfit / $totalCostBasis) * 100 : 0;
$profitPercentage = ($overallPercent >= 0 ? '+' : '') . number_format($overallPercent, 2) . '%';
?>

<?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);
    }

    .asset-row { transition: all 0.2s ease; }
    .asset-row:hover {
        transform: translateY(-2px);
        box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1);
        border-color: rgba(var(--primary-rgb), 0.3);
    }

    /* Chart specific overrides for Dark Mode */
    .dark .apexcharts-tooltip {
        background: #0f172a !important;
        border: 1px solid #1e293b !important;
        box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.5) !important;
        color: #fff !important;
    }
    .dark .apexcharts-tooltip-title {
        background: #1e293b !important;
        border-bottom: 1px solid #334155 !important;
    }
</style>

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

<div class="flex min-h-screen bg-slate-50 dark:bg-[#070b14] transition-colors duration-300">
  
  <?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">
            My <span class="text-theme">Portfolio</span>
          </h1>
          <p class="text-sm text-slate-500 dark:text-slate-400 mt-1">Real-time breakdown of your investments and assets.</p>
        </div>
        <div class="flex gap-3">
            <a href="deposit.php" class="px-5 py-2.5 bg-slate-900 dark:bg-white text-white dark:text-slate-900 font-bold uppercase tracking-widest rounded-xl text-[10px] hover:-translate-y-0.5 transition-all shadow-lg flex items-center gap-2">
                <i data-lucide="plus" class="w-4 h-4"></i> Add Funds
            </a>
        </div>
      </div>

      <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
        <div class="glass-card rounded-[2rem] p-6 shadow-sm border-t-4 border-t-theme relative overflow-hidden">
            <div class="absolute -right-6 -bottom-6 opacity-5">
                <i data-lucide="pie-chart" class="w-32 h-32"></i>
            </div>
            <p class="text-[10px] font-black uppercase tracking-widest text-slate-400 mb-2">Net Portfolio Value</p>
            <h3 class="text-3xl lg:text-4xl font-black text-slate-900 dark:text-white tracking-tight">
                $<?= number_format($totalValue, 2) ?>
            </h3>
            <div class="mt-4 flex items-center gap-2">
                <span class="px-2 py-1 rounded bg-emerald-500/10 text-emerald-500 text-[10px] font-bold flex items-center gap-1">
                    <i data-lucide="trending-up" class="w-3 h-3"></i> <?= $profitPercentage ?>
                </span>
                <span class="text-xs text-slate-500 font-medium">All Time</span>
            </div>
        </div>

        <div class="glass-card rounded-[2rem] p-6 shadow-sm flex flex-col justify-center">
            <div class="flex justify-between items-center mb-4 pb-4 border-b border-slate-200 dark:border-slate-800">
                <div>
                    <p class="text-[10px] font-black uppercase tracking-widest text-slate-400 mb-1">Active Investments</p>
                    <p class="text-xl font-black text-slate-900 dark:text-white">$<?= number_format($investedBalance, 2) ?></p>
                </div>
                <div class="w-10 h-10 rounded-full bg-theme/10 flex items-center justify-center text-theme">
                    <i data-lucide="activity" class="w-5 h-5"></i>
                </div>
            </div>
            <div class="flex justify-between items-center">
                <div>
                    <p class="text-[10px] font-black uppercase tracking-widest text-slate-400 mb-1">Available Cash</p>
                    <p class="text-xl font-black text-slate-900 dark:text-white">$<?= number_format($userBalance, 2) ?></p>
                </div>
                <div class="w-10 h-10 rounded-full bg-slate-200 dark:bg-slate-800 flex items-center justify-center text-slate-500">
                    <i data-lucide="wallet" class="w-5 h-5"></i>
                </div>
            </div>
        </div>

        <div class="glass-card rounded-[2rem] p-6 shadow-sm border-t-4 border-t-emerald-500 flex flex-col justify-center">
            <p class="text-[10px] font-black uppercase tracking-widest text-slate-400 mb-2">Total Profit / Loss</p>
            <h3 class="text-3xl font-black <?= $totalProfit >= 0 ? 'text-emerald-500' : 'text-rose-500' ?> tracking-tight">
                <?= $totalProfit >= 0 ? '+' : '' ?>$<?= number_format($totalProfit, 2) ?>
            </h3>
            <p class="text-xs text-slate-500 mt-2 font-medium leading-relaxed">
                Your portfolio is currently <?= $totalProfit >= 0 ? 'outperforming' : 'underperforming' ?> the market baseline.
            </p>
        </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 items-center justify-center">
            <h3 class="text-xs font-black uppercase tracking-widest text-slate-400 w-full mb-4">Asset Allocation</h3>
            <div id="allocationChart" class="w-full flex justify-center -ml-4"></div>
        </div>

        <div class="xl:col-span-2 glass-card rounded-[2.5rem] p-6 md:p-8 shadow-xl border border-slate-200 dark:border-slate-800">
            <div class="flex justify-between items-center mb-6">
                <h3 class="text-xs font-black uppercase tracking-widest text-slate-400">Current Holdings</h3>
                <a href="#" class="text-[10px] font-bold text-theme uppercase tracking-widest hover:underline">View Markets</a>
            </div>

            <div class="space-y-4">
                <?php if (empty($activeAssets)): ?>
                    <div class="text-center py-12">
                        <i data-lucide="folder-open" 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 active investments found.</p>
                    </div>
                <?php else: ?>
                    <?php foreach($activeAssets as $asset): ?>
                        <div class="asset-row flex flex-col sm:flex-row sm:items-center justify-between p-4 bg-slate-50 dark:bg-slate-900/40 rounded-2xl border border-slate-200 dark:border-slate-800/50 cursor-pointer">
                            
                            <div class="flex items-center gap-4 mb-4 sm:mb-0">
                                <div class="w-12 h-12 rounded-xl bg-<?= $asset['color'] ?>-500/10 flex items-center justify-center text-<?= $asset['color'] ?>-500">
                                    <i data-lucide="<?= $asset['icon'] ?>" class="w-6 h-6"></i>
                                </div>
                                <div>
                                    <h4 class="text-sm font-black text-slate-900 dark:text-white"><?= htmlspecialchars($asset['name']) ?></h4>
                                    <p class="text-[10px] font-bold text-slate-400 tracking-widest uppercase mt-0.5"><?= htmlspecialchars($asset['symbol']) ?></p>
                                </div>
                            </div>

                            <div class="flex items-center justify-between sm:justify-end sm:gap-10">
                                <div class="text-left sm:text-right">
                                    <p class="text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-0.5">Holding</p>
                                    <p class="text-sm font-black text-slate-900 dark:text-white"><?= $asset['amount'] ?></p>
                                </div>
                                
                                <div class="text-right">
                                    <h3 class="text-base font-black text-slate-900 dark:text-white">
                                        $<?= number_format($asset['value'], 2) ?>
                                    </h3>
                                    <p class="text-[10px] font-bold mt-0.5 <?= $asset['status'] == 'profit' ? 'text-emerald-500' : 'text-rose-500' ?>">
                                        <?= $asset['pnl'] ?>
                                    </p>
                                </div>
                            </div>

                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </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'; // Slate 400 vs Slate 500
        const themeHex = '<?= $dbTheme ?>';

        // Load dynamic chart data from PHP
        const dynamicLabels = <?= json_encode($chartLabels) ?>;
        const dynamicSeries = <?= json_encode($chartSeries) ?>;
        
        // Define a color palette. Theme color first, then complementary colors.
        const colorPalette = [themeHex, '#6366f1', '#f59e0b', '#10b981', '#f43f5e', '#8b5cf6', '#14b8a6', '#64748b'];

        // ApexCharts Donut Configuration
        var options = {
            series: dynamicSeries, 
            labels: dynamicLabels,
            chart: {
                type: 'donut',
                height: 320,
                fontFamily: 'inherit',
                background: 'transparent'
            },
            colors: colorPalette,
            stroke: {
                show: true,
                colors: isDark ? '#0f172a' : '#ffffff',
                width: 2
            },
            dataLabels: {
                enabled: false // Cleaner look without text on slices
            },
            plotOptions: {
                pie: {
                    donut: {
                        size: '75%',
                        labels: {
                            show: true,
                            name: {
                                show: true,
                                fontSize: '12px',
                                fontWeight: 800,
                                color: textColor,
                                offsetY: -10
                            },
                            value: {
                                show: true,
                                fontSize: '24px',
                                fontWeight: 900,
                                color: isDark ? '#ffffff' : '#0f172a',
                                offsetY: 10,
                                formatter: function (val, opts) {
                                    // Calculate and show percentage
                                    let percent = opts.globals.seriesPercent[opts.seriesIndex];
                                    return percent ? percent.toFixed(1) + "%" : "0%";
                                }
                            },
                            total: {
                                show: true,
                                showAlways: true,
                                label: 'Top Asset',
                                fontSize: '10px',
                                fontWeight: 800,
                                color: textColor,
                                formatter: function (w) {
                                    // Make center show the percentage of the largest holding
                                    let maxVal = Math.max(...w.globals.seriesPercent);
                                    return maxVal.toFixed(1) + "%";
                                }
                            }
                        }
                    }
                }
            },
            legend: {
                position: 'bottom',
                fontSize: '11px',
                fontWeight: 700,
                labels: {
                    colors: textColor
                },
                markers: {
                    width: 8,
                    height: 8,
                    radius: 12
                },
                itemMargin: {
                    horizontal: 10,
                    vertical: 5
                }
            },
            tooltip: {
                theme: isDark ? 'dark' : 'light',
                y: {
                    formatter: function(value) {
                        // Format tooltip value as currency
                        return "$" + value.toLocaleString(undefined, {minimumFractionDigits: 2});
                    }
                }
            }
        };

        var chart = new ApexCharts(document.querySelector("#allocationChart"), options);
        chart.render();
    });
</script>

</body>
</html>