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

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

// Get IP address for security notification
$user_ip = $_SERVER['REMOTE_ADDR'];
$user_agent = $_SERVER['HTTP_USER_AGENT'];

// Generate export data
$export_data = [
    'user_info' => [],
    'account_data' => [],
    'transactions' => [],
    'security' => [],
    'export_info' => [
        'export_date' => date('Y-m-d H:i:s'),
        'exported_by_user_id' => $user_id,
        'export_source_ip' => $user_ip,
        'data_range' => 'Last 90 days for transactions'
    ]
];

// User info
$user_sql = "SELECT username, email, first_name, last_name, created_at, updated_at, 
             last_login, status, email_verified, phone_verified
             FROM users WHERE id = '$user_id'";
$user_result = mysqli_query($conn, $user_sql);
$export_data['user_info'] = mysqli_fetch_assoc($user_result);

// Account data
$wallet_sql = "SELECT * FROM wallets WHERE user_id = '$user_id'";
$wallet_result = mysqli_query($conn, $wallet_sql);
$export_data['account_data']['wallet'] = mysqli_fetch_assoc($wallet_result);

// Get trading bot subscriptions
$bots_sql = "SELECT ubs.*, tbp.plan_name 
             FROM user_bot_subscriptions ubs
             LEFT JOIN trading_bot_plans tbp ON ubs.bot_plan_id = tbp.id
             WHERE ubs.user_id = '$user_id'";
$bots_result = mysqli_query($conn, $bots_sql);
$export_data['account_data']['trading_bots'] = [];
while ($row = mysqli_fetch_assoc($bots_result)) {
    $export_data['account_data']['trading_bots'][] = $row;
}

// Get referral data
$referral_sql = "SELECT * FROM referrals WHERE referrer_id = '$user_id' OR referred_id = '$user_id'";
$referral_result = mysqli_query($conn, $referral_sql);
$export_data['account_data']['referrals'] = [];
while ($row = mysqli_fetch_assoc($referral_result)) {
    $export_data['account_data']['referrals'][] = $row;
}

// Transactions (last 90 days)
$trans_sql = "SELECT * FROM transactions 
              WHERE user_id = '$user_id' 
              AND created_at >= DATE_SUB(NOW(), INTERVAL 90 DAY)
              ORDER BY created_at DESC";
$trans_result = mysqli_query($conn, $trans_sql);
$export_data['transactions']['list'] = [];
while ($row = mysqli_fetch_assoc($trans_result)) {
    $export_data['transactions']['list'][] = $row;
}

// Transaction statistics
$trans_stats_sql = "SELECT 
                    COUNT(*) as total_transactions,
                    SUM(CASE WHEN type = 'credit' THEN amount ELSE 0 END) as total_credits,
                    SUM(CASE WHEN type = 'debit' THEN amount ELSE 0 END) as total_debits,
                    MIN(created_at) as first_transaction,
                    MAX(created_at) as last_transaction
                    FROM transactions 
                    WHERE user_id = '$user_id'";
$trans_stats_result = mysqli_query($conn, $trans_stats_sql);
$export_data['transactions']['statistics'] = mysqli_fetch_assoc($trans_stats_result);

// Security settings
$security_sql = "SELECT * FROM user_security WHERE user_id = '$user_id'";
$security_result = mysqli_query($conn, $security_sql);
$export_data['security'] = mysqli_fetch_assoc($security_result);

// Remove sensitive data
unset($export_data['security']['two_factor_secret']);
unset($export_data['security']['withdrawal_pin']);
unset($export_data['account_data']['wallet']['usdt_address']);
unset($export_data['account_data']['wallet']['wallet_pin']);
unset($export_data['user_info']['password']);

// Generate export file
$export_json = json_encode($export_data, JSON_PRETTY_PRINT);
$filename = "account_export_{$user_id}_" . date('Y-m-d_His') . ".json";
$filename_display = "account_data_export_" . date('F_j_Y') . ".json";

// Save to file
$export_dir = '../exports/';
if (!file_exists($export_dir)) {
    mkdir($export_dir, 0775, true);
}

