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

$format = isset($_GET['format']) ? $_GET['format'] : 'pdf';
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : date('Y-m-01');
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : date('Y-m-t');

// Include the same functions from financial_summary.php
include('includes/functions.php');

// Get financial data
function getFinancialSummary($conn, $date_from, $date_to) {
    // Same function as in financial_summary.php
    $summary = array();
    
    $sql = "SELECT COALESCE(SUM(subscription_fee), 0) as total FROM user_bot_subscriptions 
            WHERE subscription_start BETWEEN '$date_from' AND '$date_to' AND status = 'active'";
    $result = mysqli_query($conn, $sql);
    $row = mysqli_fetch_assoc($result);
    $summary['subscription_revenue'] = $row['total'];
    
    $sql = "SELECT COALESCE(SUM(amount), 0) as total FROM deposits 
            WHERE created_at BETWEEN '$date_from' AND '$date_to' AND status = 'confirmed'";
    $result = mysqli_query($conn, $sql);
    $row = mysqli_fetch_assoc($result);
    $summary['deposit_revenue'] = $row['total'];
    
    $summary['total_revenue'] = $summary['subscription_revenue'] + $summary['deposit_revenue'];
    
    $sql = "SELECT COALESCE(SUM(amount), 0) as total FROM withdrawals 
            WHERE created_at BETWEEN '$date_from' AND '$date_to' AND status = 'completed'";
    $result = mysqli_query($conn, $sql);
    $row = mysqli_fetch_assoc($result);
    $summary['withdrawal_expenses'] = $row['total'];
    
    $sql = "SELECT COALESCE(SUM(fee), 0) as total FROM withdrawals 
            WHERE created_at BETWEEN '$date_from' AND '$date_to' AND status = 'completed'";
    $result = mysqli_query($conn, $sql);
    $row = mysqli_fetch_assoc($result);
    $summary['fee_income'] = $row['total'];
    
    $sql = "SELECT COALESCE(SUM(amount), 0) as total FROM transactions 
            WHERE type = 'profit' AND status = 'completed' 
            AND DATE(date) BETWEEN '$date_from' AND '$date_to'";
    $result = mysqli_query($conn, $sql);
    $row = mysqli_fetch_assoc($result);
    $summary['trading_profit'] = $row['total'];
    
    $summary['net_profit'] = $summary['total_revenue'] + $summary['fee_income'] + $summary['trading_profit'] - $summary['withdrawal_expenses'];
    
    return $summary;
}

$financial_data = getFinancialSummary($conn, $date_from, $date_to);

function format_money($amount) {
    return '$' . number_format($amount, 2);
}

