<?php
session_start();
include('includes/config.php');

// Get filter parameters
$format = isset($_GET['format']) ? $_GET['format'] : 'csv';
$period = isset($_GET['period']) ? $_GET['period'] : 'today';
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : date('Y-m-d');
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : date('Y-m-d');
$bot_plan = isset($_GET['bot_plan']) ? intval($_GET['bot_plan']) : 0;
$user_id = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;

// Build query for profit data (same as profit_loss.php)
$profit_sql = "SELECT 
                DATE(t.date) as transaction_date,
                COUNT(t.id) as total_transactions,
                SUM(CASE WHEN t.type = 'profit' THEN t.amount ELSE 0 END) as total_profit,
                SUM(CASE WHEN t.type = 'loss' THEN t.amount ELSE 0 END) as total_loss,
                SUM(CASE WHEN t.type = 'fee' THEN t.amount ELSE 0 END) as total_fees,
                (SUM(CASE WHEN t.type = 'profit' THEN t.amount ELSE 0 END) - 
                 SUM(CASE WHEN t.type = 'loss' THEN t.amount ELSE 0 END) - 
                 SUM(CASE WHEN t.type = 'fee' THEN t.amount ELSE 0 END)) as net_profit
               FROM transactions t
               WHERE t.status = 'completed' 
                 AND t.type IN ('profit', 'loss', 'fee')
                 AND DATE(t.date) BETWEEN '$date_from' AND '$date_to'";

if ($user_id > 0) {
    $profit_sql .= " AND t.user_id = $user_id";
}

if ($bot_plan > 0) {
    $profit_sql .= " AND t.related_id IN (SELECT id FROM user_bot_subscriptions WHERE bot_plan_id = $bot_plan) 
                     AND t.related_type = 'bot_transaction'";
}

$profit_sql .= " GROUP BY DATE(t.date) ORDER BY transaction_date DESC";

$result = mysqli_query($conn, $profit_sql);

