<?php
$page_title = "Profit History";
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 profit statistics
$stats_sql = "
    SELECT 
        COUNT(*) as total_profits,
        SUM(amount) as total_profit_amount,
        MIN(created_at) as first_profit_date,
        MAX(created_at) as last_profit_date,
        AVG(amount) as avg_daily_profit,
        (SELECT SUM(total_profit) FROM investments WHERE user_id = ? AND status = 'running') as current_investment_profits,
        (SELECT SUM(total_profit) FROM investments WHERE user_id = ? AND status = 'completed') as completed_investment_profits
    FROM transactions 
    WHERE user_id = ? AND type = 'profit' AND status = 'completed'
";

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

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

// Build query
$where = "WHERE t.user_id = ? AND t.type = 'profit'";
$params = [$user_id];

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

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

if (!empty($investment_id) && is_numeric($investment_id)) {
    $where .= " AND t.description LIKE ?";
    $params[] = "%investment #" . $investment_id . "%";
}

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

// Get profits with investment details
$sql = "
    SELECT 
        t.*,
        i.id as investment_id,
        i.amount as investment_amount,
        p.name as plan_name
    FROM transactions t
    LEFT JOIN investments i ON t.description LIKE CONCAT('%investment #', i.id, '%')
    LEFT JOIN investment_plans p ON i.plan_id = p.id
    $where
    ORDER BY t.created_at DESC
    LIMIT $limit OFFSET $offset
";

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

// Get active investments for filter
$investments_sql = "
    SELECT i.id, p.name as plan_name, i.amount 
    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
";

$investments_stmt = $db->prepare($investments_sql);
$investments_stmt->execute([$user_id]);
$active_investments = $investments_stmt->fetchAll();

// Get daily profit trend for chart
$trend_sql = "
    SELECT 
        DATE(created_at) as date,
        COUNT(*) as count,
        SUM(amount) as total_amount
    FROM transactions 
    WHERE user_id = ? AND type = 'profit' AND status = 'completed'
    AND created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
    GROUP BY DATE(created_at)
    ORDER BY date
";

