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

// Check if 2FA is enabled
$sql = "SELECT two_factor_enabled FROM user_security WHERE user_id = '$user_id'";
$result = mysqli_query($conn, $sql);
$security = mysqli_fetch_assoc($result);

if (!$security || !$security['two_factor_enabled']) {
    echo json_encode(['success' => false, 'message' => '2FA not enabled']);
    exit;
}

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

// Get IP address and device info for security notification
$user_ip = $_SERVER['REMOTE_ADDR'];
$user_agent = $_SERVER['HTTP_USER_AGENT'];
$timestamp = date('F j, Y g:i A');

// Generate new backup codes
$backup_codes = [];
$codes_html = '';
for ($i = 0; $i < 10; $i++) {
    $code = strtoupper(bin2hex(random_bytes(4))); // 8-character codes
    $backup_codes[] = $code;
    $codes_html .= "<div style='padding: 8px 12px; margin: 5px; background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 4px; font-family: monospace; font-weight: bold; color: #198754;'>" . $code . "</div>";
}

$backup_codes_json = mysqli_real_escape_string($conn, json_encode($backup_codes));

// Get old backup codes count before update
$old_codes_sql = "SELECT backup_codes FROM user_security WHERE user_id = '$user_id'";
$old_result = mysqli_query($conn, $old_codes_sql);
$old_data = mysqli_fetch_assoc($old_result);
$old_codes_count = 0;
if ($old_data['backup_codes']) {
    $old_codes = json_decode($old_data['backup_codes'], true);
    $old_codes_count = is_array($old_codes) ? count($old_codes) : 0;
}

$update_sql = "UPDATE user_security SET 
               backup_codes = '$backup_codes_json',
               backup_codes_generated_at = NOW(),
               updated_at = NOW()
               WHERE user_id = '$user_id'";

