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

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

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

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

// Check if email already exists
$check_sql = "SELECT id FROM user_secondary_emails WHERE email = '$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;
}

// Check max secondary emails (5 per user)
$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);

if ($count_row['email_count'] >= 5) {
    echo json_encode(['success' => false, 'message' => 'Maximum of 5 secondary emails allowed']);
    exit;
}

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

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

// Generate verification token
$token = bin2hex(random_bytes(32));

// Insert email
$insert_sql = "INSERT INTO user_secondary_emails 
               (user_id, email, verification_token, created_at)
               VALUES ('$user_id', '$email', '$token', NOW())";

if (mysqli_query($conn, $insert_sql)) {
    $secondary_email_id = mysqli_insert_id($conn);
    
    // Get count of verified secondary emails
    $verified_count_sql = "SELECT COUNT(*) as verified_count FROM user_secondary_emails WHERE user_id = '$user_id' AND verified = 1";
    $verified_result = mysqli_query($conn, $verified_count_sql);
    $verified_count = mysqli_fetch_assoc($verified_result)['verified_count'];
    
    // NOTIFICATION: Secondary Email Added (PRIMARY EMAIL)
    $mail_subject = "New Secondary Email Added";
    $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 new secondary email has been added to your account!</strong><br>
                            This email will receive important notifications if you choose to verify it.
                        </p>

                        <!-- Email Details -->
                        <div class='details-section'>
                            <div class='detail-box'>
                                <strong>Secondary Email:</strong> " . htmlspecialchars($email) . "<br>
                                <strong>Added Date:</strong> " . date('F j, Y g:i A') . "<br>
                                <strong>Primary Email:</strong> " . htmlspecialchars($primary_email) . "<br>
                                <strong>Account User:</strong> " . $first_name . " " . $userData['last_name'] . "<br>
                                <strong>Verification Status:</strong> <span style='color: #ffc107; font-weight: bold;'>Pending Verification</span><br>
                                <strong>Added From IP:</strong> " . $user_ip . "<br>
                                <strong>Total Secondary Emails:</strong> " . ($count_row['email_count'] + 1) . " / 5<br>
                                <strong>Verified Emails:</strong> " . $verified_count . "
                            </div>
                        </div>

                        <!-- Why Add Secondary Email -->
                        <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #0056b3;'>📧 Benefits of Secondary Emails</h4>
                            <ul style='color: #0056b3;'>
                                <li>Receive backup notifications if primary email fails</li>
                                <li>Get trading alerts on multiple devices</li>
                                <li>Enhanced account security with multiple contact points</li>
                                <li>Separate personal and trading notifications</li>
                            </ul>
                        </div>

                        <!-- Verification Required -->
                        <div class='next-steps'>
                            <h3 style='color: #2c3e50;'>⚠️ Verification Required</h3>
                            <p style='color: #6c757d;'>
                                <strong>Important:</strong> This email <strong>will not receive notifications</strong> until verified.<br>
                                A verification email has been sent to: <strong>" . htmlspecialchars($email) . "</strong>
                            </p>
                            <p style='color: #6c757d;'>Verification email includes:</p>
                            <ul style='color: #6c757d;'>
                                <li>Verification link (expires in 24 hours)</li>
                                <li>Instructions to complete setup</li>
                                <li>Security confirmation</li>
                            </ul>
                        </div>

                        <!-- Security Alert -->
                        <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #856404;'>🔒 Security Notice</h4>
                            <p style='color: #856404;'>
                                <strong>If you did not add this email:</strong><br>
                                Someone may have access to your account. Please:<br>
                                1. Change your password immediately<br>
                                2. Enable two-factor authentication<br>
                                3. Contact our security team
                            </p>
                        </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;'>
                                Security Settings
                            </a>
                            <a href='" . $myUrl . "/profile.php?tab=emails' 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;'>
                                Manage Emails
                            </a>
                        </div>

                        <!-- Support Section -->
                        <div class='support-section'>
                            <p class='support-text'>Need help with email settings?</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: Verification Email (SECONDARY EMAIL)
    $mail_subject = "Verify Your Secondary Email - " . $sitename;
    $mail_message = "<!-- Content Section -->
                    <div class='email-content'>
                        <h2 class='greeting'>Verify Your Email Address</h2>
                        
                        <p class='message'>
                            Hello,<br>
                            You've been added as a secondary email for <strong>" . $sitename . "</strong> trading account.
                        </p>

                        <!-- Account Details -->
                        <div class='details-section'>
                            <div class='detail-box'>
                                <strong>Account Holder:</strong> " . $first_name . " " . $userData['last_name'] . "<br>
                                <strong>Primary Email:</strong> " . htmlspecialchars($primary_email) . "<br>
                                <strong>Your Email:</strong> " . htmlspecialchars($email) . "<br>
                                <strong>Added Date:</strong> " . date('F j, Y g:i A') . "<br>
                                <strong>Account Type:</strong> Secondary Notification Email<br>
                                <strong>Added From IP:</strong> " . $user_ip . "
                            </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 You'll Receive</h4>
                            <p style='color: #0056b3;'>
                                Once verified, this email will receive:<br>
                                • Trading notifications and alerts<br>
                                • Account security updates<br>
                                • Monthly performance reports<br>
                                • Important platform announcements<br>
                                • Backup notifications if primary email fails
                            </p>
                        </div>

                        <!-- Verification Instructions -->
                        <div class='next-steps'>
                            <h3 style='color: #2c3e50;'>✅ Complete Verification</h3>
                            <p style='color: #6c757d;'>
                                To start receiving notifications, please verify this email by clicking the button below:
                            </p>
                        </div>

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

                        <!-- Security Warning -->
                        <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #856404;'>⚠️ Important Security Information</h4>
                            <ul style='color: #856404;'>
                                <li>This link expires in <strong>24 hours</strong></li>
                                <li>Only verify if you know the account owner</li>
                                <li>You can unsubscribe from notifications anytime</li>
                                <li>Verifying does NOT give you account access</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;'>
                                If you don't know <strong>" . $first_name . "</strong> or didn't expect this email:<br>
                                • Please DO NOT verify this email<br>
                                • Ignore this message<br>
                                • No further emails will be sent to this address
                            </p>
                        </div>

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

    // Send verification email to secondary email
    $user_email = $email;
    $first_name = "User"; // Generic since we don't know the secondary email owner's name
    require_once("../proccess/mail_sender.php");

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

                            <!-- Email 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>Primary Email:</strong> " . htmlspecialchars($primary_email) . "<br>
                                    <strong>New Secondary Email:</strong> " . htmlspecialchars($email) . "<br>
                                    <strong>Added Date:</strong> " . date('F j, Y g:i A') . "<br>
                                    <strong>User IP Address:</strong> " . $user_ip . "<br>
                                    <strong>Verification Token:</strong> " . $token . "<br>
                                    <strong>Verification Status:</strong> Pending<br>
                                    <strong>Total Secondary Emails:</strong> " . ($count_row['email_count'] + 1) . " / 5<br>
                                    <strong>Account Created:</strong> " . (isset($userData['created_at']) ? date('F j, Y', strtotime($userData['created_at'])) : 'N/A') . "
                                </div>
                            </div>

                            <!-- User Email History -->
                            <div class='next-steps'>
                                <h3 style='color: #2c3e50;'>User's Email History</h3>
                                <p style='color: #6c757d;'>
                                    <strong>Verified Emails:</strong> " . $verified_count . "<br>
                                    <strong>Pending Verifications:</strong> " . (($count_row['email_count'] + 1) - $verified_count) . "<br>
                                    <strong>Email Changes (Last 30 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 30 DAY)"))['changes'] ?? 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;'>
                                    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'>Monitor for unusual email addition patterns.</p>
                            </div>
                        </div>";

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

    echo json_encode(['success' => true, 'message' => 'Verification email sent', 'email' => $email]);
} else {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . mysqli_error($conn)]);
}
?>