<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

// Handle preflight
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

require_once '../config/database.php';
require_once '../includes/functions.php';

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendResponse(false, 'Only POST requests are allowed');
}

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);
$token = $input['token'] ?? '';

// Validate token
if (empty($token)) {
    sendResponse(false, 'Session token is required');
}

try {
    $conn = getDBConnection();
    
    // Get user_id from token
    $stmt = $conn->prepare("SELECT user_id FROM user_sessions WHERE token = ? AND expires_at > NOW()");
    $stmt->execute([$token]);
    $session = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$session) {
        sendResponse(false, 'Invalid or expired session');
    }
    
    // Get all active sessions for this user
    $stmt = $conn->prepare("
        SELECT id, token, device_info, ip_address, created_at, expires_at,
               CASE WHEN token = ? THEN 1 ELSE 0 END as is_current
        FROM user_sessions 
        WHERE user_id = ? AND expires_at > NOW()
        ORDER BY created_at DESC
    ");
    $stmt->execute([$token, $session['user_id']]);
    $sessions = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Format sessions
    foreach ($sessions as &$s) {
        $s['is_current'] = (bool)$s['is_current'];
    }
    
    sendResponse(true, 'Sessions retrieved', ['sessions' => $sessions]);
    
} catch (PDOException $e) {
    logError("Get sessions error: " . $e->getMessage());
    sendResponse(false, 'Failed to retrieve sessions');
}