if ($format == 'pdf') {
    // Simple HTML to PDF
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="financial_report_' . date('Y-m-d') . '.pdf"');
    
    $html = '<!DOCTYPE html>
    <html>
    <head>
        <title>Financial Report</title>
        <style>
            body { font-family: Arial, sans-serif; }
            h1 { color: #333; }
            table { width: 100%; border-collapse: collapse; margin-bottom: 20px; }
            th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
            th { background-color: #f2f2f2; }
            .summary { background-color: #f9f9f9; padding: 15px; margin-bottom: 20px; }
            .positive { color: green; }
            .negative { color: red; }
        </style>
    </head>
    <body>
        <h1>Financial Report</h1>
        <p>Period: ' . date('M d, Y', strtotime($date_from)) . ' to ' . date('M d, Y', strtotime($date_to)) . '</p>
        <p>Generated: ' . date('F d, Y H:i:s') . '</p>
        
        <div class="summary">
            <h2>Financial Summary</h2>
            <table>
                <tr>
                    <td><strong>Total Revenue:</strong></td>
                    <td>' . format_money($financial_data['total_revenue']) . '</td>
                </tr>
                <tr>
                    <td><strong>Subscription Revenue:</strong></td>
                    <td>' . format_money($financial_data['subscription_revenue']) . '</td>
                </tr>
                <tr>
                    <td><strong>Deposit Revenue:</strong></td>
                    <td>' . format_money($financial_data['deposit_revenue']) . '</td>
                </tr>
                <tr>
                    <td><strong>Withdrawal Expenses:</strong></td>
                    <td>' . format_money($financial_data['withdrawal_expenses']) . '</td>
                </tr>
                <tr>
                    <td><strong>Fee Income:</strong></td>
                    <td>' . format_money($financial_data['fee_income']) . '</td>
                </tr>
                <tr>
                    <td><strong>Trading Profit:</strong></td>
                    <td>' . format_money($financial_data['trading_profit']) . '</td>
                </tr>
                <tr>
                    <td><strong>Net Profit:</strong></td>
                    <td class="' . ($financial_data['net_profit'] >= 0 ? 'positive' : 'negative') . '">
                        ' . format_money($financial_data['net_profit']) . '
                    </td>
                </tr>
            </table>
        </div>
        
        <h2>Profit Margin Analysis</h2>
        <table>
            <tr>
                <th>Metric</th>
                <th>Value</th>
            </tr>';
    
    $profit_margin = $financial_data['total_revenue'] > 0 ? ($financial_data['net_profit'] / $financial_data['total_revenue']) * 100 : 0;
    
    $html .= '
            <tr>
                <td>Profit Margin</td>
                <td>' . number_format($profit_margin, 2) . '%</td>
            </tr>
            <tr>
                <td>Revenue Per Day</td>
                <td>' . format_money($financial_data['total_revenue'] / max(1, (strtotime($date_to) - strtotime($date_from)) / (60*60*24))) . '</td>
            </tr>
            <tr>
                <td>Profit Per Day</td>
                <td>' . format_money($financial_data['net_profit'] / max(1, (strtotime($date_to) - strtotime($date_from)) / (60*60*24))) . '</td>
            </tr>
        </table>
        
        <p style="margin-top: 30px; font-size: 12px; color: #666;">
            Report generated by AI Trading Platform Admin Panel
        </p>
    </body>
    </html>';
    
    echo $html;
    
} elseif ($format == 'excel') {
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment; filename="financial_report_' . date('Y-m-d') . '.xls"');
    
    echo '<table border="1">
        <tr>
            <th colspan="2">Financial Report</th>
        </tr>
        <tr>
            <td colspan="2">Period: ' . date('M d, Y', strtotime($date_from)) . ' to ' . date('M d, Y', strtotime($date_to)) . '</td>
        </tr>
        <tr>
            <td colspan="2">Generated: ' . date('F d, Y H:i:s') . '</td>
        </tr>
        <tr>
            <td colspan="2">&nbsp;</td>
        </tr>
        <tr>
            <th>Metric</th>
            <th>Amount</th>
        </tr>
        <tr>
            <td>Total Revenue</td>
            <td>' . format_money($financial_data['total_revenue']) . '</td>
        </tr>
        <tr>
            <td>Subscription Revenue</td>
            <td>' . format_money($financial_data['subscription_revenue']) . '</td>
        </tr>
        <tr>
            <td>Deposit Revenue</td>
            <td>' . format_money($financial_data['deposit_revenue']) . '</td>
        </tr>
        <tr>
            <td>Withdrawal Expenses</td>
            <td>' . format_money($financial_data['withdrawal_expenses']) . '</td>
        </tr>
        <tr>
            <td>Fee Income</td>
            <td>' . format_money($financial_data['fee_income']) . '</td>
        </tr>
        <tr>
            <td>Trading Profit</td>
            <td>' . format_money($financial_data['trading_profit']) . '</td>
        </tr>
        <tr>
            <td><strong>Net Profit</strong></td>
            <td><strong>' . format_money($financial_data['net_profit']) . '</strong></td>
        </tr>
        <tr>
            <td>Profit Margin</td>
            <td>' . number_format(($financial_data['total_revenue'] > 0 ? ($financial_data['net_profit'] / $financial_data['total_revenue']) * 100 : 0), 2) . '%</td>
        </tr>
    </table>';
    
} elseif ($format == 'csv') {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="financial_report_' . date('Y-m-d') . '.csv"');
    
    $output = fopen('php://output', 'w');
    
    fputcsv($output, array('Financial Report'));
    fputcsv($output, array('Period:', date('M d, Y', strtotime($date_from)) . ' to ' . date('M d, Y', strtotime($date_to))));
    fputcsv($output, array('Generated:', date('F d, Y H:i:s')));
    fputcsv($output, array(''));
    fputcsv($output, array('Metric', 'Amount'));
    fputcsv($output, array('Total Revenue', format_money($financial_data['total_revenue'])));
    fputcsv($output, array('Subscription Revenue', format_money($financial_data['subscription_revenue'])));
    fputcsv($output, array('Deposit Revenue', format_money($financial_data['deposit_revenue'])));
    fputcsv($output, array('Withdrawal Expenses', format_money($financial_data['withdrawal_expenses'])));
    fputcsv($output, array('Fee Income', format_money($financial_data['fee_income'])));
    fputcsv($output, array('Trading Profit', format_money($financial_data['trading_profit'])));
    fputcsv($output, array('Net Profit', format_money($financial_data['net_profit'])));
    fputcsv($output, array('Profit Margin', number_format(($financial_data['total_revenue'] > 0 ? ($financial_data['net_profit'] / $financial_data['total_revenue']) * 100 : 0), 2) . '%'));
    
    fclose($output);
}
?>