<?php
session_start();
include 'session.php';

// Get user details for notification
$userQuery = mysqli_query($conn, "SELECT first_name, last_name, email FROM users WHERE id='$user_id'");
$userData = mysqli_fetch_assoc($userQuery);
$first_name = $userData['first_name'];
$email = $userData['email'];

// Get IP address for security notification
$user_ip = $_SERVER['REMOTE_ADDR'];
$user_agent = $_SERVER['HTTP_USER_AGENT'];
$browser = get_browser_name($user_agent);
$device = is_mobile_device() ? 'Mobile' : 'Desktop';

// Get filter parameters for notification details
$type_filter = isset($_GET['type']) ? $conn->real_escape_string($_GET['type']) : '';
$category_filter = isset($_GET['category']) ? $conn->real_escape_string($_GET['category']) : '';
$status_filter = isset($_GET['status']) ? $conn->real_escape_string($_GET['status']) : '';
$date_from = isset($_GET['date_from']) ? $conn->real_escape_string($_GET['date_from']) : '';
$date_to = isset($_GET['date_to']) ? $conn->real_escape_string($_GET['date_to']) : '';
$search = isset($_GET['search']) ? $conn->real_escape_string($_GET['search']) : '';

// Count transactions for notification
$total_transactions = 0;
$total_amount = 0;

// Generate CSV first to get counts
ob_start();
$output = fopen('php://temp', 'w');

// CSV headers
fputcsv($output, [
    'Date',
    'Type',
    'Category',
    'Description',
    'Amount',
    'Fee',
    'Net Amount',
    'Currency',
    'Status',
    'Reference/Address',
    'Created At'
]);

// Get filter parameters (same as transaction history)
$combined_transactions = [];

// Get Deposits
$deposit_conditions = ["d.user_id = '$user_id'"];
if (!empty($status_filter)) $deposit_conditions[] = "d.status = '$status_filter'";
if (!empty($date_from)) $deposit_conditions[] = "DATE(d.created_at) >= '$date_from'";
if (!empty($date_to)) $deposit_conditions[] = "DATE(d.created_at) <= '$date_to'";
if (!empty($search)) $deposit_conditions[] = "(d.transaction_hash LIKE '%$search%' OR d.note LIKE '%$search%')";
$deposit_where = !empty($deposit_conditions) ? 'WHERE ' . implode(' AND ', $deposit_conditions) : '';

$deposit_sql = "SELECT 'deposit' as type, d.* FROM deposits d $deposit_where ORDER BY d.created_at DESC";
$deposit_result = mysqli_query($conn, $deposit_sql);
while ($row = mysqli_fetch_assoc($deposit_result)) {
    if (empty($type_filter) || $type_filter == 'credit') {
        $transaction = [
            'date' => $row['created_at'],
            'type' => 'Deposit',
            'category' => 'USDT Deposit',
            'description' => 'USDT Deposit',
            'amount' => $row['amount'],
            'fee' => 0,
            'net_amount' => $row['amount'],
            'currency' => 'USDT',
            'status' => $row['status'],
            'reference' => $row['transaction_hash'],
            'created_at' => $row['created_at']
        ];
        $combined_transactions[] = $transaction;
        $total_transactions++;
        $total_amount += $row['amount'];
    }
}

// Get Withdrawals
$withdrawal_conditions = ["w.user_id = '$user_id'"];
if (!empty($status_filter)) $withdrawal_conditions[] = "w.status = '$status_filter'";
if (!empty($date_from)) $withdrawal_conditions[] = "DATE(w.created_at) >= '$date_from'";
if (!empty($date_to)) $withdrawal_conditions[] = "DATE(w.created_at) <= '$date_to'";
if (!empty($search)) $withdrawal_conditions[] = "(w.destination_address LIKE '%$search%')";
$withdrawal_where = !empty($withdrawal_conditions) ? 'WHERE ' . implode(' AND ', $withdrawal_conditions) : '';

$withdrawal_sql = "SELECT 'withdrawal' as type, w.* FROM withdrawals w $withdrawal_where ORDER BY w.created_at DESC";
$withdrawal_result = mysqli_query($conn, $withdrawal_sql);
while ($row = mysqli_fetch_assoc($withdrawal_result)) {
    if (empty($type_filter) || $type_filter == 'debit') {
        $transaction = [
            'date' => $row['created_at'],
            'type' => 'Withdrawal',
            'category' => 'USDT Withdrawal',
            'description' => 'USDT Withdrawal',
            'amount' => $row['amount'],
            'fee' => $row['fee'],
            'net_amount' => $row['total_amount'],
            'currency' => 'USDT',
            'status' => $row['status'],
            'reference' => $row['destination_address'],
            'created_at' => $row['created_at']
        ];
        $combined_transactions[] = $transaction;
        $total_transactions++;
        $total_amount += $row['amount'];
    }
}

