<?php
session_start();
require_once '../connection.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

// Get user ID
$user_id = $_SESSION['user_id'];

// Get export format (default to CSV)
$format = isset($_GET['format']) ? $_GET['format'] : 'csv';
$valid_formats = ['csv', 'excel', 'pdf'];

if (!in_array($format, $valid_formats)) {
    $format = 'csv';
}

// Get filter parameters (same as statement.php)
$filter_type = isset($_GET['type']) ? $_GET['type'] : '';
$filter_status = isset($_GET['status']) ? $_GET['status'] : '';
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : '';

// Build query conditions
$where_conditions = ["user_id = ?"];
$params = [$user_id];
$types = "i";

if (!empty($filter_type)) {
    $where_conditions[] = "type = ?";
    $params[] = $filter_type;
    $types .= "s";
}

if (!empty($filter_status)) {
    $where_conditions[] = "status = ?";
    $params[] = $filter_status;
    $types .= "s";
}

if (!empty($date_from)) {
    $where_conditions[] = "DATE(created_at) >= ?";
    $params[] = $date_from;
    $types .= "s";
}

if (!empty($date_to)) {
    $where_conditions[] = "DATE(created_at) <= ?";
    $params[] = $date_to;
    $types .= "s";
}

$where_clause = implode(" AND ", $where_conditions);

// Fetch all transactions (no pagination for export)
$sql = "SELECT id, user_id, amount, type, status, created_at 
        FROM transactions 
        WHERE $where_clause 
        ORDER BY created_at DESC";

$stmt = $conn->prepare($sql);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$result = $stmt->get_result();
$transactions = $result->fetch_all(MYSQLI_ASSOC);
$stmt->close();

// Get user info for filename
$user_stmt = $conn->prepare("SELECT username, email FROM users WHERE id = ?");
$user_stmt->bind_param("i", $user_id);
$user_stmt->execute();
$user_result = $user_stmt->get_result();
$user_data = $user_result->fetch_assoc();
$user_stmt->close();

// Generate filename
$date = date('Y-m-d');
$filename = "transactions_{$user_data['username']}_{$date}";

// Calculate summary statistics
$total_deposits = 0;
$total_withdrawals = 0;
$total_investments = 0;
$total_profits = 0;
$total_referrals = 0;
$total_completed = 0;
$total_pending = 0;
$total_failed = 0;

foreach ($transactions as $t) {
    switch ($t['type']) {
        case 'deposit':
            $total_deposits += $t['amount'];
            break;
        case 'withdrawal':
            $total_withdrawals += $t['amount'];
            break;
        case 'investment':
            $total_investments += $t['amount'];
            break;
        case 'profit':
            $total_profits += $t['amount'];
            break;
        case 'referral':
            $total_referrals += $t['amount'];
            break;
    }
    
    switch ($t['status']) {
        case 'completed':
            $total_completed += $t['amount'];
            break;
        case 'pending':
            $total_pending += $t['amount'];
            break;
        case 'failed':
            $total_failed += $t['amount'];
            break;
    }
}

// Export based on format
switch ($format) {
    case 'csv':
        exportCSV($transactions, $filename, $user_data, $total_deposits, $total_withdrawals, $total_investments, $total_profits, $total_referrals);
        break;
    case 'excel':
        exportExcel($transactions, $filename, $user_data, $total_deposits, $total_withdrawals, $total_investments, $total_profits, $total_referrals);
        break;
    case 'pdf':
        exportPDF($transactions, $filename, $user_data, $total_deposits, $total_withdrawals, $total_investments, $total_profits, $total_referrals);
        break;
}

