<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}
require_once 'db.php';

$user_id = $_SESSION['user_id'];

// Fetch all active plans
$plans_query = "SELECT * FROM investment_plans WHERE status = 'active' ORDER BY min_amount ASC";
$plans_result = mysqli_query($conn, $plans_query);
$plans = [];
while ($row = mysqli_fetch_assoc($plans_result)) { $plans[] = $row; }

// User profits summary
$total_profits    = mysqli_fetch_assoc(mysqli_query($conn, "SELECT SUM(amount) as t FROM profits WHERE user_id='$user_id'"))['t'] ?? 0;
$referral_profits = mysqli_fetch_assoc(mysqli_query($conn, "SELECT SUM(amount) as t FROM profits WHERE user_id='$user_id' AND source LIKE '%Referral%'"))['t'] ?? 0;
$invest_profits   = mysqli_fetch_assoc(mysqli_query($conn, "SELECT SUM(amount) as t FROM profits WHERE user_id='$user_id' AND source NOT LIKE '%Referral%' AND source NOT LIKE '%Bonus%'"))['t'] ?? 0;

// User profits history
$profits = [];
$pr = mysqli_query($conn, "SELECT * FROM profits WHERE user_id='$user_id' ORDER BY created_at DESC");
while ($row = mysqli_fetch_assoc($pr)) { $profits[] = $row; }

// Plan color themes (mirrors plans.php)
$plan_themes = [
    ['accent' => '#00d4ff', 'icon' => 'fas fa-gem',       'bg' => 'rgba(0,212,255,0.07)'],
    ['accent' => '#b44dff', 'icon' => 'fas fa-crown',     'bg' => 'rgba(180,77,255,0.07)'],
    ['accent' => '#7fff00', 'icon' => 'fas fa-leaf',      'bg' => 'rgba(127,255,0,0.07)'],
    ['accent' => '#ff8c00', 'icon' => 'fas fa-fire',      'bg' => 'rgba(255,140,0,0.07)'],
    ['accent' => '#33bbff', 'icon' => 'fas fa-shield-alt','bg' => 'rgba(51,187,255,0.07)'],
    ['accent' => '#ff66dd', 'icon' => 'fas fa-star',      'bg' => 'rgba(255,102,221,0.07)'],
    ['accent' => '#FFD700', 'icon' => 'fas fa-trophy',    'bg' => 'rgba(255,215,0,0.07)'],
    ['accent' => '#00ffff', 'icon' => 'fas fa-rocket',    'bg' => 'rgba(0,255,255,0.07)'],
];

