<?php
require_once '../includes/user_auth.php';
require_once '../includes/functions.php';

if (!isset($auth)) {
    $auth = new Auth();
}

$user_id = $auth->getCurrentUserId();
$user_data = $auth->getCurrentUser();
if (!$user_id) {
    header("Location: ../login.php?error=session_lost");
    exit();
}
$db = Database::getInstance()->connect();
$functions = new InvestmentFunctions();
$stats = $functions->getUserStats($user_id);

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

// Get running investments
$stmt = $db->prepare("SELECT i.*, p.name as plan_name FROM investments i 
                                JOIN investment_plans p ON i.plan_id = p.id 
                                WHERE i.user_id = ? AND i.status = 'running' 
                                ORDER BY i.created_at DESC");
$stmt->execute([$user_id]);
$investments = $stmt->fetchAll();
?>

<?php require_once '../includes/header_user.php'; ?>

            <div class="mb-6">
                <p class="text-gray-600">Welcome back, <?php echo htmlspecialchars($user_data['username']); ?>!</p>
            </div>

            <!-- Stats Cards -->
            <div class="p-6 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                <!-- Account Balance -->
                <div class="bg-white rounded-xl shadow p-6 border-l-4 border-blue-500 hover:shadow-lg transition-shadow">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-600 text-sm uppercase tracking-wider">Account Balance</p>
                            <h3 class="text-2xl font-bold text-blue-600 mt-1">$<?php echo number_format($user_data['balance'] ?? 0, 2); ?></h3>
                        </div>
                        <div class="bg-blue-100 p-3 rounded-full">
                            <i class="fas fa-wallet text-blue-600 text-2xl"></i>
                        </div>
                    </div>
                    <div class="mt-4 pt-4 border-t border-gray-100">
                        <a href="deposit.php" class="text-blue-600 hover:text-blue-800 text-sm font-semibold flex items-center">
                            Add Funds <i class="fas fa-arrow-right ml-2"></i>
                        </a>
                    </div>
                </div>

                <!-- Total Deposit -->
                <div class="bg-white rounded-xl shadow p-6 border-l-4 border-green-500 hover:shadow-lg transition-shadow">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-600 text-sm uppercase tracking-wider">Total Deposit</p>
                            <h3 class="text-2xl font-bold text-green-600 mt-1">$<?php echo number_format($user_data['total_deposit'] ?? 0, 2); ?></h3>
                        </div>
                        <div class="bg-green-100 p-3 rounded-full">
                            <i class="fas fa-money-bill-wave text-green-600 text-2xl"></i>
                        </div>
                    </div>
                    <div class="mt-4 pt-4 border-t border-gray-100">
                        <a href="transactions.php?type=deposit" class="text-green-600 hover:text-green-800 text-sm font-semibold flex items-center">
                            View History <i class="fas fa-history ml-2"></i>
                        </a>
                    </div>
                </div>

                <!-- Profit Balance -->
                <div class="bg-white rounded-xl shadow p-6 border-l-4 border-purple-500 hover:shadow-lg transition-shadow">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-600 text-sm uppercase tracking-wider">Profit Balance</p>
                            <h3 class="text-2xl font-bold text-purple-600 mt-1">$<?php echo number_format($user_data['profit_balance'] ?? 0, 2); ?></h3>
                        </div>
                        <div class="bg-purple-100 p-3 rounded-full">
                            <i class="fas fa-chart-line text-purple-600 text-2xl"></i>
                        </div>
                    </div>
                    <div class="mt-4 pt-4 border-t border-gray-100">
                        <a href="profits.php" class="text-purple-600 hover:text-purple-800 text-sm font-semibold flex items-center">
                            View Profits <i class="fas fa-coins ml-2"></i>
                        </a>
                    </div>
                </div>

                <!-- Referral Bonus -->
                <div class="bg-white rounded-xl shadow p-6 border-l-4 border-yellow-500 hover:shadow-lg transition-shadow">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-600 text-sm uppercase tracking-wider">Referral Bonus</p>
                            <h3 class="text-2xl font-bold text-yellow-600 mt-1">$<?php echo number_format($user_data['referral_balance'] ?? 0, 2); ?></h3>
                        </div>
                        <div class="bg-yellow-100 p-3 rounded-full">
                            <i class="fas fa-users text-yellow-600 text-2xl"></i>
                        </div>
                    </div>
                    <div class="mt-4 pt-4 border-t border-gray-100">
                        <a href="referral.php" class="text-yellow-600 hover:text-yellow-800 text-sm font-semibold flex items-center">
                            Invite Friends <i class="fas fa-share ml-2"></i>
                        </a>
                    </div>
                </div>
            </div>

            <!-- Charts and Investments -->
            <div class="p-6 grid grid-cols-1 lg:grid-cols-3 gap-6">
                <!-- Running Investments -->
                <div class="lg:col-span-2">
                    <div class="bg-white rounded-xl shadow p-6">
                        <div class="flex justify-between items-center mb-6">
                            <h3 class="text-xl font-bold">Running Investments</h3>
                            <a href="investments.php" class="text-purple-600 hover:text-purple-800 text-sm font-semibold">
                                View All <i class="fas fa-arrow-right ml-1"></i>
                            </a>
                        </div>
                        
                        <?php if (count($investments) > 0): ?>
                            <div class="overflow-x-auto">
                                <table class="w-full">
                                    <thead>
                                        <tr class="bg-gray-50">
                                            <th class="p-3 text-left text-sm font-semibold text-gray-600">Plan</th>
                                            <th class="p-3 text-left text-sm font-semibold text-gray-600">Amount</th>
                                            <th class="p-3 text-left text-sm font-semibold text-gray-600">Daily Profit</th>
                                            <th class="p-3 text-left text-sm font-semibold text-gray-600">End Date</th>
                                            <th class="p-3 text-left text-sm font-semibold text-gray-600">Status</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($investments as $investment): 
                                            $end_date = new DateTime($investment['end_date']);
                                            $now = new DateTime();
                                            $days_left = $now->diff($end_date)->days;
                                        ?>
                                        <tr class="border-b border-gray-100 hover:bg-gray-50">
                                            <td class="p-3"><?php echo htmlspecialchars($investment['plan_name']); ?></td>
                                            <td class="p-3 font-semibold">$<?php echo number_format($investment['amount'], 2); ?></td>
                                            <td class="p-3 text-green-600 font-semibold">$<?php echo number_format($investment['daily_profit'], 2); ?></td>
                                            <td class="p-3">
                                                <?php echo date('M d, Y', strtotime($investment['end_date'])); ?>
                                                <span class="text-xs text-gray-500">(<?php echo $days_left; ?> days left)</span>
                                            </td>
                                            <td class="p-3">
                                                <span class="px-3 py-1 rounded-full text-xs font-semibold bg-green-100 text-green-800">
                                                    Running
                                                </span>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php else: ?>
                            <div class="text-center py-8">
                                <div class="text-gray-400 mb-4">
                                    <i class="fas fa-chart-pie text-4xl"></i>
                                </div>
                                <h4 class="text-lg font-semibold text-gray-600 mb-2">No Active Investments</h4>
                                <p class="text-gray-500 mb-4">Start investing to earn daily profits</p>
                                <a href="investment.php" class="inline-block bg-gradient-to-r from-purple-600 to-blue-600 text-white px-6 py-2 rounded-lg font-semibold hover:opacity-90">
                                    <i class="fas fa-plus mr-2"></i>Start Investing
                                </a>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Recent Transactions -->
                <div>
                    <div class="bg-white rounded-xl shadow p-6">
                        <div class="flex justify-between items-center mb-6">
                            <h3 class="text-xl font-bold">Recent Transactions</h3>
                            <a href="transactions.php" class="text-purple-600 hover:text-purple-800 text-sm font-semibold">
                                View All <i class="fas fa-arrow-right ml-1"></i>
                            </a>
                        </div>
                        
                        <div class="space-y-4">
                            <?php if (count($transactions) > 0): ?>
                                <?php foreach ($transactions as $transaction): 
                                    $type_colors = [
                                        'deposit' => 'bg-green-100 text-green-800',
                                        'withdrawal' => 'bg-red-100 text-red-800',
                                        'profit' => 'bg-blue-100 text-blue-800',
                                        'bonus' => 'bg-yellow-100 text-yellow-800'
                                    ];
                                    $color = $type_colors[$transaction['type']] ?? 'bg-gray-100 text-gray-800';
                                ?>
                                <div class="flex items-center justify-between p-3 rounded-lg border border-gray-100 hover:bg-gray-50">
                                    <div class="flex items-center space-x-3">
                                        <div class="w-10 h-10 rounded-full flex items-center justify-center <?php echo str_replace('text-', 'bg-', str_replace('bg-', '', explode(' ', $color)[0])) . '100'; ?>">
                                            <i class="<?php 
                                                echo $transaction['type'] == 'deposit' ? 'fas fa-arrow-down text-green-600' : 
                                                    ($transaction['type'] == 'withdrawal' ? 'fas fa-arrow-up text-red-600' : 
                                                    ($transaction['type'] == 'profit' ? 'fas fa-chart-line text-blue-600' : 'fas fa-gift text-yellow-600')); 
                                            ?>"></i>
                                        </div>
                                        <div>
                                            <p class="font-semibold"><?php echo ucfirst($transaction['type']); ?></p>
                                            <p class="text-xs text-gray-500"><?php echo date('M d, h:i A', strtotime($transaction['created_at'])); ?></p>
                                        </div>
                                    </div>
                                    <div class="text-right">
                                        <p class="font-bold <?php echo $transaction['type'] == 'deposit' || $transaction['type'] == 'profit' || $transaction['type'] == 'bonus' ? 'text-green-600' : 'text-red-600'; ?>">
                                            <?php echo ($transaction['type'] == 'deposit' || $transaction['type'] == 'profit' || $transaction['type'] == 'bonus' ? '+' : '-'); ?>
                                            $<?php echo number_format($transaction['amount'], 2); ?>
                                        </p>
                                        <span class="px-2 py-1 text-xs rounded-full <?php 
                                            echo $transaction['status'] == 'completed' ? 'bg-green-100 text-green-800' : 
                                                ($transaction['status'] == 'pending' ? 'bg-yellow-100 text-yellow-800' : 
                                                'bg-red-100 text-red-800'); 
                                        ?>">
                                            <?php echo ucfirst($transaction['status']); ?>
                                        </span>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <div class="text-center py-8">
                                    <div class="text-gray-400 mb-4">
                                        <i class="fas fa-exchange-alt text-4xl"></i>
                                    </div>
                                    <p class="text-gray-500">No transactions yet</p>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>

                    <!-- Quick Stats -->
                    <div class="mt-6 bg-gradient-to-r from-purple-600 to-blue-600 rounded-xl shadow p-6 text-white">
                        <h4 class="text-lg font-bold mb-4">Investment Summary</h4>
                        <div class="space-y-3">
                            <div class="flex justify-between items-center">
                                <span>Running Investment:</span>
                                <span class="font-bold">$<?php echo number_format($stats['running_amount'] ?? 0, 2); ?></span>
                            </div>
                            <div class="flex justify-between items-center">
                                <span>Total Withdrawn:</span>
                                <span class="font-bold">$<?php echo number_format($user_data['total_withdrawal'] ?? 0, 2); ?></span>
                            </div>
                            <div class="flex justify-between items-center">
                                <span>Account Status:</span>
                                <span class="font-bold text-green-300">Active</span>
                            </div>
                        </div>
                        <div class="mt-6">
                            <a href="investment.php" class="block text-center bg-white text-purple-600 py-2 rounded-lg font-semibold hover:bg-gray-100">
                                Invest Now
                            </a>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Quick Actions -->
            <div class="p-6">
                <div class="bg-white rounded-xl shadow p-6">
                    <h3 class="text-xl font-bold mb-6">Quick Actions</h3>
                    <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
                        <a href="deposit.php" class="bg-gradient-to-r from-green-50 to-green-100 border border-green-200 rounded-lg p-4 text-center hover:shadow-md transition-shadow">
                            <div class="text-green-600 mb-2">
                                <i class="fas fa-plus-circle text-3xl"></i>
                            </div>
                            <h4 class="font-semibold text-gray-800">Deposit Funds</h4>
                            <p class="text-sm text-gray-600 mt-1">Add money to your account</p>
                        </a>
                        
                        <a href="withdrawal.php" class="bg-gradient-to-r from-blue-50 to-blue-100 border border-blue-200 rounded-lg p-4 text-center hover:shadow-md transition-shadow">
                            <div class="text-blue-600 mb-2">
                                <i class="fas fa-wallet text-3xl"></i>
                            </div>
                            <h4 class="font-semibold text-gray-800">Withdraw Funds</h4>
                            <p class="text-sm text-gray-600 mt-1">Withdraw your earnings</p>
                        </a>
                        
                        <a href="investment.php" class="bg-gradient-to-r from-purple-50 to-purple-100 border border-purple-200 rounded-lg p-4 text-center hover:shadow-md transition-shadow">
                            <div class="text-purple-600 mb-2">
                                <i class="fas fa-chart-pie text-3xl"></i>
                            </div>
                            <h4 class="font-semibold text-gray-800">Invest</h4>
                            <p class="text-sm text-gray-600 mt-1">Start earning daily profits</p>
                        </a>
                        
                        <a href="referral.php" class="bg-gradient-to-r from-yellow-50 to-yellow-100 border border-yellow-200 rounded-lg p-4 text-center hover:shadow-md transition-shadow">
                            <div class="text-yellow-600 mb-2">
                                <i class="fas fa-users text-3xl"></i>
                            </div>
                            <h4 class="font-semibold text-gray-800">Refer & Earn</h4>
                            <p class="text-sm text-gray-600 mt-1">Earn $10 per referral</p>
                        </a>
                    </div>
                </div>
            </div>

<?php require_once '../includes/footer.php'; ?> 

    <script>
      

        // Update balance with animation
        function updateBalance() {
            $.ajax({
                url: '../api/get_balance.php',
                method: 'GET',
                success: function(response) {
                    const data = JSON.parse(response);
                    if (data.success) {
                        // Animate balance update
                        $('.balance-display').each(function() {
                            const current = parseFloat($(this).text().replace('$', '').replace(',', ''));
                            const target = parseFloat(data.balance);
                            animateValue($(this), current, target, 1000);
                        });
                    }
                }
            });
        }

        function animateValue(element, start, end, duration) {
            let startTimestamp = null;
            const step = (timestamp) => {
                if (!startTimestamp) startTimestamp = timestamp;
                const progress = Math.min((timestamp - startTimestamp) / duration, 1);
                const value = Math.floor(progress * (end - start) + start);
                element.text('$' + value.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2}));
                if (progress < 1) {
                    window.requestAnimationFrame(step);
                }
            };
            window.requestAnimationFrame(step);
        }

        // Update balance every 30 seconds
        setInterval(updateBalance, 30000);
    </script>