$filepath = $export_dir . $filename;
file_put_contents($filepath, $export_json);

// Create download link (valid for 7 days)
$download_token = bin2hex(random_bytes(16));
$expiry_date = date('Y-m-d H:i:s', strtotime('+7 days'));

// Store download token in database
$token_sql = "INSERT INTO export_downloads 
              (user_id, token, filename, expiry_date, created_at) 
              VALUES ('$user_id', '$download_token', '$filename', '$expiry_date', NOW())";
mysqli_query($conn, $token_sql);

$download_link = $myUrl . "/download-export.php?token=" . $download_token;

// NOTIFICATION: Account Data Export Ready (USER)
$mail_subject = "Your Account Data Export is Ready";
$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 account data export has been generated successfully!</strong><br>
                        You can download your complete account information using the link below.
                    </p>

                    <!-- Export Details -->
                    <div class='details-section'>
                        <div class='detail-box'>
                            <strong>Export Date:</strong> " . date('F j, Y g:i A') . "<br>
                            <strong>Export ID:</strong> EXP-" . substr($download_token, 0, 8) . "<br>
                            <strong>Filename:</strong> " . $filename_display . "<br>
                            <strong>File Size:</strong> " . round(strlen($export_json) / 1024, 2) . " KB<br>
                            <strong>Data Included:</strong> Account info, transactions, security settings<br>
                            <strong>Transaction Range:</strong> Last 90 days<br>
                            <strong>Download Link Expires:</strong> " . date('F j, Y', strtotime('+7 days')) . "<br>
                            <strong>Requested From IP:</strong> " . $user_ip . "
                        </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;'>📊 Data Included in Export</h4>
                        <ul style='color: #0056b3;'>
                            <li><strong>Personal Information:</strong> Name, email, account details</li>
                            <li><strong>Wallet Information:</strong> Balances, wallet status</li>
                            <li><strong>Transaction History:</strong> Last 90 days of all transactions</li>
                            <li><strong>Trading Data:</strong> Bot subscriptions and performance</li>
                            <li><strong>Security Settings:</strong> Account security preferences</li>
                            <li><strong>Referral Information:</strong> Referral history and earnings</li>
                            <li><strong>Account Statistics:</strong> Transaction totals and summaries</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;'>🔒 Important Security Information</h4>
                        <p style='color: #856404;'>
                            <strong>Sensitive data excluded for security:</strong><br>
                            • Passwords and PINs<br>
                            • Two-factor authentication secrets<br>
                            • Wallet private keys/addresses<br>
                            • API keys and tokens
                        </p>
                    </div>

                    <!-- Download Instructions -->
                    <div class='next-steps'>
                        <h3 style='color: #2c3e50;'>📥 Download Your Data</h3>
                        <p style='color: #6c757d;'>Click the button below to download your account data:</p>
                    </div>

                    <!-- Download Button -->
                    <div style='text-align: center; margin: 30px 0;'>
                        <a href='" . $download_link . "' class='verification-button' style='display: inline-block; padding: 16px 45px; background: #2F2CD8; color: white; text-decoration: none; border-radius: 8px; font-weight: 600; font-size: 16px;'>
                            Download Account Data
                        </a>
                    </div>

                    <!-- Alternative Link -->
                    <div style='background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 15px; margin: 20px 0; text-align: center;'>
                        <p style='color: #6c757d; font-size: 14px; margin-bottom: 10px;'>Or copy and paste this link:</p>
                        <p style='background: white; padding: 10px; border-radius: 4px; font-family: monospace; word-break: break-all; font-size: 12px;'>
                            " . $download_link . "
                        </p>
                    </div>

                    <!-- Data Privacy -->
                    <div style='background: #d4edda; border: 1px solid #c3e6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                        <h4 style='color: #155724;'>🔐 Data Privacy & Usage</h4>
                        <ul style='color: #155724;'>
                            <li>Your data is encrypted during transmission</li>
                            <li>Download link is unique and secure</li>
                            <li>Exported files are automatically deleted after 30 days</li>
                            <li>For GDPR/CCPA compliance purposes</li>
                            <li>Store downloaded files securely</li>
                        </ul>
                    </div>

                    <!-- What If Not You -->
                    <div style='background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                        <h4 style='color: #721c24;'>❌ If You Didn't Request This</h4>
                        <p style='color: #721c24;'>
                            If you didn't request this data export:<br>
                            • Your account may have been accessed by someone else<br>
                            • Change your password immediately<br>
                            • Enable two-factor authentication<br>
                            • Contact our security team
                        </p>
                    </div>

                    <!-- Support Section -->
                    <div class='support-section'>
                        <p class='support-text'>Need help with your data export?</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: Account Data Export Generated (ADMIN)
