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

$format = isset($_GET['format']) ? $_GET['format'] : 'csv';
$start_date = isset($_GET['start_date']) ? $_GET['start_date'] : date('Y-m-d', strtotime('-30 days'));
$end_date = isset($_GET['end_date']) ? $_GET['end_date'] : date('Y-m-d');
$include_stats = isset($_GET['include_stats']) ? intval($_GET['include_stats']) : 1;
$include_details = isset($_GET['include_details']) ? intval($_GET['include_details']) : 1;
$notify_admin = isset($_GET['notify']) ? intval($_GET['notify']) : 0; // New parameter for notification

// Get admin details for notification
$admin_id = $_SESSION['user_id'] ?? 1;
$adminQuery = mysqli_query($conn, "SELECT first_name, email FROM users WHERE id='$admin_id'");
$adminData = mysqli_fetch_assoc($adminQuery);
$admin_name = $adminData['first_name'] ?? 'System Administrator';

// Get performance data
$sql = "SELECT s.*, p.plan_name, p.daily_roi_percentage, 
               u.username, u.email,
               (s.total_profit / s.trading_balance * 100) as roi_percentage
        FROM user_bot_subscriptions s
        LEFT JOIN trading_bot_plans p ON s.bot_plan_id = p.id
        LEFT JOIN users u ON s.user_id = u.id
        WHERE s.subscription_start BETWEEN '$start_date' AND '$end_date'
        ORDER BY s.created_at DESC";

$result = mysqli_query($conn, $sql);
$total_rows = mysqli_num_rows($result);

// Get stats for notification
$stats_sql = "SELECT 
                COUNT(*) as total_bots,
                SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) as active_bots,
                SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) as cancelled_bots,
                SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending_bots,
                SUM(total_profit) as total_profit,
                AVG(success_rate) as avg_success_rate,
                SUM(trading_balance) as total_trading_balance
              FROM user_bot_subscriptions
              WHERE subscription_start BETWEEN '$start_date' AND '$end_date'";
$stats_result = mysqli_query($conn, $stats_sql);
$stats = mysqli_fetch_assoc($stats_result);

