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

require_once '../vendor/autoload.php'; // For Google Authenticator library

use Sonata\GoogleAuthenticator\GoogleAuthenticator;
use Sonata\GoogleAuthenticator\GoogleQrUrl;

// Check if 2FA already enabled
$check_sql = "SELECT two_factor_enabled, two_factor_secret FROM user_security WHERE user_id = '$user_id'";
$check_result = mysqli_query($conn, $check_sql);
$security = mysqli_fetch_assoc($check_result);

if ($security && $security['two_factor_enabled']) {
    echo json_encode(['success' => false, 'message' => '2FA is already 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 for security notification
$user_ip = $_SERVER['REMOTE_ADDR'];
$user_agent = $_SERVER['HTTP_USER_AGENT'];

// Generate secret
$g = new GoogleAuthenticator();
$secret = $g->generateSecret();

// Generate QR code URL
$issuer = 'AI Trading Platform';
$account = $email;
$qrCode = GoogleQrUrl::generate($account, $secret, $issuer);

// Generate backup codes
$backup_codes = [];
for ($i = 0; $i < 10; $i++) {
    $backup_codes[] = strtoupper(bin2hex(random_bytes(4))); // 8-character codes
}

// Generate one-time verification code (6 digits)
$verification_code = str_pad(random_int(0, 999999), 6, '0', STR_PAD_LEFT);

// Save secret temporarily (will be saved permanently after verification)
$_SESSION['2fa_temp_secret'] = $secret;
$_SESSION['2fa_temp_backup_codes'] = $backup_codes;
$_SESSION['2fa_temp_time'] = time();
$_SESSION['2fa_verification_code'] = $verification_code;

// NOTIFICATION: 2FA Setup Initiated (USER)
$mail_subject = "Two-Factor Authentication Setup Started";
$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) setup has been initiated!</strong><br>
                        You're taking an important step to secure your AI trading account.
                    </p>

                    <!-- Setup Details -->
                    <div class='details-section'>
                        <div class='detail-box'>
                            <strong>Security Action:</strong> 2FA Setup Initiation<br>
                            <strong>Date & Time:</strong> " . date('F j, Y g:i A') . "<br>
                            <strong>Initiated From IP:</strong> " . $user_ip . "<br>
                            <strong>Device/Browser:</strong> " . substr($user_agent, 0, 50) . "...<br>
                            <strong>Current Status:</strong> <span style='color: #ffc107; font-weight: bold;'>Setup In Progress</span><br>
                            <strong>Setup Reference:</strong> 2FA-" . date('YmdHis') . "<br>
                            <strong>Verification Code:</strong> <span style='font-size: 24px; font-weight: bold; color: #2F2CD8; letter-spacing: 2px;'>" . $verification_code . "</span>
                        </div>
                    </div>

                    <!-- Why 2FA is Important -->
                    <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                        <h4 style='color: #0056b3;'>🔒 Why Enable 2FA?</h4>
                        <p style='color: #0056b3;'>
                            2FA adds an extra layer of security to your account:<br>
                            • <strong>99.9% protection</strong> against unauthorized access<br>
                            • Required for withdrawals over $1000<br>
                            • Protects your trading funds and personal data<br>
                            • Industry-standard security practice
                        </p>
                    </div>

                    <!-- Setup Instructions -->
                    <div class='next-steps'>
                        <h3 style='color: #2c3e50;'>📱 Next Steps to Complete Setup</h3>
                        <ol style='color: #6c757d;'>
                            <li><strong>Download Authenticator App:</strong> Google Authenticator or Authy</li>
                            <li><strong>Scan QR Code:</strong> In your account security settings</li>
                            <li><strong>Enter Verification Code:</strong> From the app</li>
                            <li><strong>Save Backup Codes:</strong> Download or write them down</li>
                            <li><strong>Complete Setup:</strong> Click verify in your account</li>
                        </ol>
                    </div>

                    <!-- Verification Code Instructions -->
                    <div style='background: #d4edda; border: 1px solid #c3e6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                        <h4 style='color: #155724;'>🔑 Your Verification Code</h4>
                        <p style='color: #155724; text-align: center; font-size: 20px; font-weight: bold;'>
                            " . $verification_code . "
                        </p>
                        <p style='color: #155724; text-align: center;'>
                            Use this code during setup if requested<br>
                            <small>Expires in 10 minutes</small>
                        </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><strong>NEVER share your QR code or secret key</strong></li>
                            <li><strong>Save backup codes in a secure location</strong></li>
                            <li><strong>Each backup code can only be used once</strong></li>
                            <li><strong>Setup must be completed within 10 minutes</strong></li>
                            <li><strong>If you didn't start this setup, change your password immediately</strong></li>
                        </ul>
                    </div>

                    <!-- Action Buttons -->
                    <div style='text-align: center; margin: 30px 0;'>
                        <a href='" . $myUrl . "/security.php?tab=2fa' 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;'>
                            Complete 2FA Setup
                        </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 Information -->
                    <div class='support-section'>
                        <p class='support-text'>Need help with 2FA setup?</p>
                        <a href='" . $myUrl . "/support.php?category=security' class='support-link'>Contact Security Support</a><br>
                        <small>Setup guides available in our Help Center</small>
                    </div>
                </div>";

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

// NOTIFICATION: 2FA Setup Initiated (ADMIN - Security Alert)
$admin_mail_subject = "Security Alert: 2FA Setup Initiated - User ID: " . $user_id;
$admin_mail_message = "<!-- Content Section -->
                    <div class='email-content'>
                        <h2 class='greeting'>2FA Setup Initiated</h2>
                        
                        <p class='message'>
                            A user has started setting up Two-Factor Authentication (2FA) on their account.
                        </p>

                        <!-- Setup 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> 2FA Setup Initiation<br>
                                <strong>Date & Time:</strong> " . date('F j, Y g:i A') . "<br>
                                <strong>User IP Address:</strong> " . $user_ip . "<br>
                                <strong>User Agent:</strong> " . htmlspecialchars(substr($user_agent, 0, 100)) . "<br>
                                <strong>Setup Reference:</strong> 2FA-" . date('YmdHis') . "<br>
                                <strong>Current 2FA Status:</strong> Disabled (Setting up)<br>
                                <strong>Temporary Secret Generated:</strong> Yes<br>
                                <strong>Backup Codes Generated:</strong> 10 codes
                            </div>
                        </div>

                        <!-- User Security Profile -->
                        <div class='next-steps'>
                            <h3 style='color: #2c3e50;'>User Security Profile</h3>
                            <p style='color: #6c757d;'>
                                <strong>Account Age:</strong> " . (isset($userData['created_at']) ? 
                                    round((time() - strtotime($userData['created_at'])) / (60 * 60 * 24)) . ' days' : 'N/A') . "<br>
                                <strong>Email Verified:</strong> " . (isset($userData['email_verified']) && $userData['email_verified'] == 1 ? 'Yes' : 'No') . "<br>
                                <strong>Last Password Change:</strong> " . (isset($userData['password_changed']) ? 
                                    date('F j, Y', strtotime($userData['password_changed'])) : 'N/A') . "<br>
                                <strong>Wallet PIN Set:</strong> " . (isset($userData['has_pin']) && $userData['has_pin'] == 1 ? '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) . "
                            </p>
                        </div>

                        <!-- Security Assessment -->
                        <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #0056b3;'>🔍 Security Assessment</h4>
                            <p style='color: #0056b3;'>
                                <strong>Risk Level:</strong> <span style='color: #28a745;'>VERY LOW</span><br>
                                <strong>Action Type:</strong> Security enhancement (positive)<br>
                                <strong>User Behavior:</strong> Proactive security measure<br>
                                <strong>Setup Completion Required:</strong> Within 10 minutes<br>
                                <strong>Monitoring Recommendation:</strong> Watch for completion
                            </p>
                        </div>

                        <!-- Recent Security Activities -->
                        <div style='background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #495057;'>📊 Recent Security Activities</h4>
                            <p style='color: #495057;'>
                                Last login: " . (isset($userData['last_login']) ? 
                                    date('F j, Y g:i A', strtotime($userData['last_login'])) : 'N/A') . "<br>
                                Login attempts (last 7 days): " . 
                                    (mysqli_fetch_assoc(mysqli_query($conn, 
                                        "SELECT COUNT(*) as attempts FROM login_logs 
                                         WHERE user_id='$user_id' AND created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)"))['attempts'] ?? 0) . "<br>
                                Failed logins (last 7 days): " . 
                                    (mysqli_fetch_assoc(mysqli_query($conn, 
                                        "SELECT COUNT(*) as failed FROM login_logs 
                                         WHERE user_id='$user_id' AND success=0 AND created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)"))['failed'] ?? 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 positive security action by the user.</p>
                            <p class='support-text'>Monitor for setup completion within 10 minutes.</p>
                        </div>
                    </div>";

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

echo json_encode([
    'success' => true,
    'secret' => $secret,
    'qr_code' => $qrCode,
    'backup_codes' => $backup_codes,
    'verification_code' => $verification_code
]);
?>