if ($format == 'csv') {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="profit_loss_' . date('Y-m-d') . '.csv"');
    
    $output = fopen('php://output', 'w');
    
    // Add headers
    fputcsv($output, array('Date', 'Total Trades', 'Total Profit', 'Total Loss', 'Total Fees', 'Net Profit', 'Profit/Loss Ratio', 'Win Rate %'));
    
    // Add data
    while ($row = mysqli_fetch_assoc($result)) {
        $pl_ratio = ($row['total_loss'] > 0) ? ($row['total_profit'] / $row['total_loss']) : ($row['total_profit'] > 0 ? '∞' : 0);
        $win_rate = ($row['total_profit'] + $row['total_loss'] > 0) ? 
                    round(($row['total_profit'] / ($row['total_profit'] + $row['total_loss'])) * 100, 2) : 0;
        
        fputcsv($output, array(
            date('Y-m-d', strtotime($row['transaction_date'])),
            $row['total_transactions'],
            number_format($row['total_profit'], 2),
            number_format($row['total_loss'], 2),
            number_format($row['total_fees'], 2),
            number_format($row['net_profit'], 2),
            is_numeric($pl_ratio) ? number_format($pl_ratio, 2) . ':1' : $pl_ratio,
            $win_rate
        ));
    }
    
    fclose($output);
    
} elseif ($format == 'excel') {
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment; filename="profit_loss_' . date('Y-m-d') . '.xls"');
    
    echo '<table border="1">';
    echo '<tr>';
    echo '<th>Date</th>';
    echo '<th>Total Trades</th>';
    echo '<th>Total Profit</th>';
    echo '<th>Total Loss</th>';
    echo '<th>Total Fees</th>';
    echo '<th>Net Profit</th>';
    echo '<th>Profit/Loss Ratio</th>';
    echo '<th>Win Rate %</th>';
    echo '</tr>';
    
    while ($row = mysqli_fetch_assoc($result)) {
        $pl_ratio = ($row['total_loss'] > 0) ? ($row['total_profit'] / $row['total_loss']) : ($row['total_profit'] > 0 ? '∞' : 0);
        $win_rate = ($row['total_profit'] + $row['total_loss'] > 0) ? 
                    round(($row['total_profit'] / ($row['total_profit'] + $row['total_loss'])) * 100, 2) : 0;
        
        echo '<tr>';
        echo '<td>' . date('Y-m-d', strtotime($row['transaction_date'])) . '</td>';
        echo '<td>' . $row['total_transactions'] . '</td>';
        echo '<td>$' . number_format($row['total_profit'], 2) . '</td>';
        echo '<td>$' . number_format($row['total_loss'], 2) . '</td>';
        echo '<td>$' . number_format($row['total_fees'], 2) . '</td>';
        echo '<td>$' . number_format($row['net_profit'], 2) . '</td>';
        echo '<td>' . (is_numeric($pl_ratio) ? number_format($pl_ratio, 2) . ':1' : $pl_ratio) . '</td>';
        echo '<td>' . $win_rate . '%</td>';
        echo '</tr>';
    }
    
    echo '</table>';
    
} elseif ($format == 'pdf') {
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="profit_loss_' . date('Y-m-d') . '.pdf"');
    
    $html = '<h1>Profit & Loss Report</h1>';
    $html .= '<p><strong>Period:</strong> ' . date('F d, Y', strtotime($date_from)) . ' to ' . date('F d, Y', strtotime($date_to)) . '</p>';
    $html .= '<p><strong>Generated:</strong> ' . date('Y-m-d H:i:s') . '</p>';
    $html .= '<table border="1" cellpadding="5" cellspacing="0">';
    $html .= '<tr>';
    $html .= '<th>Date</th>';
    $html .= '<th>Total Trades</th>';
    $html .= '<th>Total Profit</th>';
    $html .= '<th>Total Loss</th>';
    $html .= '<th>Net Profit</th>';
    $html .= '</tr>';
    
    $total_trades = 0;
    $total_profit = 0;
    $total_loss = 0;
    $total_net = 0;
    
    while ($row = mysqli_fetch_assoc($result)) {
        $html .= '<tr>';
        $html .= '<td>' . date('Y-m-d', strtotime($row['transaction_date'])) . '</td>';
        $html .= '<td>' . $row['total_transactions'] . '</td>';
        $html .= '<td>$' . number_format($row['total_profit'], 2) . '</td>';
        $html .= '<td>$' . number_format($row['total_loss'], 2) . '</td>';
        $html .= '<td>$' . number_format($row['net_profit'], 2) . '</td>';
        $html .= '</tr>';
        
        $total_trades += $row['total_transactions'];
        $total_profit += $row['total_profit'];
        $total_loss += $row['total_loss'];
        $total_net += $row['net_profit'];
    }
    
    // Add totals row
    $html .= '<tr style="font-weight: bold; background-color: #f0f0f0;">';
    $html .= '<td>TOTAL</td>';
    $html .= '<td>' . $total_trades . '</td>';
    $html .= '<td>$' . number_format($total_profit, 2) . '</td>';
    $html .= '<td>$' . number_format($total_loss, 2) . '</td>';
    $html .= '<td>$' . number_format($total_net, 2) . '</td>';
    $html .= '</tr>';
    
    $html .= '</table>';
    
    // Add summary
    $html .= '<div style="margin-top: 20px;">';
    $html .= '<h3>Summary</h3>';
    $html .= '<p><strong>Profit Margin:</strong> ' . ($total_profit > 0 ? number_format(($total_net / $total_profit) * 100, 2) : 0) . '%</p>';
    $html .= '<p><strong>Win Rate:</strong> ' . ($total_profit + $total_loss > 0 ? 
              number_format(($total_profit / ($total_profit + $total_loss)) * 100, 2) : 0) . '%</p>';
    $html .= '<p><strong>Average Daily Profit:</strong> $' . number_format($total_net / max(mysqli_num_rows($result), 1), 2) . '</p>';
    $html .= '</div>';
    
    echo $html;
}
?>