<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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

// Check session status
checkSessionStatus();

// Set the timeout duration (15 minutes in seconds)
$timeoutDuration = 900;  // 15 minutes

// Set the logout redirect URL
$logoutRedirectUrl = '../logout.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit();
}

// Check if session has expired
if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity']) > $timeoutDuration) {
    // If session expired, log out user
    session_unset();
    session_destroy();
    header("Location: $logoutRedirectUrl");
    exit();
}

// Update last activity time
$_SESSION['last_activity'] = time();

// 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.');
}

// Get recent transactions
$stmt = $pdo->prepare("
    SELECT * FROM transactions 
    WHERE account_id = (SELECT account_id FROM accounts WHERE user_id = ?)
    ORDER BY created_at DESC 
    LIMIT 5
");
$stmt->execute([$userId]);
$transactions = $stmt->fetchAll();

// Get active loans
$stmt = $pdo->prepare("
    SELECT * FROM loans 
    WHERE user_id = ? AND status = 'approved' AND is_paid = 'no'
    ORDER BY created_at DESC
    LIMIT 3
");
$stmt->execute([$userId]);
$activeLoans = $stmt->fetchAll();

// Get active investments
$stmt = $pdo->prepare("
    SELECT i.*, ip.plan_name, ip.interest_rate 
    FROM investments i
    JOIN investment_plans ip ON i.plan_id = ip.plan_id
    WHERE i.user_id = ? AND i.status = 'active'
    ORDER BY i.created_at DESC
    LIMIT 3
");
$stmt->execute([$userId]);
$activeInvestments = $stmt->fetchAll();

// Check if the user has a profile picture
$profilePic = $user['profile_picture'] ? '../uploads/' . $user['profile_picture'] : '../assets/images/default-avatars.png';

// Calculate total deposit amount for current month
$stmt = $pdo->prepare("
    SELECT SUM(amount) as total 
    FROM transactions 
    WHERE account_id = (SELECT account_id FROM accounts WHERE user_id = ?)
    AND type = 'deposit'
    AND MONTH(created_at) = MONTH(CURRENT_DATE())
    AND YEAR(created_at) = YEAR(CURRENT_DATE())
");
$stmt->execute([$userId]);
$monthlyDeposit = $stmt->fetch()['total'] ?? 0;

// Calculate total withdrawal for current month
$stmt = $pdo->prepare("
    SELECT SUM(amount) as total 
    FROM transactions 
    WHERE account_id = (SELECT account_id FROM accounts WHERE user_id = ?)
    AND type = 'withdrawal'
    AND MONTH(created_at) = MONTH(CURRENT_DATE())
    AND YEAR(created_at) = YEAR(CURRENT_DATE())
");
$stmt->execute([$userId]);
$monthlyWithdrawal = $stmt->fetch()['total'] ?? 0;
?>

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Oakshire Finance - Dashboard</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">
    <script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
    <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: var(--transition);
            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;
        }

        /* Welcome Banner */
        .welcome-banner {
            background: linear-gradient(135deg, var(--primary-navy), var(--primary-dark));
            border-radius: 24px;
            padding: 32px;
            margin-bottom: 32px;
            color: white;
        }

        .welcome-banner h2 {
            font-size: 28px;
            font-weight: 700;
            margin-bottom: 8px;
        }

        .welcome-banner p {
            opacity: 0.85;
            margin-bottom: 0;
        }

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

        .stat-card {
            background: var(--white);
            border-radius: 20px;
            padding: 24px;
            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: 32px;
            font-weight: 700;
            color: var(--gray-900);
        }

        .stat-trend {
            font-size: 12px;
            color: var(--gray-500);
            margin-top: 8px;
        }

        /* Quick Actions */
        .quick-actions {
            background: var(--white);
            border-radius: 20px;
            padding: 24px;
            border: 1px solid var(--gray-200);
            margin-bottom: 32px;
        }

        .quick-actions h3 {
            font-size: 18px;
            font-weight: 600;
            margin-bottom: 20px;
        }

        .action-buttons {
            display: flex;
            flex-wrap: wrap;
            gap: 12px;
        }

        .action-btn {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 10px 20px;
            background: var(--gray-100);
            color: var(--gray-700);
            text-decoration: none;
            border-radius: 12px;
            font-weight: 500;
            font-size: 14px;
            transition: var(--transition);
        }

        .action-btn:hover {
            background: var(--primary-navy);
            color: white;
            transform: translateY(-2px);
        }

        /* Section Headers */
        .section-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .section-header h2 {
            font-size: 20px;
            font-weight: 600;
            color: var(--gray-900);
        }

        .view-all {
            color: var(--primary-blue);
            text-decoration: none;
            font-size: 14px;
            font-weight: 500;
        }

        .view-all:hover {
            text-decoration: underline;
        }

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

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

        .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: 13px;
            color: var(--gray-700);
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .data-table td {
            font-size: 14px;
            color: var(--gray-800);
        }

        .data-table tr:hover td {
            background: var(--gray-50);
        }

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

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

        .badge-negative {
            background: rgba(220, 53, 69, 0.1);
            color: var(--error-red);
        }

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

        /* Charts Grid */
        .charts-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
            gap: 24px;
            margin-bottom: 32px;
        }

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

        .chart-card h3 {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 20px;
        }

        /* Empty State */
        .empty-state {
            text-align: center;
            padding: 48px;
            color: var(--gray-500);
        }

        .empty-state i {
            font-size: 48px;
            margin-bottom: 16px;
            opacity: 0.5;
        }

        /* 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;
            }

            .welcome-banner h2 {
                font-size: 22px;
            }

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

            .charts-grid {
                grid-template-columns: 1fr;
            }

            .action-buttons {
                justify-content: center;
            }

            .data-table th,
            .data-table td {
                padding: 12px 16px;
            }
        }
    </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 active">
                        <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">
                        <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>
                <div class="nav-item">
                    <a href="login-records.php" class="nav-link">
                        <i class="fas fa-sign-in-alt"></i>
                        <span>Login Records</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>Dashboard</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">
                <!-- Welcome Banner -->
                <div class="welcome-banner">
                    <h2>Welcome back, <?= htmlspecialchars($user['full_name']) ?>!</h2>
                    <p>Here's your financial overview for today.</p>
                </div>

                <!-- Stats Cards -->
                <div class="stats-grid">
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-wallet"></i>
                        </div>
                        <h3>Current Balance</h3>
                        <div class="stat-value">$<?= number_format($user['balance'], 2) ?></div>
                        <div class="stat-trend">Available funds</div>
                    </div>

                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-arrow-down"></i>
                        </div>
                        <h3>Monthly Deposits</h3>
                        <div class="stat-value">$<?= number_format($monthlyDeposit, 2) ?></div>
                        <div class="stat-trend">This month</div>
                    </div>

                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-arrow-up"></i>
                        </div>
                        <h3>Monthly Withdrawals</h3>
                        <div class="stat-value">$<?= number_format($monthlyWithdrawal, 2) ?></div>
                        <div class="stat-trend">This month</div>
                    </div>

                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-building-columns"></i>
                        </div>
                        <h3>Account Number</h3>
                        <div class="stat-value" style="font-size: 18px;">
                            <?= htmlspecialchars($user['account_number']) ?></div>
                        <div class="stat-trend">Your account ID</div>
                    </div>
                </div>

                <!-- Quick Actions -->
                <div class="quick-actions">
                    <h3>Quick Actions</h3>
                    <div class="action-buttons">
                        <a href="deposit.php" class="action-btn"><i class="fas fa-arrow-down"></i> Deposit</a>
                        <a href="withdraw.php" class="action-btn"><i class="fas fa-arrow-up"></i> Withdraw</a>
                        <a href="transfer.php" class="action-btn"><i class="fas fa-exchange-alt"></i> Transfer</a>
                        <a href="loan.php" class="action-btn"><i class="fas fa-hand-holding-usd"></i> Apply Loan</a>
                        <a href="loan-payment.php" class="action-btn"><i class="fas fa-credit-card"></i> Pay Loan</a>
                        <a href="profile.php" class="action-btn"><i class="fas fa-user-cog"></i> Settings</a>
                    </div>
                </div>

                <!-- Charts Grid -->
                <div class="charts-grid">
                    <div class="chart-card">
                        <h3><i class="fas fa-chart-bar"></i> Weekly Activity</h3>
                        <div id="weeklyChart"></div>
                    </div>
                    <div class="chart-card">
                        <h3><i class="fas fa-chart-pie"></i> Transaction Distribution</h3>
                        <div id="pieChart"></div>
                    </div>
                </div>

                <div class="chart-card" style="margin-bottom: 32px;">
                    <h3><i class="fas fa-chart-line"></i> Balance History</h3>
                    <div id="balanceChart"></div>
                </div>

                <!-- Recent Transactions -->
                <div class="section-header">
                    <h2>Recent Transactions</h2>
                    <a href="transactions.php" class="view-all">View All <i class="fas fa-arrow-right"></i></a>
                </div>

                <div class="table-container">
                    <?php if (empty($transactions)): ?>
                        <div class="empty-state">
                            <i class="fas fa-receipt"></i>
                            <p>No recent transactions found</p>
                        </div>
                    <?php else: ?>
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Transaction ID</th>
                                    <th>Description</th>
                                    <th>Type</th>
                                    <th>Date</th>
                                    <th>Amount</th>
                                    <th>Receipt</th>
                            </thead>
                            <tbody>
                                <?php foreach ($transactions as $txn): ?>
                                    <tr>
                                        <td><code>#<?= htmlspecialchars($txn['transaction_id']) ?></code></td>
                                        <td><?= htmlspecialchars($txn['description'] ?? '—') ?></td>
                                        <td>
                                            <span
                                                class="badge <?= in_array($txn['type'], ['deposit', 'transfer_in']) ? 'badge-positive' : 'badge-negative' ?>">
                                                <?= ucfirst(str_replace('_', ' ', $txn['type'])) ?>
                                            </span>
                                        </td>
                                        <td><?= date('M d, Y h:i A', strtotime($txn['created_at'])) ?></td>
                                        <td class="<?= in_array($txn['type'], ['deposit', 'transfer_in']) ? 'badge-positive' : 'badge-negative' ?>"
                                            style="font-weight: 600;">
                                            <?= (in_array($txn['type'], ['deposit', 'transfer_in']) ? '+' : '-') ?>
                                            $<?= number_format($txn['amount'], 2) ?>
                                        </td>
                                        <td>
                                            <button
                                                onclick="window.open('generate_receipt.php?transaction_id=<?= $txn['transaction_id'] ?>', '_blank')"
                                                style="background: none; border: none; color: var(--primary-blue); cursor: pointer;">
                                                <i class="fas fa-download"></i> Receipt
                                            </button>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    <?php endif; ?>
                </div>

                <!-- Active Loans -->
                <?php if (!empty($activeLoans)): ?>
                    <div class="section-header">
                        <h2>Active Loans</h2>
                        <a href="loan.php" class="view-all">View All <i class="fas fa-arrow-right"></i></a>
                    </div>

                    <div class="table-container">
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Loan ID</th>
                                    <th>Amount</th>
                                    <th>Interest Rate</th>
                                    <th>Total Due</th>
                                    <th>Purpose</th>
                                    <th>Approved Date</th>
                            </thead>
                            <tbody>
                                <?php foreach ($activeLoans as $loan): ?>
                                    <tr>
                                        <td><code>#<?= $loan['loan_id'] ?></code></td>
                                        <td>$<?= number_format($loan['amount'], 2) ?></td>
                                        <td><?= $loan['interest_rate'] ?>%</td>
                                        <td>$<?= number_format($loan['total_due'], 2) ?></td>
                                        <td><?= htmlspecialchars($loan['purpose']) ?></td>
                                        <td><?= date('M d, Y', strtotime($loan['approved_at'])) ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>

                <!-- Active Investments -->
                <?php if (!empty($activeInvestments)): ?>
                    <div class="section-header">
                        <h2>Active Investments</h2>
                        <a href="investment.php" class="view-all">View All <i class="fas fa-arrow-right"></i></a>
                    </div>

                    <div class="table-container">
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Plan Name</th>
                                    <th>Amount</th>
                                    <th>Interest Rate</th>
                                    <th>Expected Return</th>
                                    <th>Start Date</th>
                                    <th>Maturity Date</th>
                            </thead>
                            <tbody>
                                <?php foreach ($activeInvestments as $investment): ?>
                                    <tr>
                                        <td><?= htmlspecialchars($investment['plan_name']) ?></td>
                                        <td>$<?= number_format($investment['amount'], 2) ?></td>
                                        <td><?= $investment['interest_rate'] ?>%</td>
                                        <td>$<?= number_format($investment['amount'] * (1 + $investment['interest_rate'] / 100), 2) ?>
                                        </td>
                                        <td><?= date('M d, Y', strtotime($investment['created_at'])) ?></td>
                                        <td><?= date('M d, Y', strtotime($investment['matured_at'])) ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </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');
                }
            }
        });

        // Weekly Activity Chart
        document.addEventListener("DOMContentLoaded", function () {
            fetch('get_weekly_activity.php')
                .then(response => response.json())
                .then(data => {
                    const days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
                    const deposits = Array(7).fill(0);
                    const withdrawals = Array(7).fill(0);
                    const transfers = Array(7).fill(0);

                    data.forEach(entry => {
                        const index = days.indexOf(entry.day);
                        if (index !== -1) {
                            deposits[index] = parseFloat(entry.total_deposit || 0);
                            withdrawals[index] = parseFloat(entry.total_withdraw || 0);
                            transfers[index] = parseFloat(entry.total_transfer_in || 0) + parseFloat(entry.total_transfer_out || 0);
                        }
                    });

                    const options = {
                        chart: {
                            type: 'bar',
                            height: 350,
                            toolbar: { show: false }
                        },
                        series: [
                            { name: 'Deposits', data: deposits, color: '#2e7d32' },
                            { name: 'Withdrawals', data: withdrawals, color: '#dc3545' },
                            { name: 'Transfers', data: transfers, color: '#17a2b8' }
                        ],
                        xaxis: { categories: days },
                        yaxis: { title: { text: 'Amount ($)' } },
                        tooltip: { y: { formatter: (val) => '$' + val.toFixed(2) } },
                        plotOptions: { bar: { borderRadius: 8, columnWidth: '55%' } },
                        legend: { position: 'bottom' }
                    };

                    const chart = new ApexCharts(document.querySelector("#weeklyChart"), options);
                    chart.render();
                })
                .catch(error => console.error('Error loading chart data:', error));
        });

        // Transaction Distribution Pie Chart
        document.addEventListener("DOMContentLoaded", function () {
            fetch('get_transaction_distribution.php')
                .then(response => response.json())
                .then(data => {
                    const labels = [];
                    const values = [];

                    data.forEach(entry => {
                        let label = '';
                        switch (entry.type) {
                            case 'deposit': label = 'Deposit'; break;
                            case 'transfer_out': label = 'Transfer'; break;
                            case 'withdrawal': label = 'Withdraw'; break;
                            default: label = entry.type;
                        }
                        labels.push(label);
                        values.push(parseFloat(entry.total));
                    });

                    if (values.length === 0) {
                        document.querySelector("#pieChart").innerHTML = "<p style='text-align:center; padding:40px;'>No transaction data available.</p>";
                        return;
                    }

                    const options = {
                        chart: { type: 'pie', height: 350 },
                        series: values,
                        labels: labels,
                        colors: ['#2e7d32', '#dc3545', '#17a2b8', '#ffc107'],
                        legend: { position: 'bottom' }
                    };

                    const pieChart = new ApexCharts(document.querySelector("#pieChart"), options);
                    pieChart.render();
                })
                .catch(error => console.error('Error loading pie chart data:', error));
        });

        // Balance Over Time Chart
        document.addEventListener("DOMContentLoaded", function () {
            fetch('get_balance_history.php')
                .then(response => response.json())
                .then(balanceData => {
                    const options = {
                        chart: { type: 'area', height: 350, toolbar: { show: false } },
                        series: [{ name: 'Account Balance', data: balanceData, color: '#0a2540' }],
                        stroke: { width: 3, curve: 'smooth' },
                        fill: { type: 'gradient', gradient: { shadeIntensity: 1, opacityFrom: 0.7, opacityTo: 0.2 } },
                        xaxis: { type: 'datetime', labels: { format: 'MMM dd' } },
                        yaxis: { title: { text: 'Balance ($)' }, labels: { formatter: (val) => '$' + val.toLocaleString() } },
                        tooltip: { y: { formatter: (val) => '$' + val.toLocaleString() } }
                    };
                    const chart = new ApexCharts(document.querySelector("#balanceChart"), options);
                    chart.render();
                })
                .catch(error => console.error('Error loading balance history:', error));
        });
    </script>
</body>

</html>