if (mysqli_query($conn, $update_sql)) {
    
    // NOTIFICATION: 2FA Backup Codes Generated (USER)
    $mail_subject = "2FA Backup Codes Generated - Security Alert";
    $mail_message = "<!-- Content Section -->
                    <div class='email-content'>
                        <h2 class='greeting'>Hello <span class='user-name'>" . $first_name . "</span>,</h2>
                        
                        <p class='message'>
                            🔐 <strong>New Two-Factor Authentication backup codes have been generated!</strong><br>
                            Your previous backup codes are no longer valid.
                        </p>

                        <!-- Security Details -->
                        <div class='details-section'>
                            <div class='detail-box'>
                                <strong>Security Action:</strong> 2FA Backup Codes Regenerated<br>
                                <strong>Date & Time:</strong> " . $timestamp . "<br>
                                <strong>User IP Address:</strong> " . $user_ip . "<br>
                                <strong>Device:</strong> " . (is_mobile_device() ? 'Mobile' : 'Desktop') . "<br>
                                <strong>Action Taken By:</strong> " . $first_name . " " . $last_name . "<br>
                                <strong>Email:</strong> " . $email . "<br>
                                <strong>2FA Status:</strong> <span style='color: #28a745; font-weight: bold;'>ENABLED</span><br>
                                <strong>Previous Codes Invalidated:</strong> " . $old_codes_count . " codes
                            </div>
                        </div>

                        <!-- Your New Backup Codes -->
                        <div style='background: #f0f9ff; border: 2px solid #bae6fd; border-radius: 8px; padding: 25px; margin: 30px 0;'>
                            <h3 style='color: #0369a1; text-align: center; margin-bottom: 20px;'>
                                🔑 YOUR NEW BACKUP CODES
                            </h3>
                            <div style='text-align: center; font-size: 14px; color: #64748b; margin-bottom: 20px;'>
                                Each code can be used once when you can't access your 2FA app
                            </div>
                            <div style='display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px;'>
                                " . $codes_html . "
                            </div>
                            <div style='text-align: center; margin-top: 20px; font-size: 12px; color: #64748b;'>
                                ⚠️ Keep these codes secure and private!
                            </div>
                        </div>

                        <!-- IMPORTANT SECURITY WARNING -->
                        <div style='background: #fef3c7; border: 2px solid #fcd34d; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #92400e; text-align: center;'>⚠️ CRITICAL SECURITY INFORMATION</h4>
                            <ul style='color: #92400e;'>
                                <li><strong>STORE THESE CODES SECURELY:</strong> Save in a password manager or print them</li>
                                <li><strong>DO NOT SHARE:</strong> These codes provide access to your account</li>
                                <li><strong>ONE-TIME USE:</strong> Each code works only once</li>
                                <li><strong>PREVIOUS CODES INVALIDATED:</strong> Old codes no longer work</li>
                                <li><strong>REGENERATE IF LOST:</strong> You can generate new codes anytime</li>
                            </ul>
                        </div>

                        <!-- How to Use Backup Codes -->
                        <div class='next-steps'>
                            <h3 style='color: #2c3e50;'>📝 How to Use Backup Codes</h3>
                            <p style='color: #6c757d;'>When your 2FA app is unavailable:</p>
                            <ol style='color: #6c757d;'>
                                <li>Go to login page and enter your email/password</li>
                                <li>When asked for 2FA code, click "Use backup code"</li>
                                <li>Enter one of the codes above</li>
                                <li>That code will be invalidated after use</li>
                                <li>Generate new codes if you run low</li>
                            </ol>
                        </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' 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;'>
                                Account Profile
                            </a>
                        </div>

                        <!-- Security Alert -->
                        <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 did NOT generate these backup codes:<br>
                                1. Someone may have access to your account<br>
                                2. Change your password immediately<br>
                                3. Review account activity<br>
                                4. Contact support immediately
                            </p>
                        </div>

                        <!-- Support Section -->
                        <div class='support-section'>
                            <p class='support-text'>Need help with 2FA or backup codes?</p>
                            <a href='" . $myUrl . "/support.php?category=security' class='support-link'>Contact Security Support</a>
                        </div>
                    </div>";

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

    // NOTIFICATION: 2FA Backup Codes Generated (ADMIN - Security Alert)
    $admin_mail_subject = "Security Alert: 2FA Backup Codes Regenerated - User ID: " . $user_id;
    $admin_mail_message = "<!-- Content Section -->
                        <div class='email-content'>
                            <h2 class='greeting'>Security Alert: 2FA Backup Codes Regenerated</h2>
                            
                            <p class='message'>
                                A user has generated new Two-Factor Authentication backup codes.
                            </p>

                            <!-- Security Event 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>User Email:</strong> " . $email . "<br>
                                    <strong>Security Event:</strong> 2FA Backup Codes Regeneration<br>
                                    <strong>Date & Time:</strong> " . $timestamp . "<br>
                                    <strong>User IP Address:</strong> " . $user_ip . "<br>
                                    <strong>User Agent:</strong> " . htmlspecialchars(substr($user_agent, 0, 100)) . "<br>
                                    <strong>Device Type:</strong> " . (is_mobile_device() ? 'Mobile' : 'Desktop') . "<br>
                                    <strong>2FA Status:</strong> Enabled<br>
                                    <strong>New Codes Generated:</strong> 10 backup codes<br>
                                    <strong>Previous Codes Invalidated:</strong> " . $old_codes_count . " codes<br>
                                    <strong>Account Age:</strong> " . (isset($userData['created_at']) ? 
                                        round((time() - strtotime($userData['created_at'])) / (60 * 60 * 24)) . ' days' : 'N/A') . "
                                </div>
                            </div>

                            <!-- Security Risk Assessment -->
                            <div class='next-steps'>
                                <h3 style='color: #2c3e50;'>Security Assessment</h3>
                                <p style='color: #6c757d;'>
                                    <strong>Risk Level:</strong> <span style='color: #ffc107;'>MEDIUM</span><br>
                                    <strong>Event Type:</strong> Security configuration change<br>
                                    <strong>Normal Behavior:</strong> Users may regenerate codes if lost<br>
                                    <strong>Frequency:</strong> " . 
                                        (mysqli_fetch_assoc(mysqli_query($conn, 
                                            "SELECT COUNT(*) as count FROM security_logs 
                                             WHERE user_id='$user_id' AND action='backup_codes_regenerated'
                                             AND created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)"))['count'] ?? 0) . " times in last 30 days<br>
                                    <strong>Last 2FA Login:</strong> " . 
                                        (mysqli_fetch_assoc(mysqli_query($conn, 
                                            "SELECT MAX(login_time) as last_2fa FROM user_logins 
                                             WHERE user_id='$user_id' AND two_factor_used=1"))['last_2fa'] ?? 'Never') . "
                                </p>
                            </div>

                            <!-- User Security Profile -->
                            <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #0056b3;'>📊 User Security Profile</h4>
                                <p style='color: #0056b3;'>
                                    <strong>Account Status:</strong> " . (isset($userData['status']) ? ucfirst($userData['status']) : 'Active') . "<br>
                                    <strong>Email Verified:</strong> " . (isset($userData['email_verified']) && $userData['email_verified'] == 1 ? 'Yes' : 'No') . "<br>
                                    <strong>Last Password Change:</strong> " . 
                                        (mysqli_fetch_assoc(mysqli_query($conn, 
                                            "SELECT MAX(created_at) as last_change FROM security_logs 
                                             WHERE user_id='$user_id' AND action='password_change'"))['last_change'] ?? 'Never') . "<br>
                                    <strong>Failed Login Attempts (24h):</strong> " . 
                                        (mysqli_fetch_assoc(mysqli_query($conn, 
                                            "SELECT COUNT(*) as attempts FROM failed_logins 
                                             WHERE user_id='$user_id' AND attempt_time >= DATE_SUB(NOW(), INTERVAL 24 HOUR)"))['attempts'] ?? 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>

                            <!-- Recommended Action -->
                            <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #856404;'>💡 Recommended Action</h4>
                                <p style='color: #856404;'>
                                    <strong>Monitor this user</strong> if:<br>
                                    • Multiple backup code regenerations in short period<br>
                                    • Codes regenerated from new IP/location<br>
                                    • User reports suspicious activity<br>
                                    • High failed login attempts
                                </p>
                            </div>

                            <!-- Support Section -->
                            <div class='support-section'>
                                <p class='support-text'>This is an automated security notification.</p>
                                <p class='support-text'>Investigate if suspicious activity is suspected.</p>
                            </div>
                        </div>";

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

    // Log the security event
    $log_sql = "INSERT INTO security_logs 
                (user_id, action, ip_address, user_agent, details, created_at)
                VALUES 
                ('$user_id', 'backup_codes_regenerated', '$user_ip', '" . mysqli_real_escape_string($conn, $user_agent) . "',
                 'Generated 10 new backup codes, invalidated $old_codes_count old codes', NOW())";
    mysqli_query($conn, $log_sql);

    echo json_encode([
        'success' => true,
        'message' => 'Backup codes generated',
        'codes' => $backup_codes
    ]);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to generate backup codes: ' . mysqli_error($conn)]);
}

// Helper function to detect mobile device
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;
}
?>