function exportCSV($transactions, $filename, $user_data, $total_deposits, $total_withdrawals, $total_investments, $total_profits, $total_referrals) {
    // Set headers for CSV download
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $filename . '.csv"');
    
    // Create output stream
    $output = fopen('php://output', 'w');
    
    // Add UTF-8 BOM for Excel compatibility
    fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF));
    
    // Add header information
    fputcsv($output, ['Transaction Export Report']);
    fputcsv($output, ['Generated:', date('Y-m-d H:i:s')]);
    fputcsv($output, ['User:', $user_data['username'] . ' (' . $user_data['email'] . ')']);
    fputcsv($output, ['Date Range:', $_GET['date_from'] ?? 'All time', 'to', $_GET['date_to'] ?? 'All time']);
    fputcsv($output, []); // Empty row
    
    // Add summary statistics
    fputcsv($output, ['SUMMARY STATISTICS']);
    fputcsv($output, ['Total Transactions:', count($transactions)]);
    fputcsv($output, ['Total Deposits:', '$' . number_format($total_deposits, 2)]);
    fputcsv($output, ['Total Withdrawals:', '$' . number_format($total_withdrawals, 2)]);
    fputcsv($output, ['Total Investments:', '$' . number_format($total_investments, 2)]);
    fputcsv($output, ['Total Profits:', '$' . number_format($total_profits, 2)]);
    fputcsv($output, ['Total Referrals:', '$' . number_format($total_referrals, 2)]);
    fputcsv($output, []); // Empty row
    
    // Add column headers
    fputcsv($output, ['ID', 'Transaction ID', 'Type', 'Amount ($)', 'Status', 'Date', 'Time']);
    
    // Add transaction rows
    foreach ($transactions as $transaction) {
        $date = new DateTime($transaction['created_at']);
        fputcsv($output, [
            $transaction['id'],
            'TXN' . str_pad($transaction['id'], 8, '0', STR_PAD_LEFT),
            ucfirst($transaction['type']),
            number_format($transaction['amount'], 2),
            ucfirst($transaction['status']),
            $date->format('Y-m-d'),
            $date->format('H:i:s')
        ]);
    }
    
    // Add footer
    fputcsv($output, []); // Empty row
    fputcsv($output, ['End of Report']);
    fputcsv($output, ['Total Records:', count($transactions)]);
    
    fclose($output);
    exit();
}

