<?php
session_start();
require_once '../includes/db.php';
require_once '../includes/functions.php';
require_once '../includes/session_manager.php';

redirectIfNotLoggedIn();

$userId = $_SESSION['user_id'];
$error = '';
$success = '';

// Fetch available investment plans
$stmt = $pdo->query("SELECT * FROM investment_plans ORDER BY duration_months ASC");
$plans = $stmt->fetchAll();

// Fetch user's account balance
$stmt = $pdo->prepare("SELECT account_id, balance FROM accounts WHERE user_id = ?");
$stmt->execute([$userId]);
$account = $stmt->fetch();
if (!$account) {
    die("Account not found.");
}
$balance = $account['balance'];

// Handle new investment form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['plan_id'], $_POST['amount'])) {
    $planId = $_POST['plan_id'];
    $amount = (float) $_POST['amount'];

    $stmt = $pdo->prepare("SELECT * FROM investment_plans WHERE plan_id = ?");
    $stmt->execute([$planId]);
    $plan = $stmt->fetch();

    if (!$plan) {
        $error = "Invalid investment plan.";
    } elseif ($amount < $plan['min_amount']) {
        $error = "Amount must be at least $" . number_format($plan['min_amount'], 2);
    } elseif ($amount > $plan['max_amount']) {
        $error = "Amount cannot exceed $" . number_format($plan['max_amount'], 2);
    } elseif ($amount > $balance) {
        $error = "Insufficient balance.";
    } else {
        try {
            $pdo->beginTransaction();

            $stmt = $pdo->prepare("UPDATE accounts SET balance = balance - ? WHERE user_id = ?");
            $stmt->execute([$amount, $userId]);

            $stmt = $pdo->prepare("INSERT INTO investments (user_id, plan_id, amount, created_at, status) VALUES (?, ?, ?, NOW(), 'active')");
            $stmt->execute([$userId, $planId, $amount]);

            // Insert transaction record for investment
            $stmt = $pdo->prepare("SELECT account_id FROM accounts WHERE user_id = ?");
            $stmt->execute([$userId]);
            $account = $stmt->fetch();
            $accountId = $account['account_id'];

            $stmt = $pdo->prepare('INSERT INTO transactions (account_id, type, amount, description, created_at) VALUES (?, \'investment\', ?, ?, NOW())');
            $stmt->execute([$accountId, -$amount, 'Investment in ' . $plan['plan_name']]);

            $pdo->commit();
            $_SESSION['success'] = "Investment of $" . number_format($amount, 2) . " placed in " . htmlspecialchars($plan['plan_name']) . "!";
            header("Location: investment.php");
            exit();
        } catch (Exception $e) {
            $pdo->rollBack();
            $error = "Error placing investment: " . $e->getMessage();
        }
    }
}

