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

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

$email_id = intval($_POST['email_id']);

// Get email details before deletion for notification
$email_sql = "SELECT se.*, u.first_name, u.last_name, u.email as primary_email 
              FROM user_secondary_emails se
              JOIN users u ON se.user_id = u.id
              WHERE se.id = '$email_id' AND se.user_id = '$user_id'";
$email_result = mysqli_query($conn, $email_sql);

if (!$email_result || mysqli_num_rows($email_result) === 0) {
    echo json_encode(['success' => false, 'message' => 'Email not found']);
    exit;
}

$email_data = mysqli_fetch_assoc($email_result);
$secondary_email = $email_data['email'];
$first_name = $email_data['first_name'];
$last_name = $email_data['last_name'];
$primary_email = $email_data['primary_email'];
$verified_status = $email_data['verified'];
$created_date = $email_data['created_at'];

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

// Get count of remaining secondary emails
$count_sql = "SELECT COUNT(*) as email_count FROM user_secondary_emails WHERE user_id = '$user_id'";
$count_result = mysqli_query($conn, $count_sql);
$count_row = mysqli_fetch_assoc($count_result);
$remaining_emails = $count_row['email_count'] - 1; // Minus the one being deleted

// Delete email
$delete_sql = "DELETE FROM user_secondary_emails WHERE id = '$email_id' AND user_id = '$user_id'";

