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

if (empty($_POST['password'])) {
    echo json_encode(['success' => false, 'message' => 'Password required']);
    exit;
}

$password = $_POST['password'];

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

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

// Get account statistics
$account_age = round((time() - strtotime($created_at)) / (60 * 60 * 24));
$total_deposits = mysqli_fetch_assoc(mysqli_query($conn, 
    "SELECT SUM(amount) as total FROM transactions WHERE user_id='$user_id' AND type='deposit'"))['total'] ?? 0;
$total_withdrawals = mysqli_fetch_assoc(mysqli_query($conn, 
    "SELECT SUM(amount) as total FROM transactions WHERE user_id='$user_id' AND type='withdrawal'"))['total'] ?? 0;
$total_profits = mysqli_fetch_assoc(mysqli_query($conn, 
    "SELECT SUM(total_profit) as total FROM user_bot_subscriptions WHERE user_id='$user_id'"))['total'] ?? 0;

// Verify password
$sql = "SELECT password FROM users WHERE id = '$user_id'";
$result = mysqli_query($conn, $sql);
$user = mysqli_fetch_assoc($result);

if (!password_verify($password, $user['password'])) {
    echo json_encode(['success' => false, 'message' => 'Incorrect password']);
    exit;
}

// Check if user has active balance
if ($availableBalance > 0 || $fundBalance > 0) {
    echo json_encode(['success' => false, 'message' => 'Cannot delete account with active balance. Please withdraw all funds first.']);
    exit;
}

// Check for active bot subscriptions
$bot_sql = "SELECT id, bot_plan_id FROM user_bot_subscriptions WHERE user_id = '$user_id' AND status = 'active'";
$bot_result = mysqli_query($conn, $bot_sql);
if (mysqli_num_rows($bot_result) > 0) {
    echo json_encode(['success' => false, 'message' => 'Cannot delete account with active bot subscriptions. Cancel all subscriptions first.']);
    exit;
}

// Start transaction
mysqli_begin_transaction($conn);

