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

$user_id = $_SESSION['user_id'];

// ── Auto-mature any investments whose maturity date has passed ─────────────────
// Handles status values: 'running', 'active', or '' (empty string legacy records)
$auto_mature_sql = "UPDATE investments
                    SET status = 'matured'
                    WHERE user_id = '$user_id'
                      AND maturity_date <= NOW()
                      AND (status = 'running' OR status = 'active' OR status = '')";
mysqli_query($conn, $auto_mature_sql);

// ── Fetch all investments for this user ───────────────────────────────────────
$investments_query  = "SELECT i.*, p.name AS plan_name, p.roi_percentage
                       FROM investments i
                       LEFT JOIN investment_plans p ON i.plan_id = p.id
                       WHERE i.user_id = '$user_id'
                       ORDER BY i.start_date DESC";
$investments_result = mysqli_query($conn, $investments_query);
$all_investments = [];
while ($row = mysqli_fetch_assoc($investments_result)) {
    $all_investments[] = $row;
}

// ── Counts per tab ────────────────────────────────────────────────────────────
$count_all = count($all_investments);

// Active = running/active/'' where maturity has NOT passed yet
$count_running = count(array_filter($all_investments, function($i) {
    return in_array($i['status'], ['active', 'running', '']) && $i['status'] !== 'matured';
}));

$count_matured = count(array_filter($all_investments, function($i) {
    return $i['status'] === 'matured';
}));