// Get Trading Transactions
$trading_conditions = ["t.user_id = '$user_id'"];
if (!empty($type_filter)) {
    if ($type_filter == 'credit') {
        $trading_conditions[] = "t.type IN ('credit', 'profit')";
    } elseif ($type_filter == 'debit') {
        $trading_conditions[] = "t.type IN ('debit', 'fee')";
    }
}
if (!empty($category_filter)) $trading_conditions[] = "t.category = '$category_filter'";
if (!empty($status_filter)) $trading_conditions[] = "t.status = '$status_filter'";
if (!empty($date_from)) $trading_conditions[] = "DATE(t.created_at) >= '$date_from'";
if (!empty($date_to)) $trading_conditions[] = "DATE(t.created_at) <= '$date_to'";
if (!empty($search)) $trading_conditions[] = "(t.description LIKE '%$search%' OR t.reference LIKE '%$search%')";
$trading_where = !empty($trading_conditions) ? 'WHERE ' . implode(' AND ', $trading_conditions) : '';

$trading_sql = "SELECT t.* FROM transactions t $trading_where ORDER BY t.created_at DESC";
$trading_result = mysqli_query($conn, $trading_sql);
while ($row = mysqli_fetch_assoc($trading_result)) {
    $transaction = [
        'date' => $row['created_at'],
        'type' => ucfirst($row['type']),
        'category' => ucfirst(str_replace('_', ' ', $row['category'])),
        'description' => $row['description'],
        'amount' => $row['amount'],
        'fee' => 0,
        'net_amount' => $row['amount'],
        'currency' => strtoupper($row['currency']),
        'status' => $row['status'],
        'reference' => $row['reference'] ?: '',
        'created_at' => $row['created_at']
    ];
    $combined_transactions[] = $transaction;
    $total_transactions++;
    if ($row['type'] == 'credit') {
        $total_amount += $row['amount'];
    } else {
        $total_amount -= $row['amount'];
    }
}

// Sort by date
usort($combined_transactions, function($a, $b) {
    return strtotime($b['date']) - strtotime($a['date']);
});

// Write CSV rows
foreach ($combined_transactions as $transaction) {
    fputcsv($output, [
        date('Y-m-d H:i:s', strtotime($transaction['date'])),
        $transaction['type'],
        $transaction['category'],
        $transaction['description'],
        number_format($transaction['amount'], 2),
        number_format($transaction['fee'], 2),
        number_format($transaction['net_amount'], 2),
        $transaction['currency'],
        ucfirst($transaction['status']),
        $transaction['reference'],
        $transaction['created_at']
    ]);
}

// Get CSV content
rewind($output);
$csv_content = stream_get_contents($output);
fclose($output);
ob_end_clean();

// Send CSV headers for download
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="transactions_' . date('Y-m-d') . '_' . time() . '.csv"');
header('Content-Length: ' . strlen($csv_content));

// Output CSV content
echo $csv_content;