$admin_mail_subject = "Account Data Export Request - User ID: " . $user_id;
$admin_mail_message = "<!-- Content Section -->
                    <div class='email-content'>
                        <h2 class='greeting'>Account Data Export Request</h2>
                        
                        <p class='message'>
                            A user has requested their account data export.
                        </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 ID:</strong> EXP-" . substr($download_token, 0, 8) . "<br>
                                <strong>Export Date:</strong> " . date('F j, Y g:i A') . "<br>
                                <strong>Filename:</strong> " . $filename . "<br>
                                <strong>Download Token:</strong> " . $download_token . "<br>
                                <strong>Token Expiry:</strong> " . $expiry_date . "<br>
                                <strong>Request IP:</strong> " . $user_ip . "<br>
                                <strong>Account Created:</strong> " . date('F j, Y', strtotime($account_created)) . "<br>
                                <strong>Export Count (This User):</strong> " . 
                                    (mysqli_fetch_assoc(mysqli_query($conn, 
                                        "SELECT COUNT(*) as count FROM export_downloads WHERE user_id='$user_id'"))['count'] ?? 0) . "
                            </div>
                        </div>

                        <!-- Data Summary -->
                        <div class='next-steps'>
                            <h3 style='color: #2c3e50;'>Data Summary</h3>
                            <p style='color: #6c757d;'>
                                <strong>User Information:</strong> Personal details, account status<br>
                                <strong>Wallet Data:</strong> Balance: $" . ($export_data['account_data']['wallet']['balance'] ?? 0) . "<br>
                                <strong>Transactions Included:</strong> " . count($export_data['transactions']['list']) . " transactions<br>
                                <strong>Trading Bots:</strong> " . count($export_data['account_data']['trading_bots']) . " active/subscriptions<br>
                                <strong>File Size:</strong> " . round(strlen($export_json) / 1024, 2) . " KB<br>
                                <strong>Data Format:</strong> JSON (readable format)
                            </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>
                            <ul style='color: #856404;'>
                                <li>Sensitive data (passwords, PINs) excluded from export</li>
                                <li>Download link expires in 7 days</li>
                                <li>Export files auto-delete after 30 days</li>
                                <li>User requested this export themselves</li>
                                <li>Monitor for excessive export requests</li>
                            </ul>
                        </div>

                        <!-- User Activity -->
                        <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #0056b3;'>📋 Recent User Activity</h4>
                            <p style='color: #0056b3;'>
                                <strong>Last Login:</strong> " . (isset($export_data['user_info']['last_login']) ? 
                                    date('F j, Y g:i A', strtotime($export_data['user_info']['last_login'])) : 'Never') . "<br>
                                <strong>Email Verified:</strong> " . ($export_data['user_info']['email_verified'] ?? 'No') . "<br>
                                <strong>Account Status:</strong> " . ($export_data['user_info']['status'] ?? 'Active') . "<br>
                                <strong>Total Transactions:</strong> " . ($export_data['transactions']['statistics']['total_transactions'] ?? 0) . "
                            </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/security-logs.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 Security Logs
                            </a>
                        </div>

                        <!-- Notes -->
                        <div class='support-section'>
                            <p class='support-text'>This is an automated data export notification.</p>
                            <p class='support-text'>For GDPR/CCPA compliance tracking.</p>
                        </div>
                    </div>";

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

echo json_encode(['success' => true, 'message' => 'Export email sent', 'download_token' => $download_token]);
?>