$trend_stmt = $db->prepare($trend_sql);
$trend_stmt->execute([$user_id]);
$profit_trend = $trend_stmt->fetchAll();
?>

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

    <!-- Page Header -->
    <div class="mb-6">
        <h1 class="text-2xl font-bold">Profit History</h1>
        <p class="text-gray-600">Track your daily profits and earnings</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 Profits</p>
                    <h3 class="text-2xl font-bold"><?php echo number_format($stats['total_profits']); ?></h3>
                </div>
                <i class="fas fa-coins text-yellow-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 Profit Amount</p>
                    <h3 class="text-2xl font-bold text-green-600">$<?php echo number_format((float)($stats['total_profit_amount'] ?? 0), 2); ?></h3>
                </div>
                <i class="fas fa-money-bill-wave 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">Avg Daily Profit</p>
                    <h3 class="text-2xl font-bold">$<?php echo number_format((float)($stats['avg_daily_profit'] ?? 0), 2); ?></h3>
                </div>
                <i class="fas fa-chart-line 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">Active Investments Profit</p>
                    <h3 class="text-2xl font-bold text-purple-600">$<?php echo number_format((float)($stats['current_investment_profits'] ?? 0), 2); ?></h3>
                </div>
                <i class="fas fa-chart-pie text-purple-500 text-2xl"></i>
            </div>
        </div>
    </div>

    <!-- Daily Profit Banner -->
    <div class="bg-gradient-to-r from-green-500 to-blue-500 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">Daily Profit Tracker</h3>
                <p class="opacity-90">You've earned <span class="font-bold">$<?php echo number_format((float)($stats['total_profit_amount'] ?? 0), 2); ?></span> in total profits</p>
            </div>
            <div>
                <button onclick="withdrawProfits()" class="bg-white text-green-600 font-bold px-6 py-3 rounded-lg hover:bg-gray-100">
                    <i class="fas fa-hand-holding-usd mr-2"></i>Withdraw Profits
                </button>
            </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-3 gap-4">
                <!-- Date Range -->
                <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>
                
                <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>
                
                <!-- Investment Filter -->
                <div>
                    <label class="block text-gray-700 text-sm mb-2">Investment</label>
                    <select name="investment_id" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                        <option value="">All Investments</option>
                        <?php foreach ($active_investments as $investment): ?>
                        <option value="<?php echo $investment['id']; ?>" <?php echo $investment_id == $investment['id'] ? 'selected' : ''; ?>>
                            #<?php echo $investment['id']; ?> - <?php echo htmlspecialchars($investment['plan_name']); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </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="profits.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_profits); ?> profit records
                </div>
            </div>
        </form>
    </div>

    <!-- Profit Trend Chart -->
    <div class="bg-white rounded-xl shadow p-6 mb-6">
        <h3 class="text-lg font-bold mb-4">30-Day Profit Trend</h3>
        <div class="h-64">
            <canvas id="profitChart"></canvas>
        </div>
    </div>

    <!-- Profits 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">Date</th>
                        <th class="p-4 text-left">Investment</th>
                        <th class="p-4 text-left">Amount</th>
                        <th class="p-4 text-left">Description</th>
                        <th class="p-4 text-left">Reference</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($profits) > 0) { ?>
                        <?php foreach ($profits as $profit) { ?>
                        <tr class="hover:bg-gray-50">
                            <!-- Date -->
                            <td class="p-4">
                                <p><?php echo date('M d, Y', strtotime($profit['created_at'])); ?></p>
                                <p class="text-sm text-gray-500"><?php echo date('H:i', strtotime($profit['created_at'])); ?></p>
                            </td>
                            
                            <!-- Investment -->
                            <td class="p-4">
                                <?php if ($profit['investment_id']): ?>
                                <p class="font-medium">#<?php echo $profit['investment_id']; ?></p>
                                <p class="text-sm text-gray-500"><?php echo htmlspecialchars($profit['plan_name']); ?></p>
                                <?php else: ?>
                                <span class="text-gray-500">N/A</span>
                                <?php endif; ?>
                            </td>
                            
                            <!-- Amount -->
                            <td class="p-4">
                                <p class="font-bold text-green-600">+$<?php echo number_format($profit['amount'], 2); ?></p>
                            </td>
                            
                            <!-- Description -->
                            <td class="p-4">
                                <p class="text-sm"><?php echo htmlspecialchars($profit['description']); ?></p>
                            </td>
                            
                            <!-- Reference -->
                            <td class="p-4">
                                <code class="text-sm bg-gray-100 px-2 py-1 rounded"><?php echo $profit['reference']; ?></code>
                            </td>
                            
                            <!-- Status -->
                            <td class="p-4">
                                <span class="px-3 py-1 rounded-full text-xs font-semibold <?php
                                    echo $profit['status'] == 'completed' ? 'bg-green-100 text-green-800' : 'bg-yellow-100 text-yellow-800';
                                ?>">
                                    <?php echo ucfirst($profit['status']); ?>
                                </span>
                            </td>
                            
                            <!-- Actions -->
                            <td class="p-4">
                                <button onclick="viewProfit(<?php echo $profit['id']; ?>)" 
                                        class="text-blue-600 hover:text-blue-800 text-sm font-medium">
                                    <i class="fas fa-eye mr-1"></i> Details
                                </button>
                                <?php if ($profit['status'] == 'pending'): ?>
                                <button onclick="requestProfit(<?php echo $profit['id']; ?>)" 
                                        class="text-green-600 hover:text-green-800 text-sm font-medium ml-2">
                                    <i class="fas fa-sync mr-1"></i> Request
                                </button>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php } ?>
                    <?php } else { ?>
                        <tr>
                            <td colspan="7" class="p-8 text-center text-gray-500">
                                <i class="fas fa-coins text-4xl mb-4 text-gray-300"></i>
                                <p class="text-lg">No profit records found</p>
                                <p class="text-sm mt-2">Profits will appear here once you start earning from investments</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 } ?>
                </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_profits); ?> of <?php echo number_format($total_profits); ?> profits
                </div>
                <div class="flex space-x-2">
                    <?php if ($page > 1) { ?>
                    <a href="?page=<?php echo $page - 1; ?>&start_date=<?php echo $start_date; ?>&end_date=<?php echo $end_date; ?>&investment_id=<?php echo $investment_id; ?>"
                       class="px-3 py-2 bg-gray-100 rounded-lg hover:bg-gray-200">
                        <i class="fas fa-chevron-left"></i> Previous
                    </a>
                    <?php } ?>
                    
                    <?php
                    $start = max(1, $page - 2);
                    $end = min($total_pages, $start + 4);
                    
                    for ($i = $start; $i <= $end; $i++) {
                    ?>
                    <a href="?page=<?php echo $i; ?>&start_date=<?php echo $start_date; ?>&end_date=<?php echo $end_date; ?>&investment_id=<?php echo $investment_id; ?>"
                       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 } ?>
                    
                    <?php if ($page < $total_pages) { ?>
                    <a href="?page=<?php echo $page + 1; ?>&start_date=<?php echo $start_date; ?>&end_date=<?php echo $end_date; ?>&investment_id=<?php echo $investment_id; ?>"
                       class="px-3 py-2 bg-gray-100 rounded-lg hover:bg-gray-200">
                        Next <i class="fas fa-chevron-right"></i>
                    </a>
                    <?php } ?>
                </div>
            </div>
        </div>
        <?php } ?>
    </div>
    
    <!-- Profit Summary -->
    <div class="mt-6 grid grid-cols-1 lg:grid-cols-3 gap-6">
        <!-- Monthly Breakdown -->
        <div class="bg-white rounded-xl shadow p-6">
            <h3 class="text-lg font-bold mb-4">Monthly Breakdown</h3>
            <?php
            $monthly_sql = "
                SELECT 
                    DATE_FORMAT(created_at, '%Y-%m') as month,
                    COUNT(*) as count,
                    SUM(amount) as total_amount
                FROM transactions 
                WHERE user_id = ? AND type = 'profit' AND status = 'completed'
                GROUP BY DATE_FORMAT(created_at, '%Y-%m')
                ORDER BY month DESC
                LIMIT 6
            ";
            
            $monthly_stmt = $db->prepare($monthly_sql);
            $monthly_stmt->execute([$user_id]);
            $monthly_breakdown = $monthly_stmt->fetchAll();
            ?>
            
            <div class="space-y-3">
                <?php foreach ($monthly_breakdown as $month) { ?>
                <div class="flex justify-between items-center border-b pb-3 last:border-0 last:pb-0">
                    <div>
                        <p class="font-medium"><?php echo date('F Y', strtotime($month['month'] . '-01')); ?></p>
                        <p class="text-sm text-gray-500"><?php echo $month['count']; ?> profits</p>
                    </div>
                    <div class="text-right">
                        <p class="font-bold text-green-600">$<?php echo number_format($month['total_amount'], 2); ?></p>
                    </div>
                </div>
                <?php } ?>
                
                <?php if (empty($monthly_breakdown)) { ?>
                <p class="text-gray-500 text-center py-4">No monthly data available</p>
                <?php } ?>
            </div>
        </div>
        
        <!-- Investment Performance -->
        <div class="bg-white rounded-xl shadow p-6">
            <h3 class="text-lg font-bold mb-4">Top Performing Investments</h3>
            <?php
            $top_investments_sql = "
                SELECT 
                    i.id,
                    p.name as plan_name,
                    i.amount as investment_amount,
                    i.total_profit,
                    (i.total_profit / i.amount * 100) as roi
                FROM investments i
                JOIN investment_plans p ON i.plan_id = p.id
                WHERE i.user_id = ? AND i.status = 'running'
                ORDER BY i.total_profit DESC
                LIMIT 5
            ";
            
            $top_stmt = $db->prepare($top_investments_sql);
            $top_stmt->execute([$user_id]);
            $top_investments = $top_stmt->fetchAll();
            ?>
            
            <div class="space-y-3">
                <?php foreach ($top_investments as $investment) { ?>
                <div class="border rounded-lg p-3">
                    <div class="flex justify-between items-center mb-2">
                        <p class="font-medium">#<?php echo $investment['id']; ?></p>
                        <span class="text-sm font-bold text-green-600"><?php echo number_format((float)($investment['roi'] ?? 0), 1); ?>% ROI</span>
                    </div>
                    <p class="text-sm text-gray-600 mb-1"><?php echo htmlspecialchars($investment['plan_name']); ?></p>
                    <div class="flex justify-between text-sm">
                        <span>Invested: $<?php echo number_format((float)$investment['investment_amount'], 2); ?></span>
                        <span>Profit: $<?php echo number_format((float)$investment['total_profit'], 2); ?></span>
                    </div>
                </div>
                <?php } ?>
                
                <?php if (empty($top_investments)) { ?>
                <p class="text-gray-500 text-center py-4">No active investments</p>
                <?php } ?>
            </div>
        </div>
        
        <!-- Quick Actions -->
        <div class="bg-white rounded-xl shadow p-6">
            <h3 class="text-lg font-bold mb-4">Profit Actions</h3>
            <div class="space-y-3">
                <button onclick="withdrawProfits()" class="w-full bg-green-600 text-white py-3 rounded-lg hover:bg-green-700">
                    <i class="fas fa-hand-holding-usd mr-2"></i>Withdraw All Profits
                </button>
                
                <button onclick="reinvestProfits()" class="w-full bg-blue-600 text-white py-3 rounded-lg hover:bg-blue-700">
                    <i class="fas fa-redo mr-2"></i>Reinvest Profits
                </button>
                
                <button onclick="exportProfitHistory()" class="w-full bg-purple-600 text-white py-3 rounded-lg hover:bg-purple-700">
                    <i class="fas fa-download mr-2"></i>Export History
                </button>
                
                <button onclick="viewProfitForecast()" class="w-full bg-yellow-600 text-white py-3 rounded-lg hover:bg-yellow-700">
                    <i class="fas fa-chart-line mr-2"></i>View Forecast
                </button>
            </div>
        </div>
    </div>