function exportExcel($transactions, $filename, $user_data, $total_deposits, $total_withdrawals, $total_investments, $total_profits, $total_referrals) {
    // For Excel, we'll use CSV with .xls extension (simple Excel-compatible format)
    header('Content-Type: application/vnd.ms-excel; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $filename . '.xls"');
    
    // Create output stream
    $output = fopen('php://output', 'w');
    
    // Add UTF-8 BOM
    fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF));
    
    // HTML table format for better Excel compatibility
    echo '<html>';
    echo '<head>';
    echo '<meta charset="UTF-8">';
    echo '<style>';
    echo 'th { background-color: #f2f2f2; font-weight: bold; }';
    echo '.deposit { color: green; }';
    echo '.withdrawal { color: blue; }';
    echo '.investment { color: purple; }';
    echo '.profit { color: orange; }';
    echo '.referral { color: brown; }';
    echo '.completed { color: green; }';
    echo '.pending { color: orange; }';
    echo '.failed { color: red; }';
    echo '</style>';
    echo '</head>';
    echo '<body>';
    
    // Header
    echo '<h2>Transaction Export Report</h2>';
    echo '<table border="1" cellpadding="5">';
    
    // Report info
    echo '<tr><td colspan="7"><strong>Generated:</strong> ' . date('Y-m-d H:i:s') . '</td></tr>';
    echo '<tr><td colspan="7"><strong>User:</strong> ' . htmlspecialchars($user_data['username']) . ' (' . htmlspecialchars($user_data['email']) . ')</td></tr>';
    echo '<tr><td colspan="7"><strong>Date Range:</strong> ' . ($_GET['date_from'] ?? 'All time') . ' to ' . ($_GET['date_to'] ?? 'All time') . '</td></tr>';
    
    // Summary
    echo '<tr><td colspan="7"><br><strong>SUMMARY STATISTICS</strong></td></tr>';
    echo '<tr><td><strong>Total Transactions:</strong></td><td colspan="6">' . count($transactions) . '</td></tr>';
    echo '<tr><td><strong>Total Deposits:</strong></td><td colspan="6">$' . number_format($total_deposits, 2) . '</td></tr>';
    echo '<tr><td><strong>Total Withdrawals:</strong></td><td colspan="6">$' . number_format($total_withdrawals, 2) . '</td></tr>';
    echo '<tr><td><strong>Total Investments:</strong></td><td colspan="6">$' . number_format($total_investments, 2) . '</td></tr>';
    echo '<tr><td><strong>Total Profits:</strong></td><td colspan="6">$' . number_format($total_profits, 2) . '</td></tr>';
    echo '<tr><td><strong>Total Referrals:</strong></td><td colspan="6">$' . number_format($total_referrals, 2) . '</td></tr>';
    
    // Table headers
    echo '<tr>';
    echo '<th>ID</th>';
    echo '<th>Transaction ID</th>';
    echo '<th>Type</th>';
    echo '<th>Amount ($)</th>';
    echo '<th>Status</th>';
    echo '<th>Date</th>';
    echo '<th>Time</th>';
    echo '</tr>';
    
    // Data rows
    foreach ($transactions as $transaction) {
        $date = new DateTime($transaction['created_at']);
        
        $type_class = strtolower($transaction['type']);
        $status_class = strtolower($transaction['status']);
        
        echo '<tr>';
        echo '<td>' . $transaction['id'] . '</td>';
        echo '<td>TXN' . str_pad($transaction['id'], 8, '0', STR_PAD_LEFT) . '</td>';
        echo '<td class="' . $type_class . '">' . ucfirst($transaction['type']) . '</td>';
        echo '<td>' . number_format($transaction['amount'], 2) . '</td>';
        echo '<td class="' . $status_class . '">' . ucfirst($transaction['status']) . '</td>';
        echo '<td>' . $date->format('Y-m-d') . '</td>';
        echo '<td>' . $date->format('H:i:s') . '</td>';
        echo '</tr>';
    }
    
    // Footer
    echo '<tr><td colspan="7"><br><strong>End of Report</strong></td></tr>';
    echo '<tr><td colspan="7"><strong>Total Records:</strong> ' . count($transactions) . '</td></tr>';
    
    echo '</table>';
    echo '</body></html>';
    
    fclose($output);
    exit();
}

