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

// Get current session ID
$current_session = session_id();

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

// Get count of devices to be logged out
$count_sql = "SELECT COUNT(*) as device_count FROM user_devices WHERE user_id = '$user_id' AND session_id != '$current_session'";
$count_result = mysqli_query($conn, $count_sql);
$count_data = mysqli_fetch_assoc($count_result);
$device_count = $count_data['device_count'];

// Get list of devices that will be logged out
$devices_sql = "SELECT device_name, browser, os, last_activity, ip_address FROM user_devices WHERE user_id = '$user_id' AND session_id != '$current_session'";
$devices_result = mysqli_query($conn, $devices_sql);
$logged_out_devices = [];
while ($device = mysqli_fetch_assoc($devices_result)) {
    $logged_out_devices[] = $device;
}

// Get current device info
$current_device_query = mysqli_query($conn, "SELECT * FROM user_devices WHERE user_id = '$user_id' AND session_id = '$current_session'");
$current_device = mysqli_fetch_assoc($current_device_query);

// Delete all other devices
$delete_sql = "DELETE FROM user_devices WHERE user_id = '$user_id' AND session_id != '$current_session'";

if (mysqli_query($conn, $delete_sql)) {
    
    // NOTIFICATION: Devices Logged Out (USER)
    $mail_subject = "Security Alert: Other Devices Logged Out";
    $mail_message = "<!-- Content Section -->
                    <div class='email-content'>
                        <h2 class='greeting'>Hello <span class='user-name'>" . $first_name . "</span>,</h2>
                        
                        <p class='message'>
                            🔒 <strong>You have logged out all other devices from your account.</strong><br>
                            This is a security action that helps protect your account from unauthorized access.
                        </p>

                        <!-- Security Action Details -->
                        <div class='details-section'>
                            <div class='detail-box'>
                                <strong>Security Action:</strong> Logout All Other Devices<br>
                                <strong>Action Date:</strong> " . date('F j, Y g:i A') . "<br>
                                <strong>Devices Logged Out:</strong> " . $device_count . " device(s)<br>
                                <strong>Action Initiated From:</strong> " . $user_ip . "<br>
                                <strong>Current Device:</strong> " . ($current_device['device_name'] ?? 'This Device') . "<br>
                                <strong>Current Browser:</strong> " . ($current_device['browser'] ?? 'Unknown') . "<br>
                                <strong>Current Status:</strong> <span style='color: #28a745; font-weight: bold;'>ACTIVE</span>
                            </div>
                        </div>";

    // Add device list if any devices were logged out
    if (!empty($logged_out_devices)) {
        $mail_message .= "
                        <!-- Logged Out Devices -->
                        <div style='background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #495057;'>📱 Devices That Were Logged Out</h4>
                            <div style='max-height: 200px; overflow-y: auto;'>";
        
        foreach ($logged_out_devices as $index => $device) {
            $last_active = $device['last_activity'] ? date('M j, g:i A', strtotime($device['last_activity'])) : 'Never';
            $mail_message .= "
                                <div style='border-bottom: 1px solid #dee2e6; padding: 10px 0; " . ($index == count($logged_out_devices)-1 ? 'border-bottom: none;' : '') . "'>
                                    <strong>Device " . ($index + 1) . ":</strong><br>
                                    • Name: " . htmlspecialchars($device['device_name']) . "<br>
                                    • Browser: " . htmlspecialchars($device['browser']) . "<br>
                                    • OS: " . htmlspecialchars($device['os']) . "<br>
                                    • IP: " . htmlspecialchars($device['ip_address']) . "<br>
                                    • Last Active: " . $last_active . "
                                </div>";
        }
        
        $mail_message .= "
                            </div>
                        </div>";
    }

    $mail_message .= "
                        <!-- Why This Is Important -->
                        <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #0056b3;'>🛡️ Why Logout Other Devices?</h4>
                            <p style='color: #0056b3;'>
                                Logging out other devices is an important security practice when:<br>
                                • You suspect unauthorized access<br>
                                • You've used a public/shared computer<br>
                                • You want to ensure only current device has access<br>
                                • Preparing for security audit<br>
                                • After changing password or security settings
                            </p>
                        </div>

                        <!-- What Happens Next -->
                        <div class='next-steps'>
                            <h3 style='color: #2c3e50;'>What Happens Next?</h3>
                            <ul style='color: #6c757d;'>
                                <li>Logged out devices will need to login again</li>
                                <li>You remain logged in on this device only</li>
                                <li>Any active sessions on other devices are terminated</li>
                                <li>Security logs are updated with this action</li>
                            </ul>
                        </div>

                        <!-- Security Warning -->
                        <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #856404;'>⚠️ IMPORTANT: If This Wasn't You</h4>
                            <p style='color: #856404;'>
                                If you did NOT initiate this device logout:<br>
                                • Someone may have access to your account<br>
                                • Change your password immediately<br>
                                • Enable two-factor authentication<br>
                                • 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 . "/sessions.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 Active Sessions
                            </a>
                        </div>

                        <!-- Support Section -->
                        <div class='support-section'>
                            <p class='support-text'>Need help with account security?</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: Devices Logged Out (ADMIN - Security Alert)
    $admin_mail_subject = "Security Alert: User Logged Out Other Devices - User ID: " . $user_id;
    $admin_mail_message = "<!-- Content Section -->
                        <div class='email-content'>
                            <h2 class='greeting'>Security Alert: Devices Logged Out</h2>
                            
                            <p class='message'>
                                A user has initiated a logout of all other devices from their account.
                            </p>

                            <!-- Security Action 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> Logout All Other Devices<br>
                                    <strong>Action Date:</strong> " . date('F j, Y g:i A') . "<br>
                                    <strong>Action IP:</strong> " . $user_ip . "<br>
                                    <strong>Current Session ID:</strong> " . $current_session . "<br>
                                    <strong>Devices Logged Out:</strong> " . $device_count . " device(s)<br>
                                    <strong>Current Device:</strong> " . ($current_device['device_name'] ?? 'Unknown') . "
                                </div>
                            </div>";

    // Add detailed device list for admin
    if (!empty($logged_out_devices)) {
        $admin_mail_message .= "
                            <!-- Detailed Device Log -->
                            <div style='background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #495057;'>📋 Devices That Were Logged Out</h4>";
        
        foreach ($logged_out_devices as $device) {
            $last_active = $device['last_activity'] ? date('Y-m-d H:i:s', strtotime($device['last_activity'])) : 'Never';
            $admin_mail_message .= "
                                <div style='border: 1px solid #dee2e6; border-radius: 4px; padding: 10px; margin: 8px 0; background: white;'>
                                    <strong>Device:</strong> " . htmlspecialchars($device['device_name']) . "<br>
                                    <strong>Browser:</strong> " . htmlspecialchars($device['browser']) . "<br>
                                    <strong>OS:</strong> " . htmlspecialchars($device['os']) . "<br>
                                    <strong>IP Address:</strong> " . htmlspecialchars($device['ip_address']) . "<br>
                                    <strong>Last Activity:</strong> " . $last_active . "
                                </div>";
        }
        
        $admin_mail_message .= "
                            </div>";
    }

    $admin_mail_message .= "
                            <!-- Security Analysis -->
                            <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #856404;'>🔍 Security Analysis</h4>
                                <p style='color: #856404;'>
                                    <strong>Risk Level:</strong> " . ($device_count > 3 ? 'MEDIUM' : 'LOW') . "<br>
                                    <strong>Behavior Pattern:</strong> " . ($device_count > 0 ? 'Normal security practice' : 'No other devices active') . "<br>
                                    <strong>Previous Similar Actions:</strong> " . 
                                        (mysqli_fetch_assoc(mysqli_query($conn, 
                                            "SELECT COUNT(*) as count FROM security_logs 
                                             WHERE user_id='$user_id' AND action='logout_other_devices' 
                                             AND created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)"))['count'] ?? 0) . " (last 30 days)<br>
                                    <strong>Account Security Score:</strong> " . 
                                        (isset($userData['security_score']) ? $userData['security_score'] . '/100' : 'N/A') . "
                                </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;'>
                                    View Security Logs
                                </a>
                            </div>

                            <!-- Security Notes -->
                            <div class='support-section'>
                                <p class='support-text'>This is an automated security notification.</p>
                                <p class='support-text'>Monitor for unusual device logout patterns.</p>
                            </div>
                        </div>";

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

    echo json_encode(['success' => true, 'message' => 'All other devices logged out']);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to logout devices: ' . mysqli_error($conn)]);
}
?>