<!-- Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
// Prepare profit trend data
const trendDates = <?php echo json_encode(array_column($profit_trend, 'date')); ?>;
const trendAmounts = <?php echo json_encode(array_column($profit_trend, 'total_amount')); ?>;
const trendCounts = <?php echo json_encode(array_column($profit_trend, 'count')); ?>;

// Format dates for display
const formattedDates = trendDates.map(date => {
    const d = new Date(date);
    return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
});

// Profit Chart
const profitCtx = document.getElementById('profitChart').getContext('2d');
const profitChart = new Chart(profitCtx, {
    type: 'bar',
    data: {
        labels: formattedDates,
        datasets: [
            {
                label: 'Daily Profit Amount',
                data: trendAmounts,
                backgroundColor: 'rgba(34, 197, 94, 0.5)',
                borderColor: 'rgb(34, 197, 94)',
                borderWidth: 1,
                yAxisID: 'y'
            },
            {
                label: 'Number of Profits',
                data: trendCounts,
                type: 'line',
                borderColor: 'rgb(59, 130, 246)',
                backgroundColor: 'rgba(59, 130, 246, 0.1)',
                borderWidth: 2,
                tension: 0.3,
                yAxisID: 'y1'
            }
        ]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        interaction: {
            mode: 'index',
            intersect: false,
        },
        plugins: {
            legend: {
                position: 'top',
            },
            tooltip: {
                callbacks: {
                    label: function(context) {
                        if (context.datasetIndex === 0) {
                            return 'Amount: $' + context.parsed.y.toFixed(2);
                        } else {
                            return 'Count: ' + context.parsed.y;
                        }
                    }
                }
            }
        },
        scales: {
            y: {
                type: 'linear',
                display: true,
                position: 'left',
                title: {
                    display: true,
                    text: 'Amount ($)'
                },
                ticks: {
                    callback: function(value) {
                        return '$' + value.toFixed(2);
                    }
                }
            },
            y1: {
                type: 'linear',
                display: true,
                position: 'right',
                title: {
                    display: true,
                    text: 'Count'
                },
                grid: {
                    drawOnChartArea: false,
                },
            }
        }
    }
});