// Generate the report file
if ($format == 'csv') {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="bot_performance_' . date('Y-m-d') . '.csv"');
    
    $output = fopen('php://output', 'w');
    
    // Add headers
    fputcsv($output, array('Bot ID', 'User', 'Plan', 'Status', 'Trading Balance', 'Total Profit', 'Success Rate', 'ROI %', 'Start Date', 'End Date'));
    
    // Add data
    while ($row = mysqli_fetch_assoc($result)) {
        $roi = $row['trading_balance'] > 0 ? ($row['total_profit'] / $row['trading_balance']) * 100 : 0;
        
        fputcsv($output, array(
            $row['id'],
            $row['username'],
            $row['plan_name'],
            $row['status'],
            $row['trading_balance'],
            $row['total_profit'],
            $row['success_rate'],
            number_format($roi, 2),
            $row['subscription_start'],
            $row['subscription_end']
        ));
    }
    
    fclose($output);
    
} elseif ($format == 'excel') {
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment; filename="bot_performance_' . date('Y-m-d') . '.xls"');
    
    echo '<table border="1">';
    echo '<tr>';
    echo '<th>Bot ID</th>';
    echo '<th>User</th>';
    echo '<th>Plan</th>';
    echo '<th>Status</th>';
    echo '<th>Trading Balance</th>';
    echo '<th>Total Profit</th>';
    echo '<th>Success Rate</th>';
    echo '<th>ROI %</th>';
    echo '<th>Start Date</th>';
    echo '<th>End Date</th>';
    echo '</tr>';
    
    while ($row = mysqli_fetch_assoc($result)) {
        $roi = $row['trading_balance'] > 0 ? ($row['total_profit'] / $row['trading_balance']) * 100 : 0;
        
        echo '<tr>';
        echo '<td>' . $row['id'] . '</td>';
        echo '<td>' . $row['username'] . '</td>';
        echo '<td>' . $row['plan_name'] . '</td>';
        echo '<td>' . $row['status'] . '</td>';
        echo '<td>' . $row['trading_balance'] . '</td>';
        echo '<td>' . $row['total_profit'] . '</td>';
        echo '<td>' . $row['success_rate'] . '</td>';
        echo '<td>' . number_format($roi, 2) . '</td>';
        echo '<td>' . $row['subscription_start'] . '</td>';
        echo '<td>' . $row['subscription_end'] . '</td>';
        echo '</tr>';
    }
    
    echo '</table>';
    
} elseif ($format == 'pdf') {
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="bot_performance_' . date('Y-m-d') . '.pdf"');
    
    // Simple HTML that can be converted to PDF
    $html = '<h1>Bot Performance Report</h1>';
    $html .= '<p>Date Range: ' . $start_date . ' to ' . $end_date . '</p>';
    $html .= '<p>Generated on: ' . date('Y-m-d H:i:s') . '</p>';
    
    if ($include_stats) {
        $html .= '<h3>Performance Summary</h3>';
        $html .= '<table border="1" cellpadding="5" cellspacing="0">';
        $html .= '<tr><th>Total Bots</th><th>Total Profit</th><th>Average Success Rate</th></tr>';
        $html .= '<tr>';
        $html .= '<td>' . $stats['total_bots'] . '</td>';
        $html .= '<td>$' . number_format($stats['total_profit'], 2) . '</td>';
        $html .= '<td>' . number_format($stats['avg_success_rate'], 1) . '%</td>';
        $html .= '</tr>';
        $html .= '</table>';
    }
    
    if ($include_details) {
        $html .= '<h3>Bot Performance Details</h3>';
        $html .= '<table border="1" cellpadding="5" cellspacing="0">';
        $html .= '<tr>';
        $html .= '<th>Bot ID</th>';
        $html .= '<th>User</th>';
        $html .= '<th>Plan</th>';
        $html .= '<th>Status</th>';
        $html .= '<th>Profit</th>';
        $html .= '<th>Success Rate</th>';
        $html .= '</tr>';
        
        mysqli_data_seek($result, 0); // Reset pointer
        while ($row = mysqli_fetch_assoc($result)) {
            $html .= '<tr>';
            $html .= '<td>' . $row['id'] . '</td>';
            $html .= '<td>' . $row['username'] . '</td>';
            $html .= '<td>' . $row['plan_name'] . '</td>';
            $html .= '<td>' . $row['status'] . '</td>';
            $html .= '<td>$' . number_format($row['total_profit'], 2) . '</td>';
            $html .= '<td>' . number_format($row['success_rate'], 1) . '%</td>';
            $html .= '</tr>';
        }
        
        $html .= '</table>';
    }
    
    echo $html;
}

