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

// Check admin access
if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit();
}

// Get parameters
$format = isset($_GET['format']) ? $_GET['format'] : 'csv';
$start_date = isset($_GET['start_date']) ? $_GET['start_date'] : date('Y-m-01');
$end_date = isset($_GET['end_date']) ? $_GET['end_date'] : 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;

// Get report data
$report_sql = "SELECT 
    DATE(t.date) as trade_date,
    u.username,
    p.plan_name,
    t.type,
    t.amount,
    t.description,
    t.created_at
    FROM transactions t
    LEFT JOIN users u ON t.user_id = u.id
    LEFT JOIN user_bot_subscriptions s ON t.related_id = s.id AND t.related_type = 'subscription'
    LEFT JOIN trading_bot_plans p ON s.bot_plan_id = p.id
    WHERE t.type IN ('profit', 'loss')
    AND t.status = 'completed'
    AND DATE(t.date) BETWEEN '$start_date' AND '$end_date'";

if ($bot_plan > 0) {
    $report_sql .= " AND s.bot_plan_id = $bot_plan";
}
if ($user_id > 0) {
    $report_sql .= " AND t.user_id = $user_id";
}

$report_sql .= " ORDER BY t.date DESC";
$result = mysqli_query($conn, $report_sql);

if ($format == 'csv') {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="trading_report_' . date('Y-m-d') . '.csv"');
    
    $output = fopen('php://output', 'w');
    
    // Add headers
    fputcsv($output, array('Date', 'Username', 'Bot Plan', 'Type', 'Amount ($)', 'Description', 'Time'));
    
    // Add data
    while ($row = mysqli_fetch_assoc($result)) {
        fputcsv($output, array(
            $row['trade_date'],
            $row['username'],
            $row['plan_name'],
            $row['type'],
            $row['amount'],
            $row['description'],
            date('H:i:s', strtotime($row['created_at']))
        ));
    }
    
    fclose($output);
    
} elseif ($format == 'excel') {
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment; filename="trading_report_' . date('Y-m-d') . '.xls"');
    
    echo '<table border="1">';
    echo '<tr>';
    echo '<th>Date</th>';
    echo '<th>Username</th>';
    echo '<th>Bot Plan</th>';
    echo '<th>Type</th>';
    echo '<th>Amount ($)</th>';
    echo '<th>Description</th>';
    echo '<th>Time</th>';
    echo '</tr>';
    
    while ($row = mysqli_fetch_assoc($result)) {
        echo '<tr>';
        echo '<td>' . $row['trade_date'] . '</td>';
        echo '<td>' . $row['username'] . '</td>';
        echo '<td>' . $row['plan_name'] . '</td>';
        echo '<td>' . $row['type'] . '</td>';
        echo '<td>' . $row['amount'] . '</td>';
        echo '<td>' . $row['description'] . '</td>';
        echo '<td>' . date('H:i:s', strtotime($row['created_at'])) . '</td>';
        echo '</tr>';
    }
    
    echo '</table>';
    
} elseif ($format == 'pdf') {
    // For PDF, you would need a library like TCPDF
    // This is a simplified version
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="trading_report_' . date('Y-m-d') . '.pdf"');
    
    $html = '<h1>Trading Report</h1>';
    $html .= '<p>Period: ' . $start_date . ' to ' . $end_date . '</p>';
    $html .= '<p>Generated: ' . date('Y-m-d H:i:s') . '</p>';
    $html .= '<table border="1" cellpadding="5" cellspacing="0">';
    $html .= '<tr>';
    $html .= '<th>Date</th>';
    $html .= '<th>Username</th>';
    $html .= '<th>Type</th>';
    $html .= '<th>Amount ($)</th>';
    $html .= '</tr>';
    
    $total_profit = 0;
    $total_loss = 0;
    
    mysqli_data_seek($result, 0); // Reset result pointer
    
    while ($row = mysqli_fetch_assoc($result)) {
        $html .= '<tr>';
        $html .= '<td>' . $row['trade_date'] . '</td>';
        $html .= '<td>' . $row['username'] . '</td>';
        $html .= '<td>' . $row['type'] . '</td>';
        $html .= '<td>$' . $row['amount'] . '</td>';
        $html .= '</tr>';
        
        if ($row['type'] == 'profit') {
            $total_profit += $row['amount'];
        } else {
            $total_loss += $row['amount'];
        }
    }
    
    $html .= '</table>';
    $html .= '<h3>Summary</h3>';
    $html .= '<p>Total Profit: $' . number_format($total_profit, 2) . '</p>';
    $html .= '<p>Total Loss: $' . number_format($total_loss, 2) . '</p>';
    $html .= '<p>Net P/L: $' . number_format($total_profit - $total_loss, 2) . '</p>';
    
    echo $html;
}
?>