// NOTIFICATION: Transaction History Exported (USER)
$mail_subject = "Transaction History Exported";
$mail_message = "<!-- Content Section -->
                <div class='email-content'>
                    <h2 class='greeting'>Hello <span class='user-name'>" . $first_name . "</span>,</h2>
                    
                    <p class='message'>
                        📊 <strong>Your transaction history has been exported successfully!</strong><br>
                        Your CSV file is ready for download.
                    </p>

                    <!-- Export Details -->
                    <div class='details-section'>
                        <div class='detail-box'>
                            <strong>Export Date:</strong> " . date('F j, Y g:i A') . "<br>
                            <strong>Filename:</strong> transactions_" . date('Y-m-d') . "_" . time() . ".csv<br>
                            <strong>Total Transactions:</strong> " . number_format($total_transactions) . "<br>
                            <strong>Total Amount:</strong> $" . number_format(abs($total_amount), 2) . " " . 
                                ($total_amount >= 0 ? 'Credits' : 'Debits') . "<br>
                            <strong>Export Type:</strong> CSV Format<br>
                            <strong>Export Size:</strong> " . formatBytes(strlen($csv_content)) . "<br>
                            <strong>Exported From:</strong> " . $user_ip . "<br>
                            <strong>Device:</strong> " . $device . " (" . $browser . ")<br>
                            <strong>Filters Applied:</strong> " . get_filter_summary($type_filter, $category_filter, $status_filter, $date_from, $date_to, $search) . "
                        </div>
                    </div>

                    <!-- What's Included -->
                    <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                        <h4 style='color: #0056b3;'>📋 What's Included in Export</h4>
                        <ul style='color: #0056b3;'>
                            <li>Transaction date and time</li>
                            <li>Transaction type (Deposit/Withdrawal/Trading)</li>
                            <li>Category and description</li>
                            <li>Amount, fees, and net amount</li>
                            <li>Currency (USDT)</li>
                            <li>Transaction status</li>
                            <li>Reference/Address</li>
                            <li>Created timestamp</li>
                        </ul>
                    </div>

                    <!-- Security Information -->
                    <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                        <h4 style='color: #856404;'>🔒 Security Notice</h4>
                        <ul style='color: #856404;'>
                            <li>This file contains sensitive financial information</li>
                            <li>Store it in a secure location</li>
                            <li>Do not share this file with unauthorized parties</li>
                            <li>Delete the file when no longer needed</li>
                            <li>Export was generated securely from your account</li>
                        </ul>
                    </div>

                    <!-- Uses for Export -->
                    <div class='next-steps'>
                        <h3 style='color: #2c3e50;'>📈 How to Use Your Export</h3>
                        <p style='color: #6c757d;'>This CSV file can be used for:</p>
                        <ul style='color: #6c757d;'>
                            <li>Personal accounting and tax preparation</li>
                            <li>Financial analysis and reporting</li>
                            <li>Budget planning and expense tracking</li>
                            <li>Performance evaluation of trading activities</li>
                            <li>Record keeping for compliance purposes</li>
                        </ul>
                    </div>

                    <!-- Download Information -->
                    <div style='background: #d4edda; border: 1px solid #c3e6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                        <h4 style='color: #155724;'>💾 Download Information</h4>
                        <p style='color: #155724;'>
                            <strong>File should download automatically.</strong><br>
                            If download doesn't start:<br>
                            1. Check your browser's download folder<br>
                            2. Make sure pop-ups are allowed<br>
                            3. Try exporting again<br>
                            4. Contact support if issues persist
                        </p>
                    </div>

                    <!-- Action Buttons -->
                    <div style='text-align: center; margin: 30px 0;'>
                        <a href='" . $myUrl . "/transactions.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #2F2CD8; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                            View Transactions
                        </a>
                        <a href='" . $myUrl . "/reports.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #6c757d; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                            Generate Reports
                        </a>
                        <a href='" . $myUrl . "/help/export-guide' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #17a2b8; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                            Export Guide
                        </a>
                    </div>

                    <!-- Support Section -->
                    <div class='support-section'>
                        <p class='support-text'>Need help with transaction exports?</p>
                        <a href='" . $myUrl . "/support.php?category=account' class='support-link'>Contact Account Support</a>
                    </div>
                </div>";

// Send user notification
require_once("../proccess/mail_sender.php");