// Send notification if requested
if ($notify_admin && $adminData['email']) {
    // Log report generation
    logAdminActivity(
        'Performance Report Generated',
        "Generated bot performance report in $format format for period $start_date to $end_date ($total_rows records)",
        'Reports',
        0,
        'user_bot_subscriptions'
    );
    
    // NOTIFICATION: Performance Report Generated (ADMIN)
    $mail_subject = "Bot Performance Report Generated";
    $mail_message = "<!-- Content Section -->
                    <div class='email-content'>
                        <h2 class='greeting'>Performance Report Generated</h2>
                        
                        <p class='message'>
                            A bot performance report has been successfully generated and is ready for download.
                        </p>

                        <!-- Report Details -->
                        <div class='details-section'>
                            <div class='detail-box'>
                                <strong>Report Type:</strong> Bot Performance Analysis<br>
                                <strong>Format:</strong> " . strtoupper($format) . "<br>
                                <strong>Date Range:</strong> " . $start_date . " to " . $end_date . "<br>
                                <strong>Generated By:</strong> " . $admin_name . " (ID: " . $admin_id . ")<br>
                                <strong>Generation Time:</strong> " . date('F j, Y g:i A') . "<br>
                                <strong>File Name:</strong> bot_performance_" . date('Y-m-d') . "." . $format . "<br>
                                <strong>Total Records:</strong> " . $total_rows . " bot subscriptions<br>
                                <strong>Status:</strong> <span style='color: #28a745; font-weight: bold;'>SUCCESSFULLY GENERATED</span>
                            </div>
                        </div>

                        <!-- Performance Summary -->
                        <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #0056b3;'>📊 Report Summary</h4>
                            <p style='color: #0056b3;'>
                                <strong>Total Bots:</strong> " . $stats['total_bots'] . " (Active: " . $stats['active_bots'] . ", Cancelled: " . $stats['cancelled_bots'] . ", Pending: " . $stats['pending_bots'] . ")<br>
                                <strong>Total Trading Balance:</strong> $" . number_format($stats['total_trading_balance'], 2) . "<br>
                                <strong>Total Profit Generated:</strong> <span style='color: " . ($stats['total_profit'] >= 0 ? '#28a745' : '#dc3545') . ";'>$" . number_format($stats['total_profit'], 2) . "</span><br>
                                <strong>Average Success Rate:</strong> " . number_format($stats['avg_success_rate'], 1) . "%<br>
                                <strong>Time Period:</strong> " . round((strtotime($end_date) - strtotime($start_date)) / (60 * 60 * 24)) . " days
                            </p>
                        </div>

                        <!-- Report Contents -->
                        <div class='next-steps'>
                            <h3 style='color: #2c3e50;'>📋 Report Contents</h3>
                            <p style='color: #6c757d;'>The generated report includes:</p>
                            <ul style='color: #6c757d;'>
                                <li>Bot subscription details (ID, user, plan)</li>
                                <li>Current status and trading balance</li>
                                <li>Total profit and success rate</li>
                                <li>ROI percentage calculations</li>
                                <li>Subscription dates</li>
                                " . ($include_stats ? "<li>Performance summary statistics</li>" : "") . "
                                " . ($include_details ? "<li>Detailed bot-by-bot breakdown</li>" : "") . "
                            </ul>
                        </div>

                        <!-- Usage Recommendations -->
                        <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #856404;'>💡 Report Usage</h4>
                            <p style='color: #856404;'>
                                <strong>This report can be used for:</strong><br>
                                • Performance analysis and trend identification<br>
                                • Investment strategy optimization<br>
                                • User engagement assessment<br>
                                • Revenue forecasting<br>
                                • Compliance and audit requirements<br>
                                • Business intelligence and decision making
                            </p>
                        </div>

                        <!-- Action Buttons -->
                        <div style='text-align: center; margin: 30px 0;'>
                            <a href='" . $myUrl . "/admin/reports.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #198754; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                Generate Another Report
                            </a>
                            <a href='" . $myUrl . "/admin/analytics.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #0dcaf0; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                View Analytics Dashboard
                            </a>
                        </div>

                        <!-- Data Security -->
                        <div style='background: #d1ecf1; border: 1px solid #bee5eb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #0c5460;'>🔒 Data Security Note</h4>
                            <p style='color: #0c5460;'>
                                <strong>Confidential Information:</strong> This report contains sensitive trading data.<br>
                                <strong>Recommended Actions:</strong><br>
                                • Store report securely with appropriate access controls<br>
                                • Share only with authorized personnel<br>
                                • Delete or archive reports according to data retention policy<br>
                                • Consider encryption for highly sensitive data
                            </p>
                        </div>

                        <!-- System Information -->
                        <div class='support-section'>
                            <p class='support-text'>System Information:</p>
                            <p style='color: #6c757d; font-size: 12px;'>
                                <strong>Generation Method:</strong> Automated Report System<br>
                                <strong>Data Source:</strong> user_bot_subscriptions table<br>
                                <strong>Memory Usage:</strong> " . round(memory_get_peak_usage() / 1024 / 1024, 2) . " MB<br>
                                <strong>Execution Time:</strong> " . round(microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'], 2) . " seconds
                            </p>
                        </div>
                    </div>";

    // Send admin notification
    require_once("../proccess/admin_mailer.php");
}

// Note: The report download happens above, notification is sent after headers are sent
?>