// Handle withdrawal of matured investment
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['withdraw_investment_id'])) {
    $investmentId = $_POST['withdraw_investment_id'];

    // Fetch the investment to withdraw
    $stmt = $pdo->prepare("
        SELECT inv.*, plans.interest_rate 
        FROM investments inv
        JOIN investment_plans plans ON inv.plan_id = plans.plan_id
        WHERE inv.investment_id = ? 
        AND inv.user_id = ? 
        AND inv.status = 'matured'
        AND inv.withdrawn_at IS NULL
    ");
    $stmt->execute([$investmentId, $userId]);
    $investment = $stmt->fetch();

    if ($investment) {
        try {
            $pdo->beginTransaction();

            $totalReturn = $investment['amount'] + ($investment['amount'] * $investment['interest_rate'] / 100);

            $stmt = $pdo->prepare("UPDATE accounts SET balance = balance + ? WHERE user_id = ?");
            $stmt->execute([$totalReturn, $userId]);

            $stmt = $pdo->prepare("UPDATE investments SET withdrawn_at = NOW(), status = 'withdrawn' WHERE investment_id = ?");
            $stmt->execute([$investmentId]);

            // Insert transaction record for withdrawal of matured investment
            $stmt = $pdo->prepare("SELECT account_id FROM accounts WHERE user_id = ?");
            $stmt->execute([$userId]);
            $account = $stmt->fetch();
            $accountId = $account['account_id'];

            $stmt = $pdo->prepare('INSERT INTO transactions (account_id, type, amount, description, created_at) VALUES (?, \'withdrawal_matured_investment\', ?, ?, NOW())');
            $stmt->execute([$accountId, $totalReturn, 'Withdrawal of matured investment: $' . number_format($totalReturn, 2)]);

            $pdo->commit();
            $_SESSION['success'] = "Successfully withdrawn $" . number_format($totalReturn, 2) . " from matured investment.";
            header("Location: investment.php");
            exit();
        } catch (Exception $e) {
            $pdo->rollBack();
            $error = "Withdrawal failed: " . $e->getMessage();
        }
    } else {
        $error = "Invalid or already withdrawn investment.";
    }
}

/**
 * Update matured investments (once matured, mark them as such)
 */
function updateMaturedInvestments($pdo)
{
    $stmt = $pdo->prepare("
        UPDATE investments inv
        JOIN investment_plans plans ON inv.plan_id = plans.plan_id
        SET inv.status = 'matured', inv.matured_at = NOW()
        WHERE inv.status = 'active' 
        AND DATE_ADD(inv.created_at, INTERVAL plans.duration_months MONTH) <= NOW()
        AND (inv.matured_at IS NULL OR inv.matured_at = '0000-00-00 00:00:00')
    ");
    $stmt->execute();
}

// Call the function to update matured investments
updateMaturedInvestments($pdo);

// Fetch user's investment history
$stmt = $pdo->prepare("
    SELECT inv.*, plans.plan_name, plans.interest_rate, plans.duration_months 
    FROM investments inv
    JOIN investment_plans plans ON inv.plan_id = plans.plan_id
    WHERE inv.user_id = ?
    ORDER BY inv.created_at DESC
");
$stmt->execute([$userId]);
$investments = $stmt->fetchAll();

// Get user account information
$userId = $_SESSION['user_id'];
$stmt = $pdo->prepare("
    SELECT u.*, a.account_number, a.balance 
    FROM users u 
    JOIN accounts a ON u.user_id = a.user_id 
    WHERE u.user_id = ?
");
$stmt->execute([$userId]);
$user = $stmt->fetch();

if (!$user) {
    die('User account not found.');
}

// Check if the user has a profile picture
$stmt = $pdo->prepare("SELECT profile_picture FROM users WHERE user_id = ?");
$profilePic = $user['profile_picture'] ? '../uploads/' . $user['profile_picture'] : '../assets/images/default-avatars.png';

// Calculate investment statistics
$totalInvested = 0;
$totalReturns = 0;
$activeInvestments = 0;
$maturedInvestments = 0;

foreach ($investments as $inv) {
    if ($inv['status'] === 'active') {
        $activeInvestments++;
        $totalInvested += $inv['amount'];
    } elseif ($inv['status'] === 'matured') {
        $maturedInvestments++;
        $totalInvested += $inv['amount'];
        $totalReturns += $inv['amount'] + ($inv['amount'] * $inv['interest_rate'] / 100);
    }
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <title>Oakshire Finance - Investments</title>
    <link
        href="https://fonts.googleapis.com/css2?family=Inter:opsz,wght@14..32,300;14..32,400;14..32,500;14..32,600;14..32,700;14..32,800&display=swap"
        rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        :root {
            --primary-navy: #0a2540;
            --primary-dark: #0a1c2f;
            --primary-blue: #1a4d8c;
            --accent-blue: #2c7da0;
            --success-green: #2e7d32;
            --warning-orange: #f39c12;
            --error-red: #dc3545;
            --info-blue: #17a2b8;
            --gray-50: #f8f9fc;
            --gray-100: #f1f3f9;
            --gray-200: #e9ecef;
            --gray-300: #dee2e6;
            --gray-400: #ced4da;
            --gray-500: #adb5bd;
            --gray-600: #6c757d;
            --gray-700: #495057;
            --gray-800: #343a40;
            --gray-900: #212529;
            --white: #ffffff;
            --shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.08);
            --shadow-md: 0 4px 12px rgba(0, 0, 0, 0.05);
            --shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.08);
            --shadow-hover: 0 12px 28px rgba(0, 0, 0, 0.12);
            --transition: all 0.3s ease;
        }

        body {
            font-family: 'Inter', system-ui, -apple-system, sans-serif;
            background: var(--gray-50);
            color: var(--gray-800);
            line-height: 1.5;
            overflow-x: hidden;
        }

        /* Layout */
        .dashboard-wrapper {
            display: flex;
            min-height: 100vh;
        }

        /* Sidebar */
        .sidebar {
            width: 280px;
            background: var(--white);
            border-right: 1px solid var(--gray-200);
            position: fixed;
            left: 0;
            top: 0;
            bottom: 0;
            overflow-y: auto;
            transition: transform 0.3s ease;
            z-index: 100;
        }

        .sidebar-header {
            padding: 24px;
            border-bottom: 1px solid var(--gray-200);
            text-align: center;
        }

        .logo {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            text-decoration: none;
        }

        .logo-icon {
            width: 40px;
            height: 40px;
            background: var(--primary-navy);
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .logo-icon i {
            font-size: 20px;
            color: white;
        }

        .logo-text {
            font-size: 22px;
            font-weight: 700;
            color: var(--primary-navy);
            letter-spacing: -0.3px;
        }

        .profile-section {
            padding: 24px;
            text-align: center;
            border-bottom: 1px solid var(--gray-200);
        }

        .profile-avatar {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            margin: 0 auto 12px;
            background: linear-gradient(135deg, var(--primary-navy), var(--primary-blue));
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
        }

        .profile-avatar img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .profile-avatar i {
            font-size: 40px;
            color: white;
        }

        .profile-section h5 {
            font-size: 16px;
            font-weight: 600;
            color: var(--gray-900);
            margin-bottom: 4px;
        }

        .profile-section p {
            font-size: 12px;
            color: var(--gray-500);
        }

        .nav-menu {
            padding: 16px;
        }

        .nav-item {
            margin-bottom: 4px;
        }

        .nav-link {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 16px;
            border-radius: 12px;
            text-decoration: none;
            color: var(--gray-700);
            transition: var(--transition);
            font-weight: 500;
            font-size: 14px;
        }

        .nav-link i {
            width: 20px;
            font-size: 18px;
        }

        .nav-link:hover {
            background: var(--gray-100);
            color: var(--primary-blue);
        }

        .nav-link.active {
            background: var(--primary-navy);
            color: white;
        }

        .nav-link.active i {
            color: white;
        }

        .logout-section {
            padding: 16px;
            border-top: 1px solid var(--gray-200);
            margin-top: auto;
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            background: var(--white);
        }

        .logout-btn {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 16px;
            border-radius: 12px;
            text-decoration: none;
            color: var(--error-red);
            transition: var(--transition);
            font-weight: 500;
        }

        .logout-btn:hover {
            background: rgba(220, 53, 69, 0.1);
        }

        /* Main Content */
        .main-content {
            flex: 1;
            margin-left: 280px;
            min-height: 100vh;
        }

        /* Top Header */
        .top-header {
            background: var(--white);
            border-bottom: 1px solid var(--gray-200);
            padding: 16px 32px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: sticky;
            top: 0;
            z-index: 99;
        }

        .page-title h1 {
            font-size: 24px;
            font-weight: 700;
            color: var(--gray-900);
        }

        .user-menu {
            display: flex;
            align-items: center;
            gap: 24px;
        }

        .notification-btn {
            position: relative;
            background: none;
            border: none;
            font-size: 20px;
            color: var(--gray-600);
            cursor: pointer;
            transition: var(--transition);
        }

        .notification-btn:hover {
            color: var(--primary-blue);
        }

        /* Content Area */
        .content-area {
            padding: 32px;
        }

        /* Balance Card */
        .balance-card {
            background: linear-gradient(135deg, var(--primary-navy), var(--primary-dark));
            border-radius: 20px;
            padding: 24px;
            margin-bottom: 32px;
            color: white;
        }

        .balance-card h3 {
            font-size: 14px;
            font-weight: 500;
            opacity: 0.8;
            margin-bottom: 8px;
        }

        .balance-amount {
            font-size: 36px;
            font-weight: 700;
        }

        /* Stats Cards */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 24px;
            margin-bottom: 32px;
        }

        .stat-card {
            background: var(--white);
            border-radius: 20px;
            padding: 20px;
            border: 1px solid var(--gray-200);
            transition: var(--transition);
        }

        .stat-card:hover {
            transform: translateY(-2px);
            box-shadow: var(--shadow-hover);
        }

        .stat-icon {
            width: 48px;
            height: 48px;
            background: rgba(26, 77, 140, 0.1);
            border-radius: 14px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 16px;
        }

        .stat-icon i {
            font-size: 24px;
            color: var(--primary-blue);
        }

        .stat-card h3 {
            font-size: 13px;
            font-weight: 500;
            color: var(--gray-600);
            margin-bottom: 8px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .stat-value {
            font-size: 28px;
            font-weight: 700;
            color: var(--gray-900);
        }

        /* Investment Form Card */
        .investment-card {
            background: var(--white);
            border-radius: 24px;
            border: 1px solid var(--gray-200);
            padding: 32px;
            margin-bottom: 32px;
        }

        .investment-card h2 {
            font-size: 20px;
            font-weight: 600;
            margin-bottom: 24px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            font-size: 14px;
            font-weight: 500;
            color: var(--gray-700);
            margin-bottom: 8px;
        }

        .form-group select,
        .form-group input {
            width: 100%;
            padding: 12px 16px;
            font-size: 14px;
            font-family: 'Inter', sans-serif;
            border: 1.5px solid var(--gray-200);
            border-radius: 12px;
            transition: var(--transition);
            outline: none;
        }

        .form-group select:focus,
        .form-group input:focus {
            border-color: var(--primary-blue);
            box-shadow: 0 0 0 3px rgba(26, 77, 140, 0.1);
        }

        .btn-primary {
            width: 100%;
            padding: 12px;
            background: var(--primary-navy);
            color: white;
            border: none;
            border-radius: 12px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: var(--transition);
        }

        .btn-primary:hover {
            background: var(--primary-dark);
            transform: translateY(-2px);
        }

        .btn-secondary {
            padding: 6px 12px;
            background: rgba(26, 77, 140, 0.1);
            color: var(--primary-blue);
            border: none;
            border-radius: 8px;
            font-size: 12px;
            font-weight: 500;
            cursor: pointer;
            transition: var(--transition);
        }

        .btn-secondary:hover {
            background: var(--primary-blue);
            color: white;
        }

        /* Table */
        .table-container {
            background: var(--white);
            border-radius: 20px;
            border: 1px solid var(--gray-200);
            overflow-x: auto;
        }

        .data-table {
            width: 100%;
            border-collapse: collapse;
            min-width: 600px;
        }

        .data-table th,
        .data-table td {
            padding: 16px 20px;
            text-align: left;
            border-bottom: 1px solid var(--gray-200);
        }

        .data-table th {
            background: var(--gray-50);
            font-weight: 600;
            font-size: 12px;
            color: var(--gray-700);
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .data-table td {
            font-size: 13px;
        }

        /* Badges */
        .badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 500;
        }

        .badge-active {
            background: rgba(46, 125, 50, 0.1);
            color: var(--success-green);
        }

        .badge-matured {
            background: rgba(23, 162, 184, 0.1);
            color: var(--info-blue);
        }

        .badge-withdrawn {
            background: rgba(108, 117, 125, 0.1);
            color: var(--gray-600);
        }

        /* Alerts */
        .alert {
            padding: 14px 16px;
            border-radius: 12px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 12px;
            font-size: 14px;
        }

        .alert-danger {
            background: rgba(220, 53, 69, 0.1);
            border-left: 3px solid var(--error-red);
            color: var(--error-red);
        }

        .alert-success {
            background: rgba(46, 125, 50, 0.1);
            border-left: 3px solid var(--success-green);
            color: var(--success-green);
        }

        /* Hamburger Menu */
        .hamburger {
            display: none;
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
            color: var(--gray-700);
        }

        /* Mobile Responsive */
        @media (max-width: 1024px) {
            .sidebar {
                transform: translateX(-100%);
                z-index: 1000;
            }

            .sidebar.mobile-open {
                transform: translateX(0);
            }

            .main-content {
                margin-left: 0;
            }

            .hamburger {
                display: block;
            }
        }

        @media (max-width: 768px) {
            .content-area {
                padding: 20px;
            }

            .top-header {
                padding: 12px 20px;
            }

            .page-title h1 {
                font-size: 20px;
            }

            .balance-amount {
                font-size: 28px;
            }

            .stats-grid {
                grid-template-columns: 1fr;
                gap: 16px;
            }

            .investment-card {
                padding: 20px;
            }

            .data-table th,
            .data-table td {
                padding: 12px 16px;
            }
        }

        @media (max-width: 480px) {
            .balance-amount {
                font-size: 24px;
            }

            .stat-value {
                font-size: 24px;
            }
        }
    </style>
    <link rel="stylesheet" href="../assets/css/nexus-theme.css">
</head>

<body>
    <div class="dashboard-wrapper">
        <!-- Sidebar Navigation -->
        <aside class="sidebar" id="sidebar">
            <div class="sidebar-header">
                <a href="dashboard.php" class="logo">
                    <div class="logo-icon">
                        <i class="fas fa-building-columns"></i>
                    </div>
                    <span class="logo-text">Oakshire Finance</span>
                </a>
            </div>

            <div class="profile-section">
                <div class="profile-avatar">
                    <?php if ($user['profile_picture']): ?>
                        <img src="<?= $profilePic ?>" alt="Profile Picture">
                    <?php else: ?>
                        <i class="fas fa-user-circle"></i>
                    <?php endif; ?>
                </div>
                <h5><?= htmlspecialchars($user['full_name']) ?></h5>
                <p><?= htmlspecialchars($user['account_number']) ?></p>
            </div>

            <nav class="nav-menu">
                <div class="nav-item">
                    <a href="dashboard.php" class="nav-link">
                        <i class="fas fa-chart-line"></i>
                        <span>Dashboard</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="deposit.php" class="nav-link">
                        <i class="fas fa-arrow-down"></i>
                        <span>Deposit</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="withdraw.php" class="nav-link">
                        <i class="fas fa-arrow-up"></i>
                        <span>Withdraw</span>
                    </a>
                </div>

                <div class="nav-item"><a href="cards.php" class="nav-link "><i class="fas fa-credit-card"></i> My
                        Cards</a></div>
                <div class="nav-item">
                    <a href="transactions.php" class="nav-link">
                        <i class="fas fa-receipt"></i>
                        <span>Transactions</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="investment.php" class="nav-link active">
                        <i class="fas fa-chart-pie"></i>
                        <span>Investment</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="loan.php" class="nav-link">
                        <i class="fas fa-hand-holding-usd"></i>
                        <span>Loans</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="profile.php" class="nav-link">
                        <i class="fas fa-user-circle"></i>
                        <span>Settings</span>
                    </a>
                </div>
            </nav>

            <div class="logout-section">
                <a href="../logout.php" class="logout-btn">
                    <i class="fas fa-sign-out-alt"></i>
                    <span>Logout</span>
                </a>
            </div>
        </aside>

        <!-- Main Content -->
        <main class="main-content">
            <!-- Top Header -->
            <header class="top-header">
                <button class="hamburger" id="hamburger">
                    <i class="fas fa-bars"></i>
                </button>
                <div class="page-title">
                    <h1>Investments</h1>
                </div>
                <div class="user-menu">
                    <button class="notification-btn">
                        <i class="fas fa-bell"></i>
                    </button>
                </div>
            </header>

            <!-- Content Area -->
            <div class="content-area">
                <!-- Balance Card -->
                <div class="balance-card">
                    <h3>Available Balance</h3>
                    <div class="balance-amount">$<?= number_format($balance, 2) ?></div>
                </div>

                <!-- Stats Cards -->
                <div class="stats-grid">
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-chart-line"></i>
                        </div>
                        <h3>Total Invested</h3>
                        <div class="stat-value">$<?= number_format($totalInvested, 2) ?></div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-play-circle"></i>
                        </div>
                        <h3>Active Investments</h3>
                        <div class="stat-value"><?= number_format($activeInvestments) ?></div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-check-circle"></i>
                        </div>
                        <h3>Matured Investments</h3>
                        <div class="stat-value"><?= number_format($maturedInvestments) ?></div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-chart-simple"></i>
                        </div>
                        <h3>Expected Returns</h3>
                        <div class="stat-value">$<?= number_format($totalReturns, 2) ?></div>
                    </div>
                </div>

                <!-- Investment Form -->
                <div class="investment-card">
                    <h2><i class="fas fa-plus-circle"></i> Make a New Investment</h2>

                    <?php if ($error): ?>
                        <div class="alert alert-danger">
                            <i class="fas fa-exclamation-circle"></i>
                            <span><?= htmlspecialchars($error) ?></span>
                        </div>
                    <?php endif; ?>

                    <?php if (isset($_SESSION['success'])): ?>
                        <div class="alert alert-success">
                            <i class="fas fa-check-circle"></i>
                            <span><?= $_SESSION['success'] ?></span>
                        </div>
                        <?php unset($_SESSION['success']); ?>
                    <?php endif; ?>

                    <form method="post">
                        <div class="form-group">
                            <label for="plan_id">Select Investment Plan</label>
                            <select name="plan_id" id="plan_id" required>
                                <option value="">-- Choose a Plan --</option>
                                <?php foreach ($plans as $plan): ?>
                                    <option value="<?= $plan['plan_id'] ?>" data-min="<?= $plan['min_amount'] ?>"
                                        data-max="<?= $plan['max_amount'] ?>">
                                        <?= htmlspecialchars($plan['plan_name']) ?> - <?= $plan['interest_rate'] ?>% for
                                        <?= $plan['duration_months'] ?> months
                                        ($<?= number_format($plan['min_amount'], 2) ?> -
                                        $<?= number_format($plan['max_amount'], 2) ?>)
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="form-group">
                            <label for="amount">Investment Amount ($)</label>
                            <input type="number" name="amount" id="amount" step="0.01" min="0"
                                placeholder="Enter amount" required>
                        </div>

                        <button type="submit" class="btn-primary">
                            <i class="fas fa-chart-line"></i> Invest Now
                        </button>
                    </form>
                </div>

                <!-- Investment History -->
                <div class="investment-card" style="padding: 0; overflow: hidden;">
                    <div style="padding: 20px 24px; border-bottom: 1px solid var(--gray-200);">
                        <h2><i class="fas fa-history"></i> Your Investment History</h2>
                    </div>
                    <div class="table-container" style="margin: 0; border-radius: 0;">
                        <?php if (empty($investments)): ?>
                            <div style="text-align: center; padding: 48px; color: var(--gray-500);">
                                <i class="fas fa-chart-line"
                                    style="font-size: 48px; margin-bottom: 16px; opacity: 0.5;"></i>
                                <p>No investments yet. Start your investment journey today!</p>
                            </div>
                        <?php else: ?>
                            <table class="data-table">
                                <thead>
                                    <tr>
                                        <th>Plan</th>
                                        <th>Amount</th>
                                        <th>Interest</th>
                                        <th>Duration</th>
                                        <th>Start Date</th>
                                        <th>Maturity Date</th>
                                        <th>Status</th>
                                </thead>
                                <tbody>
                                    <?php foreach ($investments as $inv):
                                        $expectedReturn = $inv['amount'] + ($inv['amount'] * $inv['interest_rate'] / 100);
                                        $statusClass = '';
                                        if ($inv['status'] === 'active')
                                            $statusClass = 'badge-active';
                                        elseif ($inv['status'] === 'matured')
                                            $statusClass = 'badge-matured';
                                        else
                                            $statusClass = 'badge-withdrawn';
                                        ?>
                                        <tr>
                                            <td><strong><?= htmlspecialchars($inv['plan_name']) ?></strong></td>
                                            <td>$<?= number_format($inv['amount'], 2) ?></td>
                                            <td><?= $inv['interest_rate'] ?>%</td>
                                            <td><?= $inv['duration_months'] ?> months</td>
                                            <td><?= date('M d, Y', strtotime($inv['created_at'])) ?></td>
                                            <td>
                                                <?php if ($inv['matured_at'] && $inv['matured_at'] != '0000-00-00 00:00:00'): ?>
                                                    <?= date('M d, Y', strtotime($inv['matured_at'])) ?>
                                                <?php else: ?>
                                                    <span style="color: var(--gray-500);">—</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <?php if ($inv['status'] === 'matured' && empty($inv['withdrawn_at'])): ?>
                                                    <span class="badge <?= $statusClass ?>">Matured</span>
                                                    <form method="post" style="margin-top: 8px;">
                                                        <input type="hidden" name="withdraw_investment_id"
                                                            value="<?= $inv['investment_id'] ?>">
                                                        <button type="submit" class="btn-secondary">
                                                            <i class="fas fa-arrow-up"></i> Withdraw
                                                        </button>
                                                    </form>
                                                <?php elseif ($inv['status'] === 'withdrawn'): ?>
                                                    <span class="badge <?= $statusClass ?>">Withdrawn</span>
                                                    <?php if (!empty($inv['withdrawn_at'])): ?>
                                                        <br><small
                                                            style="color: var(--gray-500);"><?= date('M d, Y', strtotime($inv['withdrawn_at'])) ?></small>
                                                    <?php endif; ?>
                                                <?php else: ?>
                                                    <span class="badge <?= $statusClass ?>">
                                                        <i class="fas fa-chart-line"></i> Active
                                                    </span>
                                                    <br>
                                                    <small style="color: var(--success-green);">
                                                        Expected: $<?= number_format($expectedReturn, 2) ?>
                                                    </small>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <script>
        // Mobile sidebar toggle
        const hamburger = document.getElementById('hamburger');
        const sidebar = document.getElementById('sidebar');

        if (hamburger) {
            hamburger.addEventListener('click', function () {
                sidebar.classList.toggle('mobile-open');
            });
        }

        // Close sidebar when clicking outside on mobile
        document.addEventListener('click', function (event) {
            if (window.innerWidth <= 1024) {
                const isClickInside = sidebar.contains(event.target) || hamburger.contains(event.target);
                if (!isClickInside && sidebar.classList.contains('mobile-open')) {
                    sidebar.classList.remove('mobile-open');
                }
            }
        });

        // Auto-dismiss alerts after 5 seconds
        const alerts = document.querySelectorAll('.alert');
        alerts.forEach(alert => {
            setTimeout(() => {
                alert.style.transition = 'opacity 0.3s ease';
                alert.style.opacity = '0';
                setTimeout(() => alert.remove(), 300);
            }, 5000);
        });

        // Dynamic amount limits based on selected plan
        const planSelect = document.getElementById('plan_id');
        const amountInput = document.getElementById('amount');

        if (planSelect && amountInput) {
            planSelect.addEventListener('change', function () {
                const selectedOption = this.options[this.selectedIndex];
                const minAmount = selectedOption.getAttribute('data-min');
                const maxAmount = selectedOption.getAttribute('data-max');

                if (minAmount && maxAmount) {
                    amountInput.min = minAmount;
                    amountInput.max = maxAmount;
                    amountInput.placeholder = `Enter amount between $${parseFloat(minAmount).toLocaleString()} and $${parseFloat(maxAmount).toLocaleString()}`;
                }
            });
        }
    </script>
</body>

</html>