// Generate 5 representative capital points: min, 25%, 50%, 75%, max
function getCapitalPoints($min, $max) {
    $min = (int)$min;
    $max = (int)$max;
    if ($min === $max) return [$min];
    $range = $max - $min;
    $raw = [
        $min,
        $min + round($range * 0.25),
        $min + round($range * 0.50),
        $min + round($range * 0.75),
        $max,
    ];
    // Round middle points to nearest 100 (or 50 if small range)
    $unit = $range >= 400 ? 100 : 50;
    foreach ($raw as $i => $v) {
        if ($i === 0 || $i === count($raw)-1) continue; // keep min/max exact
        $raw[$i] = (int)(round($v / $unit) * $unit);
        $raw[$i] = max($min, min($max, $raw[$i]));
    }
    return array_values(array_unique($raw));
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Profits - MaxTrade</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<style>
* { margin:0; padding:0; box-sizing:border-box; }

body {
    background:#0a0a0a;
    color:#fff;
    font-family:Arial,sans-serif;
    padding-bottom:80px;
}

/* HEADER */
.header {
    background:#111;
    padding:10px 12px;
    display:flex;
    align-items:center;
    gap:8px;
    border-bottom:1px solid #1e1e1e;
}
.header img { height:28px; }
.header h1 { font-size:13px; font-weight:700; }

/* SUMMARY */
.summary-row {
    display:grid;
    grid-template-columns:repeat(3,1fr);
    gap:6px;
    padding:8px 8px 0;
}
.sum-card {
    background:#111;
    border-radius:9px;
    padding:8px 6px;
    text-align:center;
    border:1px solid #1e1e1e;
}
.sum-icon { font-size:12px; margin-bottom:3px; }
.sum-label { font-size:7px; color:#555; text-transform:uppercase; letter-spacing:0.8px; margin-bottom:2px; }
.sum-amount { font-size:10px; font-weight:800; }
.sum-cur { font-size:7px; opacity:0.6; }

/* SECTION TITLE */
.sec-title {
    font-size:8px;
    font-weight:700;
    color:#FFD700;
    letter-spacing:1.5px;
    text-transform:uppercase;
    padding:10px 8px 5px;
    display:flex;
    align-items:center;
    gap:4px;
}

/* PLAN BLOCK */
.plan-block {
    margin:0 8px 7px;
    border-radius:9px;
    overflow:hidden;
    border:1px solid #1e1e1e;
}

.plan-hdr {
    display:flex;
    align-items:center;
    justify-content:space-between;
    padding:6px 9px;
}
.plan-hdr-left { display:flex; align-items:center; gap:5px; }
.plan-hdr-name { font-size:10px; font-weight:700; line-height:1.3; }
.plan-hdr-sub  { font-size:7px; color:rgba(255,255,255,0.4); margin-top:1px; }
.roi-pill {
    font-size:10px;
    font-weight:900;
    padding:3px 8px;
    border-radius:6px;
    white-space:nowrap;
}
.ret-badge {
    font-size:6px;
    font-weight:700;
    padding:1px 4px;
    border-radius:3px;
    margin-left:4px;
    letter-spacing:0.4px;
    vertical-align:middle;
}
.ret-fixed    { background:#1e3a8a; color:#93c5fd; }
.ret-flexible { background:#064e3b; color:#6ee7b7; }

/* TABLE */
.plan-table { width:100%; border-collapse:collapse; }
.plan-table thead tr { background:#141414; }
.plan-table thead th {
    padding:4px 7px;
    font-size:7px;
    font-weight:700;
    color:#444;
    text-transform:uppercase;
    letter-spacing:0.7px;
}
.plan-table thead th:first-child { text-align:left; }
.plan-table thead th:not(:first-child) { text-align:right; }

.plan-table tbody tr { border-top:1px solid #161616; }
.plan-table tbody tr:nth-child(even) { background:rgba(255,255,255,0.015); }
.plan-table td {
    padding:4px 7px;
    font-size:9px;
    font-weight:600;
}
.plan-table td:first-child { text-align:left; color:#777; }
.plan-table td:not(:first-child) { text-align:right; }
.td-daily { color:#00e676; }

/* HISTORY */
.history-list { margin:0 8px; display:flex; flex-direction:column; gap:5px; }
.h-item {
    background:#111;
    border-radius:8px;
    padding:8px 11px;
    display:flex;
    align-items:center;
    justify-content:space-between;
    border:1px solid #1a1a1a;
}
.h-left  { display:flex; align-items:center; gap:7px; }
.h-icon  {
    width:26px; height:26px;
    border-radius:6px;
    display:flex; align-items:center; justify-content:center;
    font-size:11px; flex-shrink:0;
}
.ic-inv  { background:rgba(0,230,118,0.12); color:#00e676; }
.ic-ref  { background:rgba(255,215,0,0.12);  color:#FFD700; }
.ic-bon  { background:rgba(180,77,255,0.12); color:#b44dff; }
.h-src   { font-size:10px; font-weight:600; }
.h-date  { font-size:8px; color:#444; margin-top:1px; }
.h-amt   { font-size:11px; font-weight:800; color:#00e676; }
.h-amt span { font-size:7px; opacity:0.6; }

.empty-state { text-align:center; padding:22px; color:#333; font-size:10px; }
.empty-state i { font-size:24px; display:block; margin-bottom:5px; }

.footnote { font-size:7px; color:#2a2a2a; text-align:center; padding:5px 8px 0; }
</style>
</head>
<body>

<!-- HEADER -->
<div class="header">
    <img src="https://pvp360.us/zambia/logoo.png" alt="PVP360">
    <h1><i class="fas fa-chart-bar" style="color:#FFD700;margin-right:4px;"></i>Profits</h1>
</div>

<!-- SUMMARY -->
<div class="summary-row">
    <div class="sum-card">
        <div class="sum-icon" style="color:#00e676;"><i class="fas fa-coins"></i></div>
        <div class="sum-label">Total</div>
        <div class="sum-amount"><span class="sum-cur">ZMW </span><?php echo number_format($total_profits,2); ?></div>
    </div>
    <div class="sum-card">
        <div class="sum-icon" style="color:#FFD700;"><i class="fas fa-seedling"></i></div>
        <div class="sum-label">Investment</div>
        <div class="sum-amount"><span class="sum-cur">ZMW </span><?php echo number_format($invest_profits,2); ?></div>
    </div>
    <div class="sum-card">
        <div class="sum-icon" style="color:#b44dff;"><i class="fas fa-users"></i></div>
        <div class="sum-label">Referrals</div>
        <div class="sum-amount"><span class="sum-cur">ZMW </span><?php echo number_format($referral_profits,2); ?></div>
    </div>
</div>

<!-- BREAKDOWN -->
<div class="sec-title"><i class="fas fa-table"></i> Investment Breakdown</div>

<?php foreach ($plans as $idx => $plan):
    $t      = $plan_themes[$idx % count($plan_themes)];
    $pts    = getCapitalPoints($plan['min_amount'], $plan['max_amount']);
    $days   = (int)$plan['duration_days'];
    $roi    = (float)$plan['roi_percentage'];
?>
<div class="plan-block">

    <!-- Plan header -->
    <div class="plan-hdr" style="background:<?php echo $t['bg']; ?>;border-bottom:1px solid <?php echo $t['accent']; ?>22;">
        <div class="plan-hdr-left">
            <i class="<?php echo $t['icon']; ?>" style="color:<?php echo $t['accent']; ?>;font-size:11px;"></i>
            <div>
                <div class="plan-hdr-name" style="color:<?php echo $t['accent']; ?>;">
                    <?php echo htmlspecialchars($plan['name']); ?>
                    <span class="ret-badge ret-<?php echo $plan['return_type']; ?>">
                        <?php echo $plan['return_type']==='fixed' ? 'PROFIT ONLY' : 'PROFIT+CAPITAL'; ?>
                    </span>
                </div>
                <div class="plan-hdr-sub">ZMW <?php echo number_format($plan['min_amount']); ?> – <?php echo number_format($plan['max_amount']); ?> &bull; <?php echo $days; ?> days</div>
            </div>
        </div>
        <div class="roi-pill" style="background:<?php echo $t['accent']; ?>18;color:<?php echo $t['accent']; ?>;border:1px solid <?php echo $t['accent']; ?>33;">
            <?php echo $roi; ?>% ROI
        </div>
    </div>

    <!-- Data rows -->
    <table class="plan-table">
        <thead>
            <tr>
                <th>Capital</th>
                <th>Daily Return</th>
                <th style="color:<?php echo $t['accent']; ?>;">At Maturity</th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($pts as $cap):
            // Daily return = capital * roi% per day
            $daily     = ($cap * $roi) / 100;             // e.g. 100 * 15% = 15/day
            $total_out = $daily * $days;                  // e.g. 15 * 90 = 1350
        ?>
            <tr>
                <td><?php echo number_format($cap); ?></td>
                <td class="td-daily"><?php echo number_format($daily, 0); ?></td>
                <td style="color:<?php echo $t['accent']; ?>;font-weight:800;"><?php echo number_format($total_out, 0); ?></td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>

</div>
<?php endforeach; ?>

<div class="footnote">* Rounded to whole numbers. Table auto-updates when plans change.</div>

<!-- HISTORY -->
<div class="sec-title"><i class="fas fa-history"></i> Earnings History</div>

<div class="history-list">
<?php if (empty($profits)): ?>
    <div class="empty-state">
        <i class="fas fa-chart-line"></i>
        No earnings yet. Start investing!
    </div>
<?php else: ?>
    <?php foreach ($profits as $p):
        $src = strtolower($p['source'] ?? '');
        if (strpos($src,'referral')!==false) { $ic='ic-ref'; $ii='fas fa-users'; }
        elseif (strpos($src,'bonus')!==false) { $ic='ic-bon'; $ii='fas fa-gift'; }
        else { $ic='ic-inv'; $ii='fas fa-chart-line'; }
    ?>
    <div class="h-item">
        <div class="h-left">
            <div class="h-icon <?php echo $ic; ?>"><i class="<?php echo $ii; ?>"></i></div>
            <div>
                <div class="h-src"><?php echo htmlspecialchars($p['source'] ?? 'Profit'); ?></div>
                <div class="h-date"><?php echo date('d M Y, H:i', strtotime($p['created_at'])); ?></div>
            </div>
        </div>
        <div class="h-amt"><span>ZMW </span><?php echo number_format($p['amount'],2); ?></div>
    </div>
    <?php endforeach; ?>
<?php endif; ?>
</div>

<script>
    document.querySelector('.nav-item[href="profits.php"]')?.classList.add('active');
</script>
<?php include 'bottom-nav.php'; ?>
</body>
</html>