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

require_once '../vendor/autoload.php';
use Sonata\GoogleAuthenticator\GoogleAuthenticator;

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

if (!isset($_SESSION['2fa_temp_secret']) || !isset($_SESSION['2fa_temp_backup_codes'])) {
    echo json_encode(['success' => false, 'message' => '2FA setup session expired']);
    exit;
}

// Check session timeout (10 minutes)
if (time() - $_SESSION['2fa_temp_time'] > 600) {
    unset($_SESSION['2fa_temp_secret'], $_SESSION['2fa_temp_backup_codes'], $_SESSION['2fa_temp_time']);
    echo json_encode(['success' => false, 'message' => 'Session expired. Please start over.']);
    exit;
}

$code = $_POST['code'];
$secret = $_SESSION['2fa_temp_secret'];
$backup_codes = $_SESSION['2fa_temp_backup_codes'];

// 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
$user_ip = $_SERVER['REMOTE_ADDR'];
$user_agent = $_SERVER['HTTP_USER_AGENT'];
$device = get_device_type($user_agent);
$location = get_location_info($user_ip);

$g = new GoogleAuthenticator();

if ($g->checkCode($secret, $code)) {
    // Save to database
    $backup_codes_json = json_encode($backup_codes);
    
    // Check if security record exists
    $check_sql = "SELECT id FROM user_security WHERE user_id = '$user_id'";
    $check_result = mysqli_query($conn, $check_sql);
    
    // Get user's security settings before update
    $old_security_data = [];
    if (mysqli_num_rows($check_result) > 0) {
        $old_security_row = mysqli_fetch_assoc($check_result);
        $old_security_data['2fa_enabled'] = $old_security_row['two_factor_enabled'] ?? 0;
    }
    
    if (mysqli_num_rows($check_result) > 0) {
        // Update existing record
        $update_sql = "UPDATE user_security SET 
                       two_factor_enabled = 1, 
                       two_factor_secret = '$secret',
                       backup_codes = '$backup_codes_json',
                       updated_at = NOW()
                       WHERE user_id = '$user_id'";
    } else {
        // Insert new record
        $update_sql = "INSERT INTO user_security 
                       (user_id, two_factor_enabled, two_factor_secret, backup_codes, created_at, updated_at)
                       VALUES ('$user_id', 1, '$secret', '$backup_codes_json', NOW(), NOW())";
    }
    
    if (mysqli_query($conn, $update_sql)) {
        // Clear session
        unset($_SESSION['2fa_temp_secret'], $_SESSION['2fa_temp_backup_codes'], $_SESSION['2fa_temp_time']);
        
        // NOTIFICATION: 2FA Enabled Successfully (USER)
        $mail_subject = "Two-Factor Authentication Enabled Successfully";
        $mail_message = "<!-- Content Section -->
                        <div class='email-content'>
                            <h2 class='greeting'>Hello <span class='user-name'>" . $first_name . "</span>,</h2>
                            
                            <p class='message'>
                                🎉 <strong>Two-Factor Authentication (2FA) has been successfully enabled on your account!</strong><br>
                                Your account security has been significantly enhanced.
                            </p>

                            <!-- Security Details -->
                            <div class='details-section'>
                                <div class='detail-box'>
                                    <strong>Security Action:</strong> 2FA Enabled<br>
                                    <strong>Enabled Date:</strong> " . date('F j, Y g:i A') . "<br>
                                    <strong>Authentication Method:</strong> Google Authenticator (TOTP)<br>
                                    <strong>Security Status:</strong> <span style='color: #28a745; font-weight: bold;'>ACTIVE</span><br>
                                    <strong>Backup Codes Generated:</strong> 8 codes<br>
                                    <strong>Setup Location:</strong> " . $user_ip . " (" . $location . ")<br>
                                    <strong>Device:</strong> " . $device . "<br>
                                    <strong>Browser:</strong> " . get_browser_name($user_agent) . "
                                </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;'>🔐 Enhanced Security Activated</h4>
                                <p style='color: #0056b3;'>
                                    <strong>Now when you log in:</strong><br>
                                    1. Enter your email and password<br>
                                    2. Open Google Authenticator app<br>
                                    3. Enter the 6-digit code<br>
                                    4. Access your account securely
                                </p>
                            </div>

                            <!-- Important: Backup Codes -->
                            <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #856404;'>💾 IMPORTANT: Backup Codes</h4>
                                <p style='color: #856404;'>
                                    <strong>You received 8 backup codes during setup.</strong><br>
                                    These are for emergency access if you lose your phone.<br><br>
                                    <strong style='color: #dc3545;'>❗ Save them in a secure place!</strong><br>
                                    Each code can be used only once.
                                </p>
                            </div>

                            <!-- Security Benefits -->
                            <div class='next-steps'>
                                <h3 style='color: #2c3e50;'>✅ Security Benefits</h3>
                                <p style='color: #6c757d;'>Your account now has:</p>
                                <ul style='color: #6c757d;'>
                                    <li>Protection against unauthorized access</li>
                                    <li>Security even if password is compromised</li>
                                    <li>Alerts for login attempts from new devices</li>
                                    <li>Compliance with security best practices</li>
                                    <li>Enhanced protection for your funds</li>
                                </ul>
                            </div>

                            <!-- What To Do Next -->
                            <div style='background: #d4edda; border: 1px solid #c3e6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #155724;'>📝 Recommended Next Steps</h4>
                                <ol style='color: #155724;'>
                                    <li>Test login with 2FA from another device</li>
                                    <li>Save backup codes in a secure password manager</li>
                                    <li>Enable notifications for new login attempts</li>
                                    <li>Review recent login activity</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 . "/login-activity.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;'>
                                    View Login Activity
                                </a>
                            </div>

                            <!-- Emergency Info -->
                            <div style='background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #721c24;'>🚨 Lost Access to 2FA?</h4>
                                <p style='color: #721c24;'>
                                    <strong>If you lose your phone or backup codes:</strong><br>
                                    1. Use backup codes (if saved)<br>
                                    2. Contact support for account recovery<br>
                                    3. Recovery may take 24-48 hours for security verification<br><br>
                                    <strong>Keep your backup codes safe!</strong>
                                </p>
                            </div>

                            <!-- Support Section -->
                            <div class='support-section'>
                                <p class='support-text'>Need help with 2FA?</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 Enabled (ADMIN - Security Alert)
        $admin_mail_subject = "Security Alert: 2FA Enabled - User ID: " . $user_id;
        $admin_mail_message = "<!-- Content Section -->
                            <div class='email-content'>
                                <h2 class='greeting'>Security Alert: 2FA Enabled</h2>
                                
                                <p class='message'>
                                    A user has successfully enabled Two-Factor Authentication on their account.
                                </p>

                                <!-- Security 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 Action:</strong> 2FA Enabled<br>
                                        <strong>Enabled Date:</strong> " . date('F j, Y g:i A') . "<br>
                                        <strong>User IP Address:</strong> " . $user_ip . "<br>
                                        <strong>Location:</strong> " . $location . "<br>
                                        <strong>Device:</strong> " . $device . "<br>
                                        <strong>Browser:</strong> " . get_browser_name($user_agent) . "<br>
                                        <strong>Previous 2FA Status:</strong> " . ($old_security_data['2fa_enabled'] ? 'Enabled' : 'Disabled') . "<br>
                                        <strong>Backup Codes Generated:</strong> 8 codes
                                    </div>
                                </div>

                                <!-- Security Assessment -->
                                <div class='next-steps'>
                                    <h3 style='color: #2c3e50;'>Security Assessment</h3>
                                    <p style='color: #6c757d;'>
                                        <strong>Risk Level:</strong> <span style='color: #28a745;'>VERY LOW</span><br>
                                        <strong>Action Type:</strong> Security enhancement<br>
                                        <strong>User Behavior:</strong> Proactive security setup<br>
                                        <strong>Account Protection Level:</strong> <span style='color: #28a745;'>HIGH</span><br>
                                        <strong>Account Age:</strong> " . (isset($userData['created_at']) ? 
                                            round((time() - strtotime($userData['created_at'])) / (60 * 60 * 24)) . ' days' : 'N/A') . "<br>
                                        <strong>Total Login Attempts:</strong> " . (isset($userData['login_count']) ? $userData['login_count'] : 0) . "
                                    </p>
                                </div>

                                <!-- Recent Security Activities -->
                                <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>Email Verified:</strong> " . (isset($userData['email_verified']) && $userData['email_verified'] == 1 ? 'Yes' : 'No') . "<br>
                                        <strong>Wallet PIN Set:</strong> " . 
                                            (mysqli_fetch_assoc(mysqli_query($conn, 
                                                "SELECT is_pin_set FROM wallets WHERE user_id='$user_id'"))['is_pin_set'] ?? 0 ? 'Yes' : 'No') . "<br>
                                        <strong>Secondary Emails:</strong> " . 
                                            (mysqli_fetch_assoc(mysqli_query($conn, 
                                                "SELECT COUNT(*) as count FROM user_secondary_emails WHERE user_id='$user_id' AND verified=1"))['count'] ?? 0) . "<br>
                                        <strong>Last Password Change:</strong> " . 
                                            (mysqli_fetch_assoc(mysqli_query($conn, 
                                                "SELECT created_at FROM password_history WHERE user_id='$user_id' ORDER BY created_at DESC LIMIT 1"))['created_at'] ?? 'Never') . "
                                    </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 user has taken proactive security measures.</p>
                                    <p class='support-text'>Account security level: EXCELLENT</p>
                                </div>
                            </div>";

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

        echo json_encode([
            'success' => true,
            'message' => '2FA enabled successfully',
            'backup_codes' => $backup_codes
        ]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Database error: ' . mysqli_error($conn)]);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid verification code']);
}

// Helper functions
function get_device_type($user_agent) {
    if (stripos($user_agent, 'Mobile') !== false) {
        return 'Mobile';
    } elseif (stripos($user_agent, 'Tablet') !== false) {
        return 'Tablet';
    } else {
        return 'Desktop';
    }
}

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 get_location_info($ip) {
    // Simple implementation - in production use IP geolocation service
    if ($ip == '127.0.0.1' || $ip == '::1') {
        return 'Localhost/Development';
    }
    
    // You could implement IP geolocation API here
    // For now return generic info
    return 'IP: ' . $ip;
}
?>