<?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;
}

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

// Get 2FA secret
$sql = "SELECT two_factor_secret FROM user_security WHERE user_id = '$user_id'";
$result = mysqli_query($conn, $sql);
$security = mysqli_fetch_assoc($result);

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

$secret = $security['two_factor_secret'];
$code = $_POST['code'];

$g = new GoogleAuthenticator();

if ($g->checkCode($secret, $code)) {
    // Get last 2FA enabled date
    $history_sql = "SELECT created_at FROM security_logs 
                   WHERE user_id = '$user_id' AND action = '2fa_enabled' 
                   ORDER BY created_at DESC LIMIT 1";
    $history_result = mysqli_query($conn, $history_sql);
    $history_data = mysqli_fetch_assoc($history_result);
    $last_enabled_date = $history_data ? date('F j, Y', strtotime($history_data['created_at'])) : 'Unknown';
    
    $update_sql = "UPDATE user_security SET 
                   two_factor_enabled = 0, 
                   two_factor_secret = NULL,
                   backup_codes = NULL,
                   updated_at = NOW()
                   WHERE user_id = '$user_id'";
    
    if (mysqli_query($conn, $update_sql)) {
        // Record security log
        $log_sql = "INSERT INTO security_logs 
                    (user_id, action, ip_address, user_agent, details, created_at)
                    VALUES 
                    ('$user_id', '2fa_disabled', '$user_ip', '$user_agent', 
                     'Two-factor authentication disabled via ' . '$device' . ' (' . '$browser' . ')', NOW())";
        mysqli_query($conn, $log_sql);
        
        // NOTIFICATION: 2FA Disabled (USER - CRITICAL SECURITY ALERT)
        $mail_subject = "⚠️ CRITICAL: Two-Factor Authentication Disabled";
        $mail_message = "<!-- Content Section -->
                        <div class='email-content'>
                            <h2 class='greeting' style='color: #dc3545;'>Security Alert: 2FA Disabled</h2>
                            
                            <div style='background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 8px; padding: 20px; margin: 20px 0;'>
                                <h4 style='color: #721c24;'>⚠️ IMPORTANT SECURITY NOTICE</h4>
                                <p style='color: #721c24;'>
                                    <strong>Two-factor authentication has been disabled on your account!</strong><br>
                                    This reduces your account security significantly.
                                </p>
                            </div>

                            <!-- Security Details -->
                            <div class='details-section'>
                                <div class='detail-box'>
                                    <strong>Security Action:</strong> Two-Factor Authentication DISABLED<br>
                                    <strong>Date & Time:</strong> " . date('F j, Y g:i A') . "<br>
                                    <strong>Action Performed By:</strong> " . $first_name . " " . $last_name . "<br>
                                    <strong>Account Email:</strong> " . $email . "<br>
                                    <strong>Device Used:</strong> " . $device . " (" . $browser . ")<br>
                                    <strong>IP Address:</strong> " . $user_ip . "<br>
                                    <strong>Location:</strong> " . get_location_from_ip($user_ip) . "<br>
                                    <strong>2FA Last Enabled:</strong> " . $last_enabled_date . "<br>
                                    <strong>New Security Status:</strong> <span style='color: #dc3545; font-weight: bold;'>REDUCED SECURITY</span>
                                </div>
                            </div>

                            <!-- Security Risk Warning -->
                            <div style='background: #f8d7da; border: 2px solid #dc3545; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #721c24;'>🔓 SECURITY RISK INCREASED</h4>
                                <p style='color: #721c24;'>
                                    <strong>Without 2FA, your account is vulnerable to:</strong><br>
                                    • Unauthorized access if password is compromised<br>
                                    • Phishing attacks<br>
                                    • Account takeover<br>
                                    • Unauthorized trading activities
                                </p>
                            </div>

                            <!-- Immediate Actions Required -->
                            <div class='next-steps'>
                                <h3 style='color: #2c3e50;'>🚨 Recommended Actions</h3>
                                <p style='color: #6c757d;'><strong>If you disabled 2FA:</strong></p>
                                <ol style='color: #6c757d;'>
                                    <li>Consider re-enabling 2FA for maximum security</li>
                                    <li>Use app-based authentication (Google Authenticator/Authy)</li>
                                    <li>Save backup codes in a secure location</li>
                                    <li>Enable email notifications for all account activities</li>
                                </ol>
                                
                                <p style='color: #6c757d;'><strong>If you DID NOT disable 2FA:</strong></p>
                                <ol style='color: #dc3545;'>
                                    <li><strong>Change your password IMMEDIATELY</strong></li>
                                    <li><strong>Contact our security team NOW</strong></li>
                                    <li>Review recent account activities</li>
                                    <li>Check for unauthorized withdrawals or trades</li>
                                </ol>
                            </div>

                            <!-- Re-enable 2FA -->
                            <div style='background: #d4edda; border: 1px solid #c3e6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #155724;'>🔒 Re-enable Two-Factor Authentication</h4>
                                <p style='color: #155724;'>
                                    For maximum account security, we strongly recommend re-enabling 2FA.
                                </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 . "/enable-2fa.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #28a745; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                    Re-enable 2FA
                                </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: bold; margin: 5px;'>
                                    🔥 Report Security Issue
                                </a>
                            </div>

                            <!-- Security Team Contact -->
                            <div class='support-section'>
                                <p class='support-text'><strong>Security Team Contact:</strong></p>
                                <p class='support-text'>
                                    📧 Email: security@" . parse_url($myUrl, PHP_URL_HOST) . "<br>
                                    ⚡ Emergency: +1-XXX-XXX-XXXX<br>
                                    🕒 24/7 Security Monitoring
                                </p>
                                <a href='" . $myUrl . "/contact.php?emergency=security' class='support-link'>Contact Security Team Immediately</a>
                            </div>
                        </div>";

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

        // NOTIFICATION: 2FA Disabled (ADMIN - CRITICAL SECURITY ALERT)
        $admin_mail_subject = "🚨 CRITICAL: 2FA Disabled - User ID: " . $user_id;
        $admin_mail_message = "<!-- Content Section -->
                            <div class='email-content'>
                                <h2 class='greeting' style='color: #dc3545;'>CRITICAL SECURITY ALERT</h2>
                                
                                <div style='background: #f8d7da; border: 2px solid #dc3545; border-radius: 8px; padding: 20px; margin: 20px 0;'>
                                    <h4 style='color: #721c24;'>⚠️ TWO-FACTOR AUTHENTICATION DISABLED</h4>
                                    <p style='color: #721c24;'>
                                        <strong>High-risk security change detected!</strong><br>
                                        User has disabled two-factor authentication.
                                    </p>
                                </div>

                                <!-- User & 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>Action:</strong> Two-Factor Authentication DISABLED<br>
                                        <strong>Date & Time:</strong> " . date('F j, Y g:i A') . "<br>
                                        <strong>User IP Address:</strong> " . $user_ip . "<br>
                                        <strong>Location:</strong> " . get_location_from_ip($user_ip) . "<br>
                                        <strong>Device:</strong> " . $device . "<br>
                                        <strong>Browser:</strong> " . $browser . "<br>
                                        <strong>2FA Last Enabled:</strong> " . $last_enabled_date . "<br>
                                        <strong>Security Risk Level:</strong> <span style='color: #dc3545; font-weight: bold;'>HIGH</span><br>
                                        <strong>Account Balance:</strong> $" . 
                                            (mysqli_fetch_assoc(mysqli_query($conn, 
                                                "SELECT balance FROM wallets WHERE user_id='$user_id'"))['balance'] ?? '0.00') . "
                                    </div>
                                </div>

                                <!-- User Account Information -->
                                <div class='next-steps'>
                                    <h3 style='color: #2c3e50;'>User Account Summary</h3>
                                    <p style='color: #6c757d;'>
                                        <strong>Account Created:</strong> " . 
                                            (isset($userData['created_at']) ? date('F j, Y', strtotime($userData['created_at'])) : 'N/A') . "<br>
                                        <strong>Active Bots:</strong> " . 
                                            (mysqli_fetch_assoc(mysqli_query($conn, 
                                                "SELECT COUNT(*) as active FROM user_bot_subscriptions 
                                                 WHERE user_id='$user_id' AND status='active'"))['active'] ?? 0) . "<br>
                                        <strong>Total Deposits:</strong> $" . 
                                            (mysqli_fetch_assoc(mysqli_query($conn, 
                                                "SELECT SUM(amount) as total FROM transactions 
                                                 WHERE user_id='$user_id' AND type='deposit' AND status='completed'"))['total'] ?? '0.00') . "<br>
                                        <strong>Recent Logins (7 days):</strong> " . 
                                            (mysqli_fetch_assoc(mysqli_query($conn, 
                                                "SELECT COUNT(*) as logins FROM login_logs 
                                                 WHERE user_id='$user_id' AND created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)"))['logins'] ?? 0) . "
                                    </p>
                                </div>

                                <!-- Risk Assessment -->
                                <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                    <h4 style='color: #856404;'>📊 Risk Assessment</h4>
                                    <p style='color: #856404;'>
                                        <strong>Risk Factors:</strong><br>
                                        • 2FA disabled reduces account security by 99.9%<br>
                                        • Account now vulnerable to password-only attacks<br>
                                        • High-value trading account<br>
                                        • Requires immediate monitoring<br><br>
                                        <strong>Recommended Action:</strong> Monitor account activity closely for 48 hours
                                    </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: #dc3545; color: white; text-decoration: none; border-radius: 6px; font-weight: bold; margin: 5px;'>
                                        🔍 Investigate Security Logs
                                    </a>
                                    <a href='" . $myUrl . "/admin/transactions.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;'>
                                        Monitor Transactions
                                    </a>
                                </div>

                                <!-- Security Checklist -->
                                <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                    <h4 style='color: #0056b3;'>✅ Security Checklist</h4>
                                    <ul style='color: #0056b3;'>
                                        <li>Monitor for unusual login attempts</li>
                                        <li>Check for suspicious withdrawals</li>
                                        <li>Review recent password changes</li>
                                        <li>Verify email change requests</li>
                                        <li>Monitor trading activities</li>
                                    </ul>
                                </div>

                                <!-- Support Section -->
                                <div class='support-section'>
                                    <p class='support-text'>This is a CRITICAL security alert.</p>
                                    <p class='support-text'>Account requires enhanced monitoring for 48 hours.</p>
                                </div>
                            </div>";

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

        echo json_encode(['success' => true, 'message' => '2FA disabled successfully']);
    } 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_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;
}

function get_location_from_ip($ip) {
    if ($ip == '127.0.0.1' || $ip == '::1') {
        return 'Localhost';
    }
    return 'IP Location Service Required';
}
?>