<?php
require_once '../config/cors.php';
require_once '../config/database.php';
require_once '../utils/helpers.php';

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

// Extract authorization token
$token = getAuthToken();

// Validate token
$user = getUserFromToken($token);
if (!$user) {
    errorResponse('User not authenticated', 401);
}

try {
    switch ($_SERVER['REQUEST_METHOD']) {
        case 'GET':
            // Get user sessions
            $stmt = $pdo->prepare("SELECT id, session_token, expires_at, created_at FROM sessions WHERE user_id = ? ORDER BY created_at DESC");
            $stmt->execute([$user['id']]);
            $sessions = $stmt->fetchAll();
            
            jsonResponse(['sessions' => $sessions], 200);
            break;
            
        case 'POST':
            // Create or refresh session
            $action = isset($input['action']) ? $input['action'] : 'create';
            
            if ($action === 'create') {
                // Create new session
                $sessionId = generateUUID();
                $sessionToken = bin2hex(random_bytes(32));
                $expiresAt = date('Y-m-d H:i:s', strtotime('+1 hour'));
                
                $stmt = $pdo->prepare("INSERT INTO sessions (id, user_id, session_token, expires_at) VALUES (?, ?, ?, ?)");
                $stmt->execute([$sessionId, $user['id'], $sessionToken, $expiresAt]);
                
                jsonResponse([
                    'session_id' => $sessionId,
                    'session_token' => $sessionToken,
                    'expires_at' => $expiresAt
                ], 200);
            } elseif ($action === 'refresh') {
                // Refresh existing session
                $sessionId = isset($input['session_id']) ? $input['session_id'] : null;
                
                if (!$sessionId) {
                    errorResponse('Session ID is required', 400);
                }
                
                $expiresAt = date('Y-m-d H:i:s', strtotime('+1 hour'));
                
                $stmt = $pdo->prepare("UPDATE sessions SET expires_at = ?, updated_at = datetime('now') WHERE id = ? AND user_id = ?");
                $stmt->execute([$expiresAt, $sessionId, $user['id']]);
                
                jsonResponse([
                    'session_id' => $sessionId,
                    'expires_at' => $expiresAt
                ], 200);
            } else {
                errorResponse('Invalid action', 400);
            }
            break;
            
        case 'DELETE':
            // Delete session
            $sessionId = isset($input['session_id']) ? $input['session_id'] : null;
            
            if (!$sessionId) {
                errorResponse('Session ID is required', 400);
            }
            
            $stmt = $pdo->prepare("DELETE FROM sessions WHERE id = ? AND user_id = ?");
            $stmt->execute([$sessionId, $user['id']]);
            
            jsonResponse(['success' => true], 200);
            break;
            
        default:
            errorResponse('Method not allowed', 405);
    }
} catch (Exception $e) {
    errorResponse('Error managing sessions: ' . $e->getMessage(), 500);
}
?>