// Profit functions
function viewProfit(id) {
    $.ajax({
        url: '../api/get-profit.php',
        method: 'GET',
        data: { id: id },
        success: function(response) {
            const profit = JSON.parse(response);
            
            const modalContent = `
                <div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
                    <div class="bg-white rounded-xl shadow-xl w-full max-w-lg">
                        <div class="p-6 border-b">
                            <h3 class="text-xl font-bold">Profit Details</h3>
                        </div>
                        <div class="p-6 space-y-4">
                            <div class="grid grid-cols-2 gap-4">
                                <div>
                                    <p class="text-sm text-gray-600">Amount</p>
                                    <p class="text-2xl font-bold text-green-600">$${parseFloat(profit.amount).toFixed(2)}</p>
                                </div>
                                <div>
                                    <p class="text-sm text-gray-600">Date</p>
                                    <p class="font-bold">${new Date(profit.created_at).toLocaleString()}</p>
                                </div>
                            </div>
                            
                            <div>
                                <p class="text-sm text-gray-600">Reference</p>
                                <p class="font-medium">${profit.reference}</p>
                            </div>
                            
                            <div>
                                <p class="text-sm text-gray-600">Description</p>
                                <p class="font-medium">${profit.description}</p>
                            </div>
                            
                            <div>
                                <p class="text-sm text-gray-600">Status</p>
                                <span class="px-3 py-1 rounded-full text-sm font-semibold ${profit.status === 'completed' ? 'bg-green-100 text-green-800' : 'bg-yellow-100 text-yellow-800'}">
                                    ${profit.status.toUpperCase()}
                                </span>
                            </div>
                            
                            ${profit.investment_id ? `
                            <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
                                <p class="text-sm text-gray-600 mb-1">Related Investment</p>
                                <p class="font-medium">#${profit.investment_id}</p>
                                <a href="investment.php?id=${profit.investment_id}" class="text-blue-600 text-sm hover:text-blue-800">
                                    View Investment Details →
                                </a>
                            </div>
                            ` : ''}
                        </div>
                        <div class="p-6 border-t">
                            <button onclick="closeModal()" class="w-full bg-gray-600 text-white py-2 rounded-lg hover:bg-gray-700">
                                Close
                            </button>
                        </div>
                    </div>
                </div>
            `;
            
            document.body.insertAdjacentHTML('beforeend', modalContent);
        }
    });
}