// NOTIFICATION: Transaction History Exported (ADMIN)
$admin_mail_subject = "Transaction History Exported - User ID: " . $user_id;
$admin_mail_message = "<!-- Content Section -->
                    <div class='email-content'>
                        <h2 class='greeting'>Transaction History Exported</h2>
                        
                        <p class='message'>
                            A user has exported their transaction history as a CSV file.
                        </p>

                        <!-- Export Details -->
                        <div class='details-section'>
                            <div class='detail-box'>
                                <strong>User ID:</strong> " . $user_id . "<br>
                                <strong>User Name:</strong> " . $first_name . " " . $userData['last_name'] . "<br>
                                <strong>User Email:</strong> " . $email . "<br>
                                <strong>Export Date:</strong> " . date('F j, Y g:i A') . "<br>
                                <strong>Filename:</strong> transactions_" . date('Y-m-d') . "_" . time() . ".csv<br>
                                <strong>Total Transactions Exported:</strong> " . number_format($total_transactions) . "<br>
                                <strong>Export Size:</strong> " . formatBytes(strlen($csv_content)) . "<br>
                                <strong>User IP Address:</strong> " . $user_ip . "<br>
                                <strong>Device:</strong> " . $device . " (" . $browser . ")<br>
                                <strong>Applied Filters:</strong> " . get_filter_summary($type_filter, $category_filter, $status_filter, $date_from, $date_to, $search) . "
                            </div>
                        </div>

                        <!-- User Activity -->
                        <div class='next-steps'>
                            <h3 style='color: #2c3e50;'>User Export History</h3>
                            <p style='color: #6c757d;'>
                                <strong>Total Exports (Last 30 days):</strong> " . 
                                    (mysqli_fetch_assoc(mysqli_query($conn, 
                                        "SELECT COUNT(*) as exports FROM user_activity_logs 
                                         WHERE user_id='$user_id' AND activity_type='export_transactions' 
                                         AND created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)"))['exports'] ?? 0) . "<br>
                                <strong>Last Export:</strong> " . 
                                    (mysqli_fetch_assoc(mysqli_query($conn, 
                                        "SELECT created_at FROM user_activity_logs 
                                         WHERE user_id='$user_id' AND activity_type='export_transactions' 
                                         ORDER BY created_at DESC LIMIT 1,1"))['created_at'] ?? 'First export') . "<br>
                                <strong>Account Age:</strong> " . (isset($userData['created_at']) ? 
                                    round((time() - strtotime($userData['created_at'])) / (60 * 60 * 24)) . ' days' : 'N/A') . "
                            </p>
                        </div>

                        <!-- Security Notes -->
                        <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #856404;'>🔍 Security Notes</h4>
                            <p style='color: #856404;'>
                                <strong>Check for:</strong><br>
                                • Frequent exports in short period<br>
                                • Exports to unusual IP addresses<br>
                                • Large transaction volumes<br>
                                • Suspicious filter patterns<br>
                                • Timing with withdrawal requests
                            </p>
                        </div>

                        <!-- Admin Actions -->
                        <div style='text-align: center; margin: 30px 0;'>
                            <a href='" . $myUrl . "/admin/users.php?id=" . $user_id . "' 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;'>
                                View User Profile
                            </a>
                            <a href='" . $myUrl . "/admin/transactions.php?user_id=" . $user_id . "' 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 Transactions
                            </a>
                            <a href='" . $myUrl . "/admin/security-logs.php?user_id=" . $user_id . "' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #6c757d; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                Activity Logs
                            </a>
                        </div>

                        <!-- Notes -->
                        <div class='support-section'>
                            <p class='support-text'>This is a standard data export notification.</p>
                            <p class='support-text'>Monitor for unusual export patterns.</p>
                        </div>
                    </div>";

// Log user activity
mysqli_query($conn, 
    "INSERT INTO user_activity_logs 
    (user_id, activity_type, description, ip_address, created_at) 
    VALUES 
    ('$user_id', 'export_transactions', 'Exported transaction history CSV', '$user_ip', NOW())");

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

exit;

// Helper functions
function get_browser_name($user_agent) {
    if (strpos($user_agent, 'Chrome') !== false) return 'Chrome';
    if (strpos($user_agent, 'Firefox') !== false) return 'Firefox';
    if (strpos($user_agent, 'Safari') !== false) return 'Safari';
    if (strpos($user_agent, 'Edge') !== false) return 'Edge';
    if (strpos($user_agent, 'Opera') !== false) return 'Opera';
    return 'Unknown Browser';
}

function is_mobile_device() {
    $mobile_agents = array(
        'Android', 'webOS', 'iPhone', 'iPad', 'iPod', 'BlackBerry', 
        'Windows Phone', 'Mobile', 'Tablet'
    );
    
    foreach ($mobile_agents as $agent) {
        if (stripos($_SERVER['HTTP_USER_AGENT'], $agent) !== false) {
            return true;
        }
    }
    return false;
}

function formatBytes($bytes, $precision = 2) {
    $units = ['B', 'KB', 'MB', 'GB', 'TB'];
    $bytes = max($bytes, 0);
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
    $pow = min($pow, count($units) - 1);
    $bytes /= pow(1024, $pow);
    return round($bytes, $precision) . ' ' . $units[$pow];
}

function get_filter_summary($type, $category, $status, $date_from, $date_to, $search) {
    $filters = [];
    
    if (!empty($type)) $filters[] = "Type: " . ($type == 'credit' ? 'Credits Only' : ($type == 'debit' ? 'Debits Only' : $type));
    if (!empty($category)) $filters[] = "Category: " . ucfirst($category);
    if (!empty($status)) $filters[] = "Status: " . ucfirst($status);
    if (!empty($date_from)) $filters[] = "From: " . $date_from;
    if (!empty($date_to)) $filters[] = "To: " . $date_to;
    if (!empty($search)) $filters[] = "Search: '" . htmlspecialchars($search) . "'";
    
    return empty($filters) ? 'No filters' : implode(', ', $filters);
}
?>