try {
    // Mark user as deleted (soft delete)
    $delete_sql = "UPDATE users SET 
                   status = 'deleted',
                   deleted_at = NOW(),
                   updated_at = NOW(),
                   deletion_reason = 'user_requested',
                   deletion_ip = '$user_ip'
                   WHERE id = '$user_id'";
    
    if (!mysqli_query($conn, $delete_sql)) {
        throw new Exception('Failed to delete user: ' . mysqli_error($conn));
    }
    
    // Cancel any pending bot subscriptions
    $cancel_bots_sql = "UPDATE user_bot_subscriptions SET 
                       status = 'cancelled',
                       updated_at = NOW()
                       WHERE user_id = '$user_id' AND status IN ('active', 'pending')";
    mysqli_query($conn, $cancel_bots_sql);
    
    // NOTIFICATION: Account Deleted (USER)
    $mail_subject = "Account Deleted - " . $sitename;
    $mail_message = "<!-- Content Section -->
                    <div class='email-content'>
                        <h2 class='greeting'>Goodbye <span class='user-name'>" . $first_name . "</span>,</h2>
                        
                        <p class='message'>
                            Your account has been <strong>permanently deleted</strong> as requested.
                        </p>

                        <!-- Deletion Details -->
                        <div class='details-section'>
                            <div class='detail-box'>
                                <strong>Account Username:</strong> " . htmlspecialchars($username) . "<br>
                                <strong>Account Email:</strong> " . htmlspecialchars($user_email) . "<br>
                                <strong>Account Name:</strong> " . $first_name . " " . $last_name . "<br>
                                <strong>Deletion Date:</strong> " . date('F j, Y g:i A') . "<br>
                                <strong>Deletion IP Address:</strong> " . $user_ip . "<br>
                                <strong>Account Age:</strong> " . $account_age . " days<br>
                                <strong>Deletion Status:</strong> <span style='color: #dc3545; font-weight: bold;'>PERMANENT</span>
                            </div>
                        </div>

                        <!-- Account Summary -->
                        <div style='background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #495057;'>📊 Account Summary</h4>
                            <p style='color: #495057;'>
                                <strong>Total Deposits:</strong> $" . number_format($total_deposits, 2) . "<br>
                                <strong>Total Withdrawals:</strong> $" . number_format($total_withdrawals, 2) . "<br>
                                <strong>Total Profits Earned:</strong> $" . number_format($total_profits, 2) . "<br>
                                <strong>Account Created:</strong> " . date('F j, Y', strtotime($created_at)) . "
                            </p>
                        </div>

                        <!-- What Happens Next -->
                        <div class='next-steps'>
                            <h3 style='color: #2c3e50;'>What Happens Now?</h3>
                            <ul style='color: #6c757d;'>
                                <li>Your account is <strong>permanently deactivated</strong></li>
                                <li>All active trading bots have been cancelled</li>
                                <li>Your personal data will be anonymized in 30 days</li>
                                <li>You cannot reactivate this account</li>
                                <li>All sessions have been terminated</li>
                            </ul>
                        </div>

                        <!-- Data Retention Notice -->
                        <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #856404;'>📝 Data Retention Policy</h4>
                            <p style='color: #856404;'>
                                For legal and regulatory purposes, we retain:<br>
                                • Financial transaction records for 7 years<br>
                                • Account closure records for 5 years<br>
                                • IP logs for security investigations<br><br>
                                Your personal identifiers will be removed within 30 days.
                            </p>
                        </div>

                        <!-- If This Wasn't You -->
                        <div style='background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #721c24;'>🚨 URGENT: If This Wasn't You</h4>
                            <p style='color: #721c24;'>
                                If you did NOT request this deletion:<br><br>
                                <strong>Contact support IMMEDIATELY:</strong><br>
                                • Email: security@" . parse_url($myUrl, PHP_URL_HOST) . "<br>
                                • Phone: [Support Phone Number]<br>
                                • Reference: Account ID " . $user_id . "<br><br>
                                We may be able to restore your account within 24 hours.
                            </p>
                        </div>

                        <!-- Final Message -->
                        <div style='text-align: center; margin: 30px 0; padding: 20px; background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%); border-radius: 8px;'>
                            <h3 style='color: #2c3e50;'>Thank You for Trading With Us</h3>
                            <p style='color: #6c757d;'>
                                We appreciate your time with " . $sitename . ".<br>
                                We hope to serve you again in the future.
                            </p>
                        </div>

                        <!-- Goodbye Message -->
                        <div class='support-section'>
                            <p class='support-text'>This is the final email from " . $sitename . ".</p>
                            <p class='support-text'>Goodbye and best wishes for your trading journey!</p>
                        </div>
                    </div>";

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

    // NOTIFICATION: Account Deleted (ADMIN - URGENT)
    $admin_mail_subject = "🚨 ACCOUNT DELETED - User ID: " . $user_id;
    $admin_mail_message = "<!-- Content Section -->
                        <div class='email-content'>
                            <h2 class='greeting' style='color: #dc3545;'>🚨 ACCOUNT DELETED</h2>
                            
                            <p class='message'>
                                A user has permanently deleted their account.
                            </p>

                            <!-- User Details -->
                            <div class='details-section'>
                                <div class='detail-box'>
                                    <strong>User ID:</strong> " . $user_id . "<br>
                                    <strong>Username:</strong> " . htmlspecialchars($username) . "<br>
                                    <strong>Full Name:</strong> " . $first_name . " " . $last_name . "<br>
                                    <strong>Email:</strong> " . htmlspecialchars($user_email) . "<br>
                                    <strong>Deletion Date:</strong> " . date('F j, Y g:i A') . "<br>
                                    <strong>Deletion IP:</strong> " . $user_ip . "<br>
                                    <strong>User Agent:</strong> " . htmlspecialchars(substr($user_agent, 0, 100)) . "<br>
                                    <strong>Account Age:</strong> " . $account_age . " days<br>
                                    <strong>Deletion Reason:</strong> User Requested
                                </div>
                            </div>

                            <!-- Account Statistics -->
                            <div style='background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #495057;'>📈 Account Performance</h4>
                                <p style='color: #495057;'>
                                    <strong>Total Deposits:</strong> $" . number_format($total_deposits, 2) . "<br>
                                    <strong>Total Withdrawals:</strong> $" . number_format($total_withdrawals, 2) . "<br>
                                    <strong>Net Balance:</strong> $" . number_format($total_deposits - $total_withdrawals, 2) . "<br>
                                    <strong>Total Profits:</strong> $" . number_format($total_profits, 2) . "<br>
                                    <strong>Active Bots:</strong> " . mysqli_num_rows($bot_result) . " (cancelled)<br>
                                    <strong>Last Login:</strong> " . (isset($userData['last_login']) ? date('F j, Y g:i A', strtotime($userData['last_login'])) : 'N/A') . "
                                </p>
                            </div>

                            <!-- User Activity -->
                            <div class='next-steps'>
                                <h3 style='color: #2c3e50;'>Recent Activity</h3>
                                <p style='color: #6c757d;'>
                                    <strong>Support Tickets:</strong> " . 
                                        (mysqli_fetch_assoc(mysqli_query($conn, 
                                            "SELECT COUNT(*) as count FROM support_tickets WHERE user_id='$user_id'"))['count'] ?? 0) . "<br>
                                    <strong>Referrals:</strong> " . 
                                        (mysqli_fetch_assoc(mysqli_query($conn, 
                                            "SELECT COUNT(*) as count FROM users WHERE referred_by='$user_id'"))['count'] ?? 0) . "<br>
                                    <strong>Email Changes (Last 7 days):</strong> " . 
                                        (mysqli_fetch_assoc(mysqli_query($conn, 
                                            "SELECT COUNT(*) as changes FROM user_secondary_emails 
                                             WHERE user_id='$user_id' AND created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)"))['changes'] ?? 0) . "
                                </p>
                            </div>

                            <!-- Suspicious Activity Check -->
                            <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #856404;'>⚠️ Suspicious Activity Check</h4>
                                <p style='color: #856404;'>
                                    <strong>Check for:</strong><br>
                                    • Recent password/email changes<br>
                                    • Unusual login locations<br>
                                    • Multiple failed login attempts<br>
                                    • Recent large withdrawals<br>
                                    • Support tickets about account security
                                </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 (Archived)
                                </a>
                                <a href='" . $myUrl . "/admin/security-logs.php?user_id=" . $user_id . "' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #dc3545; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                    Security Investigation
                                </a>
                            </div>

                            <!-- Recovery Window -->
                            <div style='background: #d1ecf1; border: 1px solid #bee5eb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #0c5460;'>⏰ Recovery Window</h4>
                                <p style='color: #0c5460;'>
                                    <strong>Account can be restored within 24 hours</strong><br>
                                    After 24 hours: Permanent deletion<br>
                                    After 30 days: Personal data anonymized<br>
                                    User can contact support for recovery: " . $user_email . "
                                </p>
                            </div>

                            <!-- Support Section -->
                            <div class='support-section'>
                                <p class='support-text'>This is an URGENT security notification.</p>
                                <p class='support-text'>Monitor for related suspicious activity.</p>
                            </div>
                        </div>";

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

    // Logout all sessions
    session_destroy();
    
    // Commit transaction
    mysqli_commit($conn);
    
    echo json_encode(['success' => true, 'message' => 'Account deleted successfully']);
    
} catch (Exception $e) {
    // Rollback transaction
    mysqli_rollback($conn);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>