<?php
session_start();
include 'layouts/dbconn.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$user_id = $_SESSION['user_id'];

try {
    // Log the action
    $action = "security_logout_all";
    $details = "User initiated logout from all devices";
    $ip_address = $_SERVER['REMOTE_ADDR'];
    
    $log_query = "INSERT INTO admin_logs (user_id, action, details, ip_address, created_at) 
                 VALUES (?, ?, ?, ?, NOW())";
    $log_stmt = $conn->prepare($log_query);
    $log_stmt->bind_param("isss", $user_id, $action, $details, $ip_address);
    $log_stmt->execute();
    
    // Update user session token or auth key if such a mechanism exists
    // This would typically invalidate all existing sessions
    $token = bin2hex(random_bytes(32));
    $update_query = "UPDATE users SET session_token = ?, last_active = NULL WHERE user_id = ?";
    $update_stmt = $conn->prepare($update_query);
    $update_stmt->bind_param("si", $token, $user_id);
    $update_stmt->execute();
    
    // Destroy the current session
    session_unset();
    session_destroy();
    
    // Redirect to login page with success message
    header('Location: login.php?message=You have been logged out from all devices successfully');
    exit();
} catch (Exception $e) {
    // Log error
    error_log("Logout all devices error: " . $e->getMessage());
    
    // Redirect to profile page with error message
    $_SESSION['error_message'] = "An error occurred while logging out from all devices. Please try again.";
    header('Location: user_profile.php');
    exit();
}
?>