// Card colour themes
$card_themes = [
    ['bg' => 'linear-gradient(135deg, #0f2027, #203a43, #2c5364)', 'accent' => '#00d4ff',  'border' => '#2c5364',  'icon' => 'fa-gem'],
    ['bg' => 'linear-gradient(135deg, #1a0533, #2d0a5e, #4a0080)', 'accent' => '#b44dff',  'border' => '#7b2fff',  'icon' => 'fa-crown'],
    ['bg' => 'linear-gradient(135deg, #1a2f00, #2e5000, #3d6b00)', 'accent' => '#7fff00',  'border' => '#5cb800',  'icon' => 'fa-leaf'],
    ['bg' => 'linear-gradient(135deg, #2d0a00, #5c1a00, #8c2900)', 'accent' => '#ff8c00',  'border' => '#ff6600',  'icon' => 'fa-fire'],
    ['bg' => 'linear-gradient(135deg, #001a33, #003366, #004d99)', 'accent' => '#33bbff',  'border' => '#0099ff',  'icon' => 'fa-shield-alt'],
    ['bg' => 'linear-gradient(135deg, #1a001a, #33003d, #4d0066)', 'accent' => '#ff66dd',  'border' => '#ff33cc',  'icon' => 'fa-star'],
    ['bg' => 'linear-gradient(135deg, #1a1a00, #333300, #4d4d00)', 'accent' => '#FFD700',  'border' => '#cccc00',  'icon' => 'fa-trophy'],
    ['bg' => 'linear-gradient(135deg, #001a1a, #003333, #004d4d)', 'accent' => '#00ffff',  'border' => '#00cccc',  'icon' => 'fa-rocket'],
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Investments - 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: #000; color: #fff;
            font-family: Arial, sans-serif;
            padding-bottom: 80px;
            font-size: 13px;
        }

        /* ── Header ── */
        .header {
            background: linear-gradient(135deg, #111 0%, #1a1a1a 100%);
            padding: 16px 15px 12px;
            text-align: center;
            box-shadow: 0 3px 15px rgba(0,0,0,0.6);
            position: sticky; top: 0; z-index: 100;
        }
        .header h1 { color: #FFD700; font-size: 18px; letter-spacing: 0.5px; }
        .header-sub { font-size: 10px; color: #666; margin-top: 2px; }

        /* ── Summary Row ── */
        .summary-row {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 8px;
            padding: 12px 12px 0;
        }
        .summary-box {
            background: #111; border: 1px solid #222;
            border-radius: 10px; padding: 10px 8px;
            text-align: center;
        }
        .summary-box.active-box  { border-color: #00c853; }
        .summary-box.matured-box { border-color: #FFD700; }
        .summary-box.all-box     { border-color: #555; }
        .summary-number { font-size: 22px; font-weight: bold; }
        .summary-box.active-box  .summary-number { color: #00c853; }
        .summary-box.matured-box .summary-number { color: #FFD700; }
        .summary-box.all-box     .summary-number { color: #aaa; }
        .summary-label {
            font-size: 9px; color: #666;
            margin-top: 2px; text-transform: uppercase; letter-spacing: 0.5px;
        }

        /* ── Tabs ── */
        .tabs { display: flex; gap: 8px; padding: 12px; }
        .tab {
            flex: 1; padding: 10px 6px;
            background: #111; border: 1px solid #222;
            border-radius: 8px; text-align: center;
            cursor: pointer; font-weight: bold; font-size: 12px;
            transition: all 0.25s; color: #888;
        }
        .tab.active { background: #FFD700; color: #000; border-color: #FFD700; }
        .tab:hover:not(.active) { border-color: #FFD700; color: #FFD700; }

        /* ── Tab Content ── */
        .tab-content { display: none; padding: 0 12px; }
        .tab-content.active { display: block; }

        /* ── Investment Card ── */
        .investment-card {
            border-radius: 14px; padding: 14px;
            margin-bottom: 12px;
            position: relative; overflow: hidden;
            box-shadow: 0 6px 20px rgba(0,0,0,0.7);
            border: 1px solid #333;
        }
        .investment-card::before {
            content: '';
            position: absolute; top: -40px; right: -40px;
            width: 120px; height: 120px;
            border-radius: 50%;
            background: rgba(255,255,255,0.03);
            pointer-events: none;
        }
        .investment-card::after {
            content: '';
            position: absolute; bottom: -30px; left: -30px;
            width: 80px; height: 80px;
            border-radius: 50%;
            background: rgba(255,255,255,0.02);
            pointer-events: none;
        }

        /* Card top row */
        .card-top {
            display: flex;
            justify-content: space-between; align-items: flex-start;
            margin-bottom: 12px;
        }
        .card-plan-name {
            font-size: 13px; font-weight: bold;
            display: flex; align-items: center; gap: 6px;
        }
        .card-plan-name i { font-size: 12px; }

        /* Status badges */
        .status-badge {
            padding: 4px 10px; border-radius: 20px;
            font-size: 9px; font-weight: bold;
            letter-spacing: 0.5px; text-transform: uppercase;
            display: flex; align-items: center; gap: 4px;
        }
        .badge-active  { background: rgba(0,200,83,0.2);  color: #00c853; border: 1px solid #00c853; }
        .badge-matured { background: rgba(255,215,0,0.2); color: #FFD700; border: 1px solid #FFD700; }

        /* Amount */
        .card-amount {
            font-size: 26px; font-weight: bold;
            margin-bottom: 10px; letter-spacing: 0.5px;
        }

        /* Details grid */
        .card-details {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 6px; margin-bottom: 10px;
        }
        .detail-item {
            background: rgba(0,0,0,0.3);
            border-radius: 6px; padding: 7px 8px;
        }
        .detail-item-label {
            font-size: 8px; color: #888;
            text-transform: uppercase; letter-spacing: 0.5px;
            margin-bottom: 3px;
        }
        .detail-item-value { font-size: 11px; font-weight: bold; color: #fff; }
        .detail-item-value.green { color: #00c853; }
        .detail-item-value.gold  { color: #FFD700; }

        /* Progress bar */
        .progress-section { margin-top: 6px; }
        .progress-header {
            display: flex; justify-content: space-between;
            margin-bottom: 5px; font-size: 9px; color: #888;
        }
        .progress-bar {
            width: 100%; height: 6px;
            background: rgba(0,0,0,0.4);
            border-radius: 10px; overflow: hidden;
        }
        .progress-fill {
            height: 100%; border-radius: 10px;
            transition: width 0.5s ease;
        }

        /* Countdown */
        .countdown {
            text-align: center; margin-top: 8px;
            font-size: 10px; color: #aaa;
            background: rgba(0,0,0,0.3);
            border-radius: 6px; padding: 5px;
        }
        .countdown span { font-weight: bold; }

        /* Completed banner */
        .completed-banner {
            display: flex; align-items: center;
            justify-content: center; gap: 6px;
            background: rgba(255,215,0,0.1);
            border: 1px solid rgba(255,215,0,0.3);
            border-radius: 8px; padding: 8px;
            margin-top: 8px;
            font-size: 10px; color: #FFD700; font-weight: bold;
        }

        /* No investments */
        .no-investments {
            background: #111; border: 1px solid #222;
            border-radius: 14px; padding: 40px 20px;
            text-align: center; color: #555;
        }
        .no-investments i { font-size: 40px; display: block; margin-bottom: 12px; opacity: 0.3; }
        .no-investments h3 { color: #666; margin-bottom: 6px; }
        .no-investments p  { font-size: 12px; }
        .go-plans-btn {
            display: inline-block; margin-top: 14px;
            padding: 10px 20px;
            background: #FFD700; color: #000;
            border-radius: 8px; font-weight: bold;
            text-decoration: none; font-size: 12px;
        }
    </style>
</head>
<body>

    <!-- Header -->
    <div class="header">
        <h1><i class="fas fa-chart-line"></i> My Investments</h1>
        <div class="header-sub">Track your portfolio performance</div>
    </div>

    <!-- Summary Row -->
    <div class="summary-row">
        <div class="summary-box all-box">
            <div class="summary-number"><?php echo $count_all; ?></div>
            <div class="summary-label">Total</div>
        </div>
        <div class="summary-box active-box">
            <div class="summary-number"><?php echo $count_running; ?></div>
            <div class="summary-label">Active</div>
        </div>
        <div class="summary-box matured-box">
            <div class="summary-number"><?php echo $count_matured; ?></div>
            <div class="summary-label">Completed</div>
        </div>
    </div>

    <!-- Tabs -->
    <div class="tabs">
        <div class="tab active"  onclick="switchTab('all',     this)">All</div>
        <div class="tab"         onclick="switchTab('active',  this)">Active</div>
        <div class="tab"         onclick="switchTab('matured', this)">Completed</div>
    </div>

    <?php
    /**
     * Render a single investment card.
     *
     * @param array $investment  Row from investments + investment_plans JOIN
     * @param int   $themeIndex  Used to pick card colour theme
     * @param array $card_themes Array of theme arrays
     */
    function renderCard(array $investment, int $themeIndex, array $card_themes): void {
        $theme = $card_themes[$themeIndex % count($card_themes)];

        // Determine if this investment is still running
        $status   = $investment['status'];
        $isActive = in_array($status, ['active', 'running', '']) && $status !== 'matured';

        $start    = strtotime($investment['start_date'] ?? 'now');
        $maturity = strtotime($investment['maturity_date']);
        $now      = time();

        $total_duration = max(1, $maturity - $start);
        $elapsed        = $now - $start;
        $progress       = min(100, max(0, ($elapsed / $total_duration) * 100));

        $days_left = max(0, (int) ceil(($maturity - $now) / 86400));

        // total_return = profit only (fixed) OR principal + profit (flexible)
        $total_return = floatval($investment['total_return'] ?? ($investment['amount'] + $investment['profit']));
        ?>
        <div class="investment-card"
             style="background:<?php echo $theme['bg']; ?>; border-color:<?php echo $theme['border']; ?>;">

            <!-- Plan name + status -->
            <div class="card-top">
                <div class="card-plan-name" style="color:<?php echo $theme['accent']; ?>;">
                    <i class="fas <?php echo $theme['icon']; ?>"></i>
                    <?php echo htmlspecialchars($investment['plan_name'] ?? 'Investment Plan'); ?>
                </div>
                <?php if ($isActive): ?>
                    <span class="status-badge badge-active">
                        <i class="fas fa-circle" style="font-size:6px;"></i> Active
                    </span>
                <?php else: ?>
                    <span class="status-badge badge-matured">
                        <i class="fas fa-check-circle" style="font-size:9px;"></i> Completed
                    </span>
                <?php endif; ?>
            </div>

            <!-- Invested amount -->
            <div class="card-amount" style="color:<?php echo $theme['accent']; ?>;">
                ZMW <?php echo number_format(floatval($investment['amount']), 2); ?>
            </div>

            <!-- Detail Grid -->
            <div class="card-details">
                <div class="detail-item">
                    <div class="detail-item-label"><i class="fas fa-calendar-plus"></i> Start Date</div>
                    <div class="detail-item-value"><?php echo date('d M Y', $start); ?></div>
                </div>
                <div class="detail-item">
                    <div class="detail-item-label"><i class="fas fa-calendar-check"></i> Maturity Date</div>
                    <div class="detail-item-value"><?php echo date('d M Y', $maturity); ?></div>
                </div>
                <div class="detail-item">
                    <div class="detail-item-label"><i class="fas fa-percentage"></i> ROI</div>
                    <div class="detail-item-value" style="color:<?php echo $theme['accent']; ?>;">
                        <?php echo htmlspecialchars($investment['roi_percentage'] ?? '—'); ?>%
                    </div>
                </div>
                <div class="detail-item">
                    <div class="detail-item-label"><i class="fas fa-coins"></i> Profit</div>
                    <div class="detail-item-value green">
                        ZMW <?php echo number_format(floatval($investment['profit']), 2); ?>
                    </div>
                </div>
                <div class="detail-item" style="grid-column: 1 / -1;">
                    <div class="detail-item-label">
                        <i class="fas fa-wallet"></i>
                        Total Return
                        <?php
                        $rt = $investment['return_type'] ?? 'fixed';
                        echo '(' . ($rt === 'flexible' ? 'Capital + Profit' : 'Profit Only') . ')';
                        ?>
                    </div>
                    <div class="detail-item-value gold" style="font-size:13px;">
                        ZMW <?php echo number_format($total_return, 2); ?>
                    </div>
                </div>
            </div>

            <!-- Progress bar (active) or completion banner (matured) -->
            <?php if ($isActive): ?>
                <div class="progress-section">
                    <div class="progress-header">
                        <span><i class="fas fa-hourglass-half"></i> Progress</span>
                        <span><?php echo round($progress); ?>%</span>
                    </div>
                    <div class="progress-bar">
                        <div class="progress-fill"
                             style="width:<?php echo $progress; ?>%;
                                    background: linear-gradient(90deg,
                                        <?php echo $theme['border']; ?>,
                                        <?php echo $theme['accent']; ?>);">
                        </div>
                    </div>
                </div>
                <div class="countdown">
                    ⏳ <span><?php echo $days_left; ?> day<?php echo $days_left !== 1 ? 's' : ''; ?></span>
                    remaining until maturity
                </div>
            <?php else: ?>
                <div class="completed-banner">
                    <i class="fas fa-check-double"></i>
                    Investment Matured — Funds Added to Your Account Balance
                </div>
            <?php endif; ?>
        </div>
        <?php
    }
    ?>

    <!-- ALL tab -->
    <div id="all-content" class="tab-content active">
        <?php if ($count_all > 0):
            foreach ($all_investments as $i => $inv):
                renderCard($inv, $i, $card_themes);
            endforeach;
        else: ?>
            <div class="no-investments">
                <i class="fas fa-seedling"></i>
                <h3>No Investments Yet</h3>
                <p>Start investing today to grow your wealth.</p>
                <a href="plans.php" class="go-plans-btn"><i class="fas fa-rocket"></i> View Plans</a>
            </div>
        <?php endif; ?>
    </div>

    <!-- ACTIVE tab -->
    <div id="active-content" class="tab-content">
        <?php
        $active_list = array_values(array_filter($all_investments, function($i) {
            return in_array($i['status'], ['active', 'running', '']) && $i['status'] !== 'matured';
        }));
        if (count($active_list) > 0):
            foreach ($active_list as $i => $inv):
                renderCard($inv, $i, $card_themes);
            endforeach;
        else: ?>
            <div class="no-investments">
                <i class="fas fa-chart-line"></i>
                <h3>No Active Investments</h3>
                <p>Check out our investment plans to get started.</p>
                <a href="plans.php" class="go-plans-btn"><i class="fas fa-rocket"></i> View Plans</a>
            </div>
        <?php endif; ?>
    </div>

    <!-- COMPLETED tab -->
    <div id="matured-content" class="tab-content">
        <?php
        $matured_list = array_values(array_filter($all_investments, function($i) {
            return $i['status'] === 'matured';
        }));
        if (count($matured_list) > 0):
            foreach ($matured_list as $i => $inv):
                renderCard($inv, $i, $card_themes);
            endforeach;
        else: ?>
            <div class="no-investments">
                <i class="fas fa-trophy"></i>
                <h3>No Completed Investments</h3>
                <p>Your completed investments will appear here once they mature.</p>
            </div>
        <?php endif; ?>
    </div>

    <script>
        function switchTab(tab, el) {
            document.querySelectorAll('.tab').forEach(function(t) { t.classList.remove('active'); });
            document.querySelectorAll('.tab-content').forEach(function(c) { c.classList.remove('active'); });
            el.classList.add('active');
            document.getElementById(tab + '-content').classList.add('active');
        }

        // Auto-refresh every 60 s to keep progress bars and statuses current
        setTimeout(function() { location.reload(); }, 60000);

        var navHome = document.querySelector('.nav-item[href="home.php"]');
        if (navHome) navHome.classList.add('active');
    </script>

    <?php include 'bottom-nav.php'; ?>
</body>
</html>