function exportPDF($transactions, $filename, $user_data, $total_deposits, $total_withdrawals, $total_investments, $total_profits, $total_referrals) {
    // Check if TCPDF library exists, if not, fallback to HTML PDF
    if (file_exists('../vendor/autoload.php')) {
        require_once '../vendor/autoload.php';
        
        // Create new PDF document
        $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
        
        // Set document information
        $pdf->SetCreator('Trading Platform');
        $pdf->SetAuthor('Trading Platform');
        $pdf->SetTitle('Transaction Report - ' . $user_data['username']);
        $pdf->SetSubject('Transaction History');
        
        // Remove default header/footer
        $pdf->setPrintHeader(false);
        $pdf->setPrintFooter(false);
        
        // Add a page
        $pdf->AddPage();
        
        // Set font
        $pdf->SetFont('helvetica', '', 10);
        
        // Title
        $pdf->SetFont('helvetica', 'B', 16);
        $pdf->Cell(0, 10, 'Transaction Export Report', 0, 1, 'C');
        $pdf->Ln(5);
        
        // Report info
        $pdf->SetFont('helvetica', '', 10);
        $pdf->Cell(0, 6, 'Generated: ' . date('Y-m-d H:i:s'), 0, 1);
        $pdf->Cell(0, 6, 'User: ' . $user_data['username'] . ' (' . $user_data['email'] . ')', 0, 1);
        $pdf->Cell(0, 6, 'Date Range: ' . ($_GET['date_from'] ?? 'All time') . ' to ' . ($_GET['date_to'] ?? 'All time'), 0, 1);
        $pdf->Ln(5);
        
        // Summary statistics
        $pdf->SetFont('helvetica', 'B', 12);
        $pdf->Cell(0, 8, 'SUMMARY STATISTICS', 0, 1);
        $pdf->SetFont('helvetica', '', 10);
        
        $summary_data = [
            ['Total Transactions:', count($transactions)],
            ['Total Deposits:', '$' . number_format($total_deposits, 2)],
            ['Total Withdrawals:', '$' . number_format($total_withdrawals, 2)],
            ['Total Investments:', '$' . number_format($total_investments, 2)],
            ['Total Profits:', '$' . number_format($total_profits, 2)],
            ['Total Referrals:', '$' . number_format($total_referrals, 2)]
        ];
        
        foreach ($summary_data as $row) {
            $pdf->Cell(40, 6, $row[0], 0, 0);
            $pdf->Cell(40, 6, $row[1], 0, 1);
        }
        $pdf->Ln(5);
        
        // Transactions table
        $pdf->SetFont('helvetica', 'B', 10);
        
        // Calculate column widths
        $col_widths = [20, 25, 25, 30, 25, 30, 25];
        
        // Table header
        $pdf->SetFillColor(240, 240, 240);
        $pdf->Cell($col_widths[0], 8, 'ID', 1, 0, 'C', true);
        $pdf->Cell($col_widths[1], 8, 'Txn ID', 1, 0, 'C', true);
        $pdf->Cell($col_widths[2], 8, 'Type', 1, 0, 'C', true);
        $pdf->Cell($col_widths[3], 8, 'Amount ($)', 1, 0, 'C', true);
        $pdf->Cell($col_widths[4], 8, 'Status', 1, 0, 'C', true);
        $pdf->Cell($col_widths[5], 8, 'Date', 1, 0, 'C', true);
        $pdf->Cell($col_widths[6], 8, 'Time', 1, 1, 'C', true);
        
        // Table data
        $pdf->SetFont('helvetica', '', 9);
        $fill = false;
        
        foreach ($transactions as $transaction) {
            $date = new DateTime($transaction['created_at']);
            
            // Set color based on type
            if ($transaction['type'] == 'deposit' || $transaction['type'] == 'profit' || $transaction['type'] == 'referral') {
                $pdf->SetTextColor(0, 128, 0); // Green for positive
            } else {
                $pdf->SetTextColor(255, 0, 0); // Red for negative
            }
            
            $pdf->Cell($col_widths[0], 6, $transaction['id'], 1, 0, 'C', $fill);
            $pdf->Cell($col_widths[1], 6, 'TXN' . str_pad($transaction['id'], 8, '0', STR_PAD_LEFT), 1, 0, 'C', $fill);
            
            // Reset color for type
            $pdf->SetTextColor(0, 0, 0);
            $pdf->Cell($col_widths[2], 6, ucfirst($transaction['type']), 1, 0, 'C', $fill);
            $pdf->Cell($col_widths[3], 6, number_format($transaction['amount'], 2), 1, 0, 'R', $fill);
            
            // Color for status
            switch ($transaction['status']) {
                case 'completed':
                    $pdf->SetTextColor(0, 128, 0);
                    break;
                case 'pending':
                    $pdf->SetTextColor(255, 165, 0);
                    break;
                case 'failed':
                    $pdf->SetTextColor(255, 0, 0);
                    break;
                default:
                    $pdf->SetTextColor(0, 0, 0);
            }
            
            $pdf->Cell($col_widths[4], 6, ucfirst($transaction['status']), 1, 0, 'C', $fill);
            
            // Reset color for date/time
            $pdf->SetTextColor(0, 0, 0);
            $pdf->Cell($col_widths[5], 6, $date->format('Y-m-d'), 1, 0, 'C', $fill);
            $pdf->Cell($col_widths[6], 6, $date->format('H:i:s'), 1, 1, 'C', $fill);
            
            $fill = !$fill;
        }
        
        // Footer
        $pdf->Ln(5);
        $pdf->SetFont('helvetica', 'I', 9);
        $pdf->Cell(0, 6, 'End of Report - Total Records: ' . count($transactions), 0, 1, 'C');
        
        // Output PDF
        $pdf->Output($filename . '.pdf', 'D');
        exit();
        
    } else {
        // Fallback to HTML PDF if TCPDF not available
        header('Content-Type: text/html; charset=utf-8');
        echo '<html><head>';
        echo '<style>';
        echo 'body { font-family: Arial, sans-serif; }';
        echo 'table { border-collapse: collapse; width: 100%; }';
        echo 'th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }';
        echo 'th { background-color: #f2f2f2; }';
        echo '.deposit { color: green; }';
        echo '.withdrawal { color: blue; }';
        echo '.investment { color: purple; }';
        echo '.profit { color: orange; }';
        echo '.referral { color: brown; }';
        echo '.completed { color: green; }';
        echo '.pending { color: orange; }';
        echo '.failed { color: red; }';
        echo '@media print { .no-print { display: none; } }';
        echo '</style>';
        echo '</head><body>';
        echo '<div class="no-print"><button onclick="window.print()">Print/Save as PDF</button></div>';
        echo '<h2>Transaction Export Report</h2>';
        echo '<p><strong>Generated:</strong> ' . date('Y-m-d H:i:s') . '</p>';
        echo '<p><strong>User:</strong> ' . htmlspecialchars($user_data['username']) . ' (' . htmlspecialchars($user_data['email']) . ')</p>';
        echo '<p><strong>Date Range:</strong> ' . ($_GET['date_from'] ?? 'All time') . ' to ' . ($_GET['date_to'] ?? 'All time') . '</p>';
        
        // Summary
        echo '<h3>SUMMARY STATISTICS</h3>';
        echo '<table>';
        echo '<tr><td><strong>Total Transactions:</strong></td><td>' . count($transactions) . '</td></tr>';
        echo '<tr><td><strong>Total Deposits:</strong></td><td>$' . number_format($total_deposits, 2) . '</td></tr>';
        echo '<tr><td><strong>Total Withdrawals:</strong></td><td>$' . number_format($total_withdrawals, 2) . '</td></tr>';
        echo '<tr><td><strong>Total Investments:</strong></td><td>$' . number_format($total_investments, 2) . '</td></tr>';
        echo '<tr><td><strong>Total Profits:</strong></td><td>$' . number_format($total_profits, 2) . '</td></tr>';
        echo '<tr><td><strong>Total Referrals:</strong></td><td>$' . number_format($total_referrals, 2) . '</td></tr>';
        echo '</table>';
        
        // Transactions table
        echo '<h3>TRANSACTIONS</h3>';
        echo '<table>';
        echo '<tr>';
        echo '<th>ID</th>';
        echo '<th>Transaction ID</th>';
        echo '<th>Type</th>';
        echo '<th>Amount ($)</th>';
        echo '<th>Status</th>';
        echo '<th>Date</th>';
        echo '<th>Time</th>';
        echo '</tr>';
        
        foreach ($transactions as $transaction) {
            $date = new DateTime($transaction['created_at']);
            $type_class = strtolower($transaction['type']);
            $status_class = strtolower($transaction['status']);
            
            echo '<tr>';
            echo '<td>' . $transaction['id'] . '</td>';
            echo '<td>TXN' . str_pad($transaction['id'], 8, '0', STR_PAD_LEFT) . '</td>';
            echo '<td class="' . $type_class . '">' . ucfirst($transaction['type']) . '</td>';
            echo '<td>' . number_format($transaction['amount'], 2) . '</td>';
            echo '<td class="' . $status_class . '">' . ucfirst($transaction['status']) . '</td>';
            echo '<td>' . $date->format('Y-m-d') . '</td>';
            echo '<td>' . $date->format('H:i:s') . '</td>';
            echo '</tr>';
        }
        
        echo '</table>';
        echo '<p><strong>End of Report - Total Records:</strong> ' . count($transactions) . '</p>';
        echo '</body></html>';
        exit();
    }
}
?>