function closeModal() {
    const modal = document.querySelector('.fixed.inset-0');
    if (modal) modal.remove();
}

function requestProfit(id) {
    if (confirm('Request processing of this profit?')) {
        $.ajax({
            url: '../api/request-profit.php',
            method: 'POST',
            data: { id: id },
            success: function(response) {
                const result = JSON.parse(response);
                alert(result.message);
                if (result.success) {
                    location.reload();
                }
            }
        });
    }
}

function withdrawProfits() {
    // Get available profit balance
    $.ajax({
        url: '../api/get-profit-balance.php',
        method: 'GET',
        success: function(response) {
            const data = JSON.parse(response);
            const availableBalance = parseFloat(data.available_balance);
            
            if (availableBalance <= 0) {
                alert('No profits available for withdrawal');
                return;
            }
            
            const amount = prompt(Enter amount to withdraw (Available: $${availableBalance.toFixed(2)}):, availableBalance.toFixed(2));
            
            if (amount && amount > 0) {
                if (parseFloat(amount) > availableBalance) {
                    alert('Amount exceeds available profit balance');
                    return;
                }
                
                window.location.href = withdrawal.php?amount=${amount}&source=profit;
            }
        }
    });
}

function reinvestProfits() {
    if (confirm('Reinvest all available profits into new investments?')) {
        $.ajax({
            url: '../api/reinvest-profits.php',
            method: 'POST',
            success: function(response) {
                const result = JSON.parse(response);
                alert(result.message);
                if (result.success) {
                    location.reload();
                }
            }
        });
    }
}

function exportProfitHistory() {
    const params = new URLSearchParams(window.location.search);
    window.open(../api/export-profits.php?${params.toString()}, '_blank');
}

function viewProfitForecast() {
    $.ajax({
        url: '../api/get-profit-forecast.php',
        method: 'GET',
        success: function(response) {
            const forecast = JSON.parse(response);
            
            const modalContent = `
                <div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
                    <div class="bg-white rounded-xl shadow-xl w-full max-w-lg">
                        <div class="p-6 border-b">
                            <h3 class="text-xl font-bold">Profit Forecast</h3>
                        </div>
                        <div class="p-6 space-y-4">
                            <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
                                <p class="text-sm text-gray-600 mb-2">Next 30 Days Forecast</p>
                                <p class="text-2xl font-bold text-green-600">$${parseFloat(forecast.next_30_days).toFixed(2)}</p>
                            </div>
                            
                            <div class="grid grid-cols-2 gap-4">
                                <div>
                                    <p class="text-sm text-gray-600">Daily Average</p>
                                    <p class="font-bold">$${parseFloat(forecast.daily_average).toFixed(2)}</p>
                                </div>
                                <div>
                                    <p class="text-sm text-gray-600">Weekly Forecast</p>
                                    <p class="font-bold">$${parseFloat(forecast.weekly_forecast).toFixed(2)}</p>
                                </div>
                            </div>
                            
                            <div>
                                <p class="text-sm text-gray-600 mb-2">Active Investments</p>
                                <ul class="space-y-2">
                                    ${forecast.investments.map(inv => `
                                        <li class="flex justify-between items-center border-b pb-2 last:border-0">
                                            <span class="text-sm">${inv.plan_name}</span>
                                            <span class="font-bold text-green-600">$${parseFloat(inv.daily_profit).toFixed(2)}/day</span>
                                        </li>
                                    `).join('')}
                                </ul>
                            </div>
                        </div>
                        <div class="p-6 border-t">
                            <button onclick="closeModal()" class="w-full bg-gray-600 text-white py-2 rounded-lg hover:bg-gray-700">
                                Close
                            </button>
                        </div>
                    </div>
                </div>
            `;
            
            document.body.insertAdjacentHTML('beforeend', modalContent);
        }
    });
}

// Auto-refresh for new profits
setTimeout(() => {
    location.reload();
}, 60000); // Refresh every minute
</script>

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