if (mysqli_query($conn, $delete_sql)) {
    // NOTIFICATION: Secondary Email Removed (PRIMARY EMAIL)
    $mail_subject = "Secondary Email Removed";
    $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 secondary email has been removed from your account.</strong><br>
                            This email will no longer receive notifications from " . $sitename . ".
                        </p>

                        <!-- Removal Details -->
                        <div class='details-section'>
                            <div class='detail-box'>
                                <strong>Removed Email:</strong> " . htmlspecialchars($secondary_email) . "<br>
                                <strong>Removal Date:</strong> " . date('F j, Y g:i A') . "<br>
                                <strong>Primary Email:</strong> " . htmlspecialchars($primary_email) . "<br>
                                <strong>Verification Status:</strong> " . ($verified_status == 1 ? 
                                    '<span style="color: #28a745; font-weight: bold;">Verified</span>' : 
                                    '<span style="color: #ffc107; font-weight: bold;">Not Verified</span>') . "<br>
                                <strong>Added Date:</strong> " . date('F j, Y', strtotime($created_date)) . "<br>
                                <strong>Removed From IP:</strong> " . $user_ip . "<br>
                                <strong>Remaining Secondary Emails:</strong> " . $remaining_emails . " / 5<br>
                                <strong>Action:</strong> Manual Removal by User
                            </div>
                        </div>

                        <!-- Impact of Removal -->
                        <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #856404;'>📧 What This Means</h4>
                            <ul style='color: #856404;'>
                                <li>No more notifications will be sent to " . htmlspecialchars($secondary_email) . "</li>
                                <li>Trading alerts will only go to primary email</li>
                                <li>Account recovery options are reduced</li>
                                <li>You can add new secondary emails anytime</li>
                            </ul>
                        </div>

                        <!-- Security Check -->
                        <div style='background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #721c24;'>🔒 Security Check Required</h4>
                            <p style='color: #721c24;'>
                                <strong>If you did NOT remove this email:</strong><br>
                                1. Someone may have accessed your account<br>
                                2. Check your recent login activity<br>
                                3. Change your password immediately<br>
                                4. Contact our security team
                            </p>
                        </div>

                        <!-- Next Steps -->
                        <div class='next-steps'>
                            <h3 style='color: #2c3e50;'>📋 Recommended Actions</h3>
                            <p style='color: #6c757d;'>Consider these options:</p>
                            <ul style='color: #6c757d;'>
                                <li>Add a new secondary email for backup notifications</li>
                                <li>Review your account security settings</li>
                                <li>Enable two-factor authentication if not already active</li>
                                <li>Check login history for suspicious activity</li>
                            </ul>
                        </div>

                        <!-- Action Buttons -->
                        <div style='text-align: center; margin: 30px 0;'>
                            <a href='" . $myUrl . "/profile.php?tab=emails' 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;'>
                                Manage Emails
                            </a>
                            <a href='" . $myUrl . "/security.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;'>
                                Security Settings
                            </a>
                        </div>

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

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

    // NOTIFICATION: Email Removal Notification (DELETED EMAIL - if verified)
    if ($verified_status == 1) {
        $mail_subject = "Email Removed from " . $sitename . " Notifications";
        $mail_message = "<!-- Content Section -->
                        <div class='email-content'>
                            <h2 class='greeting'>Notification Update</h2>
                            
                            <p class='message'>
                                This email address has been removed from receiving notifications from <strong>" . $sitename . "</strong>.
                            </p>

                            <!-- Removal Details -->
                            <div class='details-section'>
                                <div class='detail-box'>
                                    <strong>Your Email:</strong> " . htmlspecialchars($secondary_email) . "<br>
                                    <strong>Account Name:</strong> " . $first_name . " " . $last_name . "<br>
                                    <strong>Primary Account Email:</strong> " . htmlspecialchars($primary_email) . "<br>
                                    <strong>Removal Date:</strong> " . date('F j, Y g:i A') . "<br>
                                    <strong>Removal Reason:</strong> Manual removal by account owner<br>
                                    <strong>Service:</strong> AI Trading Platform
                                </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;'>📨 What Happens Now</h4>
                                <ul style='color: #0056b3;'>
                                    <li>You will no longer receive trading notifications</li>
                                    <li>Account security alerts will stop</li>
                                    <li>Performance reports will not be sent</li>
                                    <li>Platform announcements will not be delivered</li>
                                    <li>This is a permanent removal</li>
                                </ul>
                            </div>

                            <!-- Important Notes -->
                            <div style='background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #6c757d;'>ℹ️ Important Information</h4>
                                <p style='color: #6c757d;'>
                                    • This action was initiated by the account owner<br>
                                    • You were removed as a secondary notification email only<br>
                                    • Your email was not used for login or account access<br>
                                    • No personal data has been shared with third parties<br>
                                    • This does not affect any other services you may use
                                </p>
                            </div>

                            <!-- If This Was a Mistake -->
                            <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #856404;'>❓ If This Was Unexpected</h4>
                                <p style='color: #856404;'>
                                    If you believe this removal was a mistake:<br>
                                    • Contact the account owner directly (" . $first_name . " " . $last_name . ")<br>
                                    • Do not reply to this email<br>
                                    • This is an automated notification only
                                </p>
                            </div>

                            <!-- Final Message -->
                            <div class='support-section'>
                                <p class='support-text'>Thank you for being part of our notification system.</p>
                                <p class='support-text'>We hope to serve you again in the future.</p>
                            </div>
                        </div>";

        // Send notification to removed email
        $user_email = $secondary_email;
        $first_name = "User"; // Generic name for external email
        require_once("../proccess/mail_sender.php");
    }

    // NOTIFICATION: Secondary Email Removed (ADMIN)
    $admin_mail_subject = "Secondary Email Removed - User ID: " . $user_id;
    $admin_mail_message = "<!-- Content Section -->
                        <div class='email-content'>
                            <h2 class='greeting'>Secondary Email Removed</h2>
                            
                            <p class='message'>
                                A user has removed a secondary email from their account.
                            </p>

                            <!-- Removal 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>Primary Email:</strong> " . htmlspecialchars($primary_email) . "<br>
                                    <strong>Removed Email:</strong> " . htmlspecialchars($secondary_email) . "<br>
                                    <strong>Removal Date:</strong> " . date('F j, Y g:i A') . "<br>
                                    <strong>User IP Address:</strong> " . $user_ip . "<br>
                                    <strong>Email Added Date:</strong> " . date('F j, Y', strtotime($created_date)) . "<br>
                                    <strong>Verification Status:</strong> " . ($verified_status == 1 ? 'Verified' : 'Not Verified') . "<br>
                                    <strong>Remaining Secondary Emails:</strong> " . $remaining_emails . " / 5<br>
                                    <strong>Action:</strong> User-Initiated Removal
                                </div>
                            </div>

                            <!-- User Email Statistics -->
                            <div class='next-steps'>
                                <h3 style='color: #2c3e50;'>User Email Statistics</h3>
                                <p style='color: #6c757d;'>
                                    <strong>Account Age:</strong> " . 
                                        (isset($email_data['account_created']) ? 
                                         round((time() - strtotime($email_data['account_created'])) / (60 * 60 * 24)) . ' days' : 'N/A') . "<br>
                                    <strong>Total Email Changes (30 days):</strong> " . 
                                        (mysqli_fetch_assoc(mysqli_query($conn, 
                                            "SELECT COUNT(*) as changes FROM user_email_changes 
                                             WHERE user_id='$user_id' AND created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)"))['changes'] ?? 0) . "<br>
                                    <strong>Active Sessions:</strong> " . 
                                        (mysqli_fetch_assoc(mysqli_query($conn, 
                                            "SELECT COUNT(*) as sessions FROM user_sessions 
                                             WHERE user_id='$user_id' AND expires_at > NOW()"))['sessions'] ?? 0) . "
                                </p>
                            </div>

                            <!-- Security Assessment -->
                            <div style='background: " . ($remaining_emails == 0 ? '#fff3cd' : '#d4edda') . "; border: 1px solid " . ($remaining_emails == 0 ? '#ffeaa7' : '#c3e6cb') . "; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: " . ($remaining_emails == 0 ? '#856404' : '#155724') . ";'>" . 
                                    ($remaining_emails == 0 ? '⚠️ Security Concern' : '✅ Normal Activity') . "</h4>
                                <p style='color: " . ($remaining_emails == 0 ? '#856404' : '#155724') . ";'>
                                    " . ($remaining_emails == 0 ? 
                                        '<strong>Warning:</strong> User has no secondary emails.<br>Account recovery options are limited.' : 
                                        'User maintains ' . $remaining_emails . ' secondary email(s) for notifications.') . "
                                </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: bold; margin: 5px;'>
                                    Security Logs
                                </a>
                            </div>

                            <!-- Notes -->
                            <div class='support-section'>
                                <p class='support-text'>This is a standard account update notification.</p>
                                <p class='support-text'>" . 
                                    ($remaining_emails == 0 ? 
                                     'Consider contacting user about security best practices.' : 
                                     'No action required.') . "</p>
                            </div>
                        </div>";

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

    echo json_encode(['success' => true, 'message' => 'Email removed successfully']);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to remove email: ' . mysqli_error($conn)]);
}
?>