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

$required = ['current_password', 'new_email'];
foreach ($required as $field) {
    if (empty($_POST[$field])) {
        echo json_encode(['success' => false, 'message' => "Missing required field: $field"]);
        exit;
    }
}

$current_password = $_POST['current_password'];
$new_email = mysqli_real_escape_string($conn, $_POST['new_email']);

// Validate new email
if (!filter_var($new_email, FILTER_VALIDATE_EMAIL)) {
    echo json_encode(['success' => false, 'message' => 'Invalid email address']);
    exit;
}

// Check if email already exists
$check_sql = "SELECT id FROM users WHERE email = '$new_email'";
$check_result = mysqli_query($conn, $check_sql);

if (mysqli_num_rows($check_result) > 0) {
    echo json_encode(['success' => false, 'message' => 'Email already in use']);
    exit;
}

// Get user details for notification
$user_sql = "SELECT * FROM users WHERE id = '$user_id'";
$user_result = mysqli_query($conn, $user_sql);
$user = mysqli_fetch_assoc($user_result);

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

$current_email = $user['email'];
$first_name = $user['first_name'];
$last_name = $user['last_name'];

// 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';

// Generate verification token
$token = bin2hex(random_bytes(32));
$expires = date('Y-m-d H:i:s', strtotime('+24 hours'));

// Save pending email change
$update_sql = "UPDATE users SET 
               pending_email = '$new_email',
               email_change_token = '$token',
               email_change_expires = '$expires',
               updated_at = NOW()
               WHERE id = '$user_id'";

if (!mysqli_query($conn, $update_sql)) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . mysqli_error($conn)]);
    exit;
}

// NOTIFICATION: Email Change Requested (CURRENT EMAIL)
$mail_subject = "Important: Email Change Requested";
$mail_message = "<!-- Content Section -->
                <div class='email-content'>
                    <h2 class='greeting'>Hello <span class='user-name'>" . $first_name . "</span>,</h2>
                    
                    <p class='message'>
                        ⚠️ <strong>A request to change your primary email address has been submitted.</strong><br>
                        This is a critical security action that requires verification.
                    </p>

                    <!-- Change Request Details -->
                    <div class='details-section'>
                        <div class='detail-box'>
                            <strong>Current Email:</strong> " . htmlspecialchars($current_email) . "<br>
                            <strong>Requested New Email:</strong> " . htmlspecialchars($new_email) . "<br>
                            <strong>Request Date:</strong> " . date('F j, Y g:i A') . "<br>
                            <strong>Requested From IP:</strong> " . $user_ip . "<br>
                            <strong>Device:</strong> " . $device . " (" . $browser . ")<br>
                            <strong>Verification Token:</strong> " . $token . "<br>
                            <strong>Token Expires:</strong> " . date('F j, Y g:i A', strtotime('+24 hours')) . "<br>
                            <strong>Account User:</strong> " . $first_name . " " . $last_name . "
                        </div>
                    </div>

                    <!-- What Happens Next -->
                    <div class='next-steps'>
                        <h3 style='color: #2c3e50;'>What Happens Next?</h3>
                        <p style='color: #6c757d;'>Here's the verification process:</p>
                        <ol style='color: #6c757d;'>
                            <li>A verification email has been sent to the new address: <strong>" . htmlspecialchars($new_email) . "</strong></li>
                            <li>The new email owner must click the verification link</li>
                            <li>Once verified, your login email will change to the new address</li>
                            <li>You'll receive a confirmation on both emails</li>
                            <li>Your account data and settings remain unchanged</li>
                        </ol>
                    </div>

                    <!-- Security Alert -->
                    <div style='background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                        <h4 style='color: #721c24;'>🚨 CRITICAL SECURITY ALERT</h4>
                        <p style='color: #721c24;'>
                            <strong>If you did NOT request this email change:</strong><br>
                            • Someone may have access to your account<br>
                            • <strong>CHANGE YOUR PASSWORD IMMEDIATELY</strong><br>
                            • Enable two-factor authentication<br>
                            • Contact our security team NOW
                        </p>
                    </div>

                    <!-- Action Steps -->
                    <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                        <h4 style='color: #856404;'>🛡️ Immediate Action Required</h4>
                        <ul style='color: #856404;'>
                            <li><strong>If you requested this:</strong> Wait for verification email</li>
                            <li><strong>If you DIDN'T request this:</strong>
                                <ol>
                                    <li><a href='" . $myUrl . "/change-password.php' style='color: #856404; text-decoration: underline;'>Change Password</a></li>
                                    <li><a href='" . $myUrl . "/security.php' style='color: #856404; text-decoration: underline;'>Enable 2FA</a></li>
                                    <li><a href='" . $myUrl . "/support.php?priority=high' style='color: #856404; text-decoration: underline;'>Contact Security Team</a></li>
                                </ol>
                            </li>
                        </ul>
                    </div>

                    <!-- Action Buttons -->
                    <div style='text-align: center; margin: 30px 0;'>
                        <a href='" . $myUrl . "/security.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;'>
                            Review Security
                        </a>
                        <a href='" . $myUrl . "/support.php?category=security' 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;'>
                            Report Security Issue
                        </a>
                    </div>

                    <!-- Support Section -->
                    <div class='support-section'>
                        <p class='support-text'>This is a critical security notification.</p>
                        <p class='support-text'>If anything seems suspicious, contact us immediately.</p>
                        <a href='" . $myUrl . "/support.php?priority=high' class='support-link'>Emergency Security Support</a>
                    </div>
                </div>";

// Send notification to current email
$user_email = $current_email;
require_once("../proccess/mail_sender.php");

// NOTIFICATION: Email Change Verification (NEW EMAIL)
$mail_subject = "Verify Your New Email Address - " . $sitename;
$mail_message = "<!-- Content Section -->
                <div class='email-content'>
                    <h2 class='greeting'>Verify Your Email Address</h2>
                    
                    <p class='message'>
                        Hello,<br>
                        A request has been made to use this email as the primary contact for a " . $sitename . " trading account.
                    </p>

                    <!-- Account Details -->
                    <div class='details-section'>
                        <div class='detail-box'>
                            <strong>Account Holder:</strong> " . $first_name . " " . $last_name . "<br>
                            <strong>Current Email:</strong> " . htmlspecialchars($current_email) . "<br>
                            <strong>Requested New Email:</strong> " . htmlspecialchars($new_email) . " (this email)<br>
                            <strong>Request Date:</strong> " . date('F j, Y g:i A') . "<br>
                            <strong>Requested From IP:</strong> " . $user_ip . "<br>
                            <strong>Account ID:</strong> " . $user_id . "
                        </div>
                    </div>

                    <!-- What This Means -->
                    <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                        <h4 style='color: #0056b3;'>📧 After Verification</h4>
                        <p style='color: #0056b3;'>
                            Once verified, this email will become the:<br>
                            • <strong>Primary login email</strong> for the account<br>
                            • Main contact for all notifications<br>
                            • Recovery email for password resets<br>
                            • Receiving address for all account communications
                        </p>
                    </div>

                    <!-- Verification Instructions -->
                    <div class='next-steps'>
                        <h3 style='color: #2c3e50;'>✅ Complete Email Change</h3>
                        <p style='color: #6c757d;'>
                            If you are <strong>" . $first_name . " " . $last_name . "</strong> and requested this change,<br>
                            please verify by clicking the button below:
                        </p>
                    </div>

                    <!-- Verification Button -->
                    <div style='text-align: center; margin: 30px 0;'>
                        <a href='" . $myUrl . "/verify-email-change.php?token=" . $token . "&email=" . urlencode($new_email) . "' 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;'>
                            Verify & Change Email
                        </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;'>
                            " . $myUrl . "/verify-email-change.php?token=" . $token . "&email=" . urlencode($new_email) . "
                        </p>
                    </div>

                    <!-- Important Security Information -->
                    <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                        <h4 style='color: #856404;'>⚠️ CRITICAL SECURITY INFORMATION</h4>
                        <ul style='color: #856404;'>
                            <li>This link expires in <strong>24 hours</strong></li>
                            <li>Only verify if you are the account owner: <strong>" . $first_name . " " . $last_name . "</strong></li>
                            <li>Verifying gives this email FULL ACCESS to the account</li>
                            <li>You will receive ALL future notifications at this address</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 This Wasn't You</h4>
                        <p style='color: #721c24;'>
                            <strong>DO NOT CLICK THE VERIFICATION LINK</strong><br>
                            If you don't know <strong>" . $first_name . " " . $last_name . "</strong>:<br>
                            • Please ignore this email<br>
                            • The request will expire automatically<br>
                            • No further action is required<br>
                            • The account owner has been notified
                        </p>
                    </div>

                    <!-- Support Section -->
                    <div class='support-section'>
                        <p class='support-text'>Questions about this email change?</p>
                        <a href='" . $myUrl . "/support.php' class='support-link'>Contact Support</a>
                    </div>
                </div>";

// Send verification email to new email
$user_email = $new_email;
$first_name = "User"; // Generic since we're sending to new email
require_once("../proccess/mail_sender.php");

// NOTIFICATION: Primary Email Change Request (ADMIN)
$admin_mail_subject = "SECURITY: Primary Email Change Request - User ID: " . $user_id;
$admin_mail_message = "<!-- Content Section -->
                    <div class='email-content'>
                        <h2 class='greeting'>Security Alert: Primary Email Change Request</h2>
                        
                        <p class='message'>
                            A user has requested to change their primary email address. This is a high-security action.
                        </p>

                        <!-- Change Request Details -->
                        <div class='details-section'>
                            <div class='detail-box'>
                                <strong>User ID:</strong> " . $user_id . "<br>
                                <strong>User Name:</strong> " . $first_name . " " . $last_name . "<br>
                                <strong>Current Email:</strong> " . htmlspecialchars($current_email) . "<br>
                                <strong>Requested New Email:</strong> " . htmlspecialchars($new_email) . "<br>
                                <strong>Request Date:</strong> " . date('F j, Y g:i A') . "<br>
                                <strong>User IP Address:</strong> " . $user_ip . "<br>
                                <strong>Device:</strong> " . $device . "<br>
                                <strong>Browser:</strong> " . $browser . "<br>
                                <strong>Verification Token:</strong> " . $token . "<br>
                                <strong>Token Expires:</strong> " . date('F j, Y g:i A', strtotime('+24 hours')) . "<br>
                                <strong>Account Status:</strong> " . ($user['status'] ?? 'Active') . "
                            </div>
                        </div>

                        <!-- User Account History -->
                        <div class='next-steps'>
                            <h3 style='color: #2c3e50;'>User Account History</h3>
                            <p style='color: #6c757d;'>
                                <strong>Account Created:</strong> " . (isset($user['created_at']) ? date('F j, Y', strtotime($user['created_at'])) : 'N/A') . "<br>
                                <strong>Last Login:</strong> " . (isset($user['last_login']) ? date('F j, Y g:i A', strtotime($user['last_login'])) : 'N/A') . "<br>
                                <strong>Total Logins:</strong> " . ($user['login_count'] ?? 0) . "<br>
                                <strong>2FA Enabled:</strong> " . (isset($user['two_factor_enabled']) && $user['two_factor_enabled'] == 1 ? 'Yes' : 'No') . "<br>
                                <strong>Previous Email Changes:</strong> " . 
                                    (mysqli_fetch_assoc(mysqli_query($conn, 
                                        "SELECT COUNT(*) as changes FROM email_change_log 
                                         WHERE user_id='$user_id'"))['changes'] ?? 0) . "
                            </p>
                        </div>

                        <!-- Security Risk Assessment -->
                        <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #856404;'>⚠️ Security Risk Assessment</h4>
                            <p style='color: #856404;'>
                                <strong>Risk Level:</strong> <span style='color: #dc3545; font-weight: bold;'>HIGH</span><br>
                                <strong>Reason:</strong> Primary email change is a critical security action<br>
                                <strong>Monitoring Required:</strong> Yes<br>
                                <strong>Auto-approval:</strong> After verification (24-hour window)<br>
                                <strong>Flag for Review:</strong> " . 
                                    ((isset($user['email_changes_count']) && $user['email_changes_count'] > 2) ? 
                                    'Yes - Frequent changes' : 'No - Normal pattern') . "
                            </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;'>
                                Security Logs
                            </a>
                            <a href='" . $myUrl . "/admin/block-user.php?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;'>
                                Block Suspicious Activity
                            </a>
                        </div>

                        <!-- Monitoring Instructions -->
                        <div class='support-section'>
                            <p class='support-text'><strong>Admin Monitoring Instructions:</strong></p>
                            <p class='support-text'>
                                1. Watch for verification completion<br>
                                2. Monitor for suspicious login attempts<br>
                                3. Check if IP address matches usual patterns<br>
                                4. Review user's recent activity<br>
                                5. Be ready to intervene if needed
                            </p>
                        </div>
                    </div>";

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

// Log the email change request
$log_sql = "INSERT INTO email_change_log 
            (user_id, old_email, new_email, request_ip, token, created_at)
            VALUES 
            ('$user_id', '$current_email', '$new_email', '$user_ip', '$token', NOW())";
mysqli_query($conn, $log_sql);

echo json_encode(['success' => true, 'message' => 'Verification email sent', 'email' => $new_email]);

// Helper functions for device/browser detection
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;
}
?>