<?php
$page_title = "My Investments";
require_once '../config/config.php';

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


$db = Database::getInstance()->connect();
if (!$auth->isLoggedIn()) {
    header("Location: ../login.php");
    exit();
}
$user_id = $auth->getCurrentUserId();

// Get investment statistics
$stats_sql = "
    SELECT 
        COUNT(*) as total_investments,
        SUM(CASE WHEN status = 'running' THEN 1 ELSE 0 END) as active_investments,
        SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed_investments,
        SUM(amount) as total_invested,
        SUM(total_profit) as total_profits,
        SUM(CASE WHEN status = 'running' THEN amount ELSE 0 END) as active_invested
    FROM investments 
    WHERE user_id = ?
";

$stats_stmt = $db->prepare($stats_sql);
$stats_stmt->execute([$user_id]);
$stats = $stats_stmt->fetch();

// Get active investment plans for dropdown
$plans_stmt = $db->query("SELECT id, name, min_amount, max_amount, daily_return, duration_days FROM investment_plans WHERE status = 'active'");
$plans = $plans_stmt->fetchAll();

// Filter parameters
$status = $_GET['status'] ?? 'all';
$plan_id = $_GET['plan_id'] ?? '';
$start_date = $_GET['start_date'] ?? '';
$end_date = $_GET['end_date'] ?? '';
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$limit = 10;
$offset = ($page - 1) * $limit;

// Build query for investments
$where = "WHERE i.user_id = ?";
$params = [$user_id];

if ($status != 'all') {
    $where .= " AND i.status = ?";
    $params[] = $status;
}

if (!empty($plan_id) && is_numeric($plan_id)) {
    $where .= " AND i.plan_id = ?";
    $params[] = $plan_id;
}

if (!empty($start_date)) {
    $where .= " AND DATE(i.created_at) >= ?";
    $params[] = $start_date;
}

if (!empty($end_date)) {
    $where .= " AND DATE(i.created_at) <= ?";
    $params[] = $end_date;
}

// Get total count
$count_sql = "SELECT COUNT(*) as total FROM investments i $where";
$count_stmt = $db->prepare($count_sql);
$count_stmt->execute($params);
$total_investments = $count_stmt->fetch()['total'];
$total_pages = ceil($total_investments / $limit);

// Get investments with plan details
$sql = "
    SELECT 
        i.*, 
        p.name as plan_name,
        p.daily_return,
        p.duration_days,
        p.total_return,
        p.principal_return
    FROM investments i
    JOIN investment_plans p ON i.plan_id = p.id
    $where
    ORDER BY i.created_at DESC
    LIMIT $limit OFFSET $offset
";

$stmt = $db->prepare($sql);
$stmt->execute($params);
$investments = $stmt->fetchAll();

?>

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

    <!-- Page Header -->
    <div class="mb-6">
        <h1 class="text-2xl font-bold">My Investments</h1>
        <p class="text-gray-600">Track and manage your investment portfolio</p>
    </div>
    <!-- Stats Cards -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Total Investments</p>
                    <h3 class="text-2xl font-bold"><?php echo number_format((int)($stats['total_investments'] ?? 0)); ?></h3>
                </div>
                <i class="fas fa-chart-pie text-purple-500 text-2xl"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Active Investments</p>
                    <h3 class="text-2xl font-bold text-green-600"><?php echo number_format((int)($stats['active_investments'] ?? 0)); ?></h3>
                </div>
                <i class="fas fa-running text-green-500 text-2xl"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Total Invested</p>
                    <h3 class="text-2xl font-bold">$<?php echo number_format((float)($stats['total_invested'] ?? 0), 2); ?></h3>
                </div>
                <i class="fas fa-money-bill-wave text-blue-500 text-2xl"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Total Profits</p>
                    <h3 class="text-2xl font-bold text-green-600">$<?php echo number_format((float)($stats['total_profits'] ?? 0), 2); ?></h3>
                </div>
                <i class="fas fa-coins text-yellow-500 text-2xl"></i>
            </div>
        </div>
    </div>

    <!-- Quick Stats -->
    <div class="bg-gradient-to-r from-blue-500 to-purple-600 text-white rounded-xl p-6 mb-6">
        <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
            <div>
                <h3 class="text-xl font-bold mb-2">Investment Portfolio</h3>
                <p class="opacity-90">Currently active: <span class="font-bold">$<?php echo number_format((float)($stats['active_invested'] ?? 0), 2); ?></span></p>
            </div>
            <div>
                <a href="investment.php" class="bg-white text-blue-600 font-bold px-6 py-3 rounded-lg hover:bg-gray-100 inline-block">
                    <i class="fas fa-plus-circle mr-2"></i>New Investment
                </a>
            </div>
        </div>
    </div>

    <!-- Filters -->
    <div class="bg-white rounded-xl shadow p-6 mb-6">
        <form method="GET" action="" class="space-y-4">
            <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
                <!-- Status Filter -->
                <div>
                    <label class="block text-gray-700 text-sm mb-2">Status</label>
                    <select name="status" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                        <option value="all" <?php echo $status == 'all' ? 'selected' : ''; ?>>All Investments</option>
                        <option value="running" <?php echo $status == 'running' ? 'selected' : ''; ?>>Running</option>
                        <option value="completed" <?php echo $status == 'completed' ? 'selected' : ''; ?>>Completed</option>
                        <option value="cancelled" <?php echo $status == 'cancelled' ? 'selected' : ''; ?>>Cancelled</option>
                    </select>
                </div>
                
                <!-- Plan Filter -->
                <div>
                    <label class="block text-gray-700 text-sm mb-2">Plan</label>
                    <select name="plan_id" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                        <option value="">All Plans</option>
                        <?php foreach ($plans as $plan): ?>
                        <option value="<?php echo $plan['id']; ?>" <?php echo $plan_id == $plan['id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($plan['name']); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <!-- Start Date -->
                <div>
                    <label class="block text-gray-700 text-sm mb-2">From Date</label>
                    <input type="date" name="start_date" value="<?php echo htmlspecialchars($start_date); ?>"
                           class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                </div>
                
                <!-- End Date -->
                <div>
                    <label class="block text-gray-700 text-sm mb-2">To Date</label>
                    <input type="date" name="end_date" value="<?php echo htmlspecialchars($end_date); ?>"
                           class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                </div>
            </div>
            
            <div class="flex justify-between items-center pt-4">
                <div>
                    <button type="submit" class="bg-purple-600 text-white px-4 py-2 rounded-lg hover:bg-purple-700">
                        <i class="fas fa-filter mr-2"></i>Apply Filters
                    </button>
                    <a href="investments.php" class="ml-2 text-gray-600 hover:text-gray-800">
                        Clear Filters
                    </a>
                </div>
                
                <div class="text-sm text-gray-600">
                    Showing <?php echo number_format($total_investments); ?> investments
                </div>
            </div>
        </form>
    </div>

    <!-- Investments Table -->
    <div class="bg-white rounded-xl shadow overflow-hidden">
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="p-4 text-left">Investment</th>
                        <th class="p-4 text-left">Plan</th>
                        <th class="p-4 text-left">Amount</th>
                        <th class="p-4 text-left">Daily Profit</th>
                        <th class="p-4 text-left">Total Profit</th>
                        <th class="p-4 text-left">Period</th>
                        <th class="p-4 text-left">Status</th>
                        <th class="p-4 text-left">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100">
                    <?php if (count($investments) > 0): ?>
                        <?php foreach ($investments as $investment): 
                            $start_date_obj = new DateTime($investment['start_date']);
                            $end_date_obj = new DateTime($investment['end_date']);
                            $current_date = new DateTime();
                            
                            $total_days = $investment['duration_days'];
                            
                            if ($current_date > $end_date_obj) {
                                $days_elapsed = $total_days;
                            } else {
                                $days_elapsed = $current_date->diff($start_date_obj)->days;
                            }
                            
                            $days_left = max(0, $total_days - $days_elapsed);
                            $progress = min(100, ($days_elapsed / $total_days) * 100);
                            
                            // Calculate expected total profit
                            $daily_profit = $investment['amount'] * ($investment['daily_return'] / 100);
                            $expected_total = $daily_profit * $total_days;
                        ?>
                        <tr class="hover:bg-gray-50">
                            <!-- Investment Info -->
                            <td class="p-4">
                                <p class="font-medium">ID: <?php echo $investment['id']; ?></p>
                                <p class="text-sm text-gray-500"><?php echo date('M d, Y', strtotime($investment['created_at'])); ?></p>
                            </td>
                            
                            <!-- Plan -->
                            <td class="p-4">
                                <p class="font-medium"><?php echo htmlspecialchars($investment['plan_name']); ?></p>
                                <p class="text-sm text-gray-500"><?php echo $investment['daily_return']; ?>% daily</p>
                            </td>
                            
                            <!-- Amount -->
                            <td class="p-4">
                                <p class="font-bold text-green-600">$<?php echo number_format($investment['amount'], 2); ?></p>
                            </td>
                            
                            <!-- Daily Profit -->
                            <td class="p-4">
                                <p class="font-bold">$<?php echo number_format($daily_profit, 2); ?></p>
                                <p class="text-xs text-gray-500">Per day</p>
                            </td>
                            
                            <!-- Total Profit -->
                            <td class="p-4">
                                <div>
                                    <p class="font-bold text-green-600">$<?php echo number_format($investment['total_profit'], 2); ?></p>
                                    <p class="text-xs text-gray-500">of $<?php echo number_format($expected_total, 2); ?></p>
                                </div>
                            </td>
                            
                            <!-- Period -->
                            <td class="p-4">
                                <div class="space-y-2">
                                    <div class="flex justify-between text-sm">
                                        <span>Start:</span>
                                        <span><?php echo date('M d', strtotime($investment['start_date'])); ?></span>
                                    </div>
                                    <div class="flex justify-between text-sm">
                                        <span>End:</span>
                                        <span><?php echo date('M d, Y', strtotime($investment['end_date'])); ?></span>
                                    </div>
                                    <div class="flex justify-between text-sm">
                                        <span>Days left:</span>
                                        <span class="font-semibold <?php echo $days_left > 0 ? 'text-green-600' : 'text-red-600'; ?>">
                                            <?php echo $days_left; ?>
                                        </span>
                                    </div>
                                    <div class="w-full bg-gray-200 rounded-full h-2">
                                        <div class="bg-green-600 h-2 rounded-full" style="width: <?php echo $progress; ?>%"></div>
                                    </div>
                                </div>
                            </td>
                            
                            <!-- Status -->
                            <td class="p-4">
                                <span class="px-3 py-1 rounded-full text-xs font-semibold <?php
                                    echo $investment['status'] == 'running' ? 'bg-green-100 text-green-800' :
                                        ($investment['status'] == 'completed' ? 'bg-blue-100 text-blue-800' :
                                        'bg-red-100 text-red-800');
                                ?>">
                                    <?php echo ucfirst($investment['status']); ?>
                                </span>
                            </td>
                            
                            <!-- Actions -->
                            <td class="p-4">
                                <div class="flex flex-col space-y-2">
                                    <a href="investment.php?id=<?php echo $investment['id']; ?>" 
                                       class="text-blue-600 hover:text-blue-800 text-sm font-medium">
                                        <i class="fas fa-eye mr-1"></i> View Details
                                    </a>
                                    
                                    <?php if ($investment['status'] == 'running'): ?>
                                    <button onclick="reinvest(<?php echo $investment['id']; ?>)" 
                                            class="text-green-600 hover:text-green-800 text-sm font-medium text-left">
                                        <i class="fas fa-redo mr-1"></i> Reinvest
                                    </button>
                                    <?php endif; ?>
                                    
                                    <button onclick="exportInvestment(<?php echo $investment['id']; ?>)" 
                                            class="text-purple-600 hover:text-purple-800 text-sm font-medium text-left">
                                        <i class="fas fa-download mr-1"></i> Export
                                    </button>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="8" class="p-8 text-center text-gray-500">
                                <i class="fas fa-chart-pie text-4xl mb-4 text-gray-300"></i>
                                <p class="text-lg">No investments found</p>
                                <p class="text-sm mt-2">Start your first investment to grow your wealth</p>
                                <div class="mt-4">
                                    <a href="investment.php" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700">
                                        <i class="fas fa-plus mr-2"></i>Start Investing
                                    </a>
                                </div>
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        
        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
        <div class="border-t border-gray-100 p-4">
            <div class="flex items-center justify-between">
                <div class="text-sm text-gray-600">
                    Showing <?php echo ($offset + 1); ?> to <?php echo min($offset + $limit, $total_investments); ?> of <?php echo number_format($total_investments); ?> investments
                </div>
                <div class="flex space-x-2">
                    <?php if ($page > 1): ?>
                    <a href="?page=<?php echo $page - 1; ?>&status=<?php echo $status; ?>&plan_id=<?php echo $plan_id; ?>&start_date=<?php echo $start_date; ?>&end_date=<?php echo $end_date; ?>"
                       class="px-3 py-2 bg-gray-100 rounded-lg hover:bg-gray-200">
                        <i class="fas fa-chevron-left"></i> Previous
                    </a>
                    <?php endif; ?>
                    
                    <?php
                    $start_page = max(1, $page - 2);
                    $end_page = min($total_pages, $start_page + 4);
                    
                    for ($i = $start_page; $i <= $end_page; $i++):
                    ?>
                    <a href="?page=<?php echo $i; ?>&status=<?php echo $status; ?>&plan_id=<?php echo $plan_id; ?>&start_date=<?php echo $start_date; ?>&end_date=<?php echo $end_date; ?>"
                       class="px-3 py-2 rounded-lg <?php echo $i == $page ? 'bg-purple-600 text-white' : 'bg-gray-100 hover:bg-gray-200'; ?>">
                        <?php echo $i; ?>
                    </a>
                    <?php endfor; ?>
                    
                    <?php if ($page < $total_pages): ?>
                    <a href="?page=<?php echo $page + 1; ?>&status=<?php echo $status; ?>&plan_id=<?php echo $plan_id; ?>&start_date=<?php echo $start_date; ?>&end_date=<?php echo $end_date; ?>"
                       class="px-3 py-2 bg-gray-100 rounded-lg hover:bg-gray-200">
                        Next <i class="fas fa-chevron-right"></i>
                    </a>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>
    
    <!-- Investment Insights -->
    <div class="mt-6 grid grid-cols-1 md:grid-cols-2 gap-6">
        <!-- Performance Chart -->
        <div class="bg-white rounded-xl shadow p-6">
            <h3 class="text-lg font-bold mb-4">Investment Performance</h3>
            <div class="h-64">
                <canvas id="performanceChart"></canvas>
            </div>
        </div>
        
        <!-- Quick Tips -->
        <div class="bg-white rounded-xl shadow p-6">
            <h3 class="text-lg font-bold mb-4">Investment Tips</h3>
            <div class="space-y-4">
                <div class="flex items-start">
                    <i class="fas fa-lightbulb text-yellow-500 mt-1 mr-3"></i>
                    <div>
                        <p class="font-medium">Diversify Your Portfolio</p>
                        <p class="text-sm text-gray-600">Spread investments across different plans for better risk management.</p>
                    </div>
                </div>
                <div class="flex items-start">
                    <i class="fas fa-chart-line text-green-500 mt-1 mr-3"></i>
                    <div>
                        <p class="font-medium">Reinvest Profits</p>
                        <p class="text-sm text-gray-600">Reinvest your profits to take advantage of compound growth.</p>
                    </div>
                </div>
                <div class="flex items-start">
                    <i class="fas fa-calendar-alt text-blue-500 mt-1 mr-3"></i>
                    <div>
                        <p class="font-medium">Monitor Regularly</p>
                        <p class="text-sm text-gray-600">Check your investment progress and make adjustments as needed.</p>
                    </div>
                </div>
                <div class="flex items-start">
                    <i class="fas fa-shield-alt text-purple-500 mt-1 mr-3"></i>
                    <div>
                        <p class="font-medium">Risk Management</p>
                        <p class="text-sm text-gray-600">Only invest what you can afford to lose. Start small and grow gradually.</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

<!-- Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
// Prepare data for chart
const investmentData = <?php
    $chart_data = [];
    foreach ($investments as $inv) {
        if ($inv['status'] == 'running') {
            $chart_data[] = [
                'label' => $inv['plan_name'],
                'amount' => $inv['amount'],
                'profit' => $inv['total_profit']
            ];
        }
    }
    echo json_encode($chart_data);
?>;

// Performance Chart
const ctx = document.getElementById('performanceChart').getContext('2d');
const performanceChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: investmentData.map(item => item.label.substring(0, 15) + '...'),
        datasets: [
            {
                label: 'Invested Amount',
                data: investmentData.map(item => item.amount),
                backgroundColor: 'rgba(59, 130, 246, 0.5)',
                borderColor: 'rgb(59, 130, 246)',
                borderWidth: 1
            },
            {
                label: 'Profit Earned',
                data: investmentData.map(item => item.profit),
                backgroundColor: 'rgba(34, 197, 94, 0.5)',
                borderColor: 'rgb(34, 197, 94)',
                borderWidth: 1
            }
        ]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: {
                position: 'top',
            },
            tooltip: {
                callbacks: {
                    label: function(context) {
                        return context.dataset.label + ': $' + context.parsed.y.toFixed(2);
                    }
                }
            }
        },
        scales: {
            y: {
                beginAtZero: true,
                ticks: {
                    callback: function(value) {
                        return '$' + value.toFixed(2);
                    }
                }
            }
        }
    }
});

// Reinvest function
function reinvest(investmentId) {
    if (confirm('Reinvest profits from this investment?')) {
        $.ajax({
            url: '../api/reinvest.php',
            method: 'POST',
            data: { investment_id: investmentId },
            success: function(response) {
                const result = JSON.parse(response);
                alert(result.message);
                if (result.success) {
                    location.reload();
                }
            }
        });
    }
}

// Export investment
function exportInvestment(investmentId) {
    window.open(../api/export-investment.php?id=${investmentId}, '_blank');
}

// Auto-refresh page every 5 minutes for live updates
setTimeout(() => {
    location.reload();
}, 300000); // 5 minutes

// Calculate total portfolio value
function calculatePortfolioValue() {
    const activeInvestments = <?php echo $stats['active_invested'] ?? 0; ?>;
    const totalProfits = <?php echo $stats['total_profits'] ?? 0; ?>;
    const portfolioValue = activeInvestments + totalProfits;
    
    return portfolioValue;
}

// Display portfolio value
document.addEventListener('DOMContentLoaded', function() {
    const portfolioValue = calculatePortfolioValue();
    console.log('Portfolio Value: $' + portfolioValue.toFixed(2));
});
</script>

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