<?php

require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/helpers.php';
require_once __DIR__ . '/../../middleware/auth.php';

if (getMethod() !== 'GET') {
    jsonResponse(false, 'Method not allowed', null, 405);
}

function paginatedJsonResponse(bool $ok, string $message, array $data, array $pagination, int $status = 200): void
{
    http_response_code($status);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode([
        'ok' => $ok,
        'message' => $message,
        'data' => $data,
        'pagination' => $pagination,
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

global $pdo;
$user = requireAuth();

$page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
$limit = isset($_GET['limit']) ? (int) $_GET['limit'] : 10;

if ($page < 1) {
    $page = 1;
}
if ($limit < 1) {
    $limit = 10;
}
if ($limit > 100) {
    $limit = 100;
}

$countStmt = $pdo->prepare('SELECT COUNT(*) FROM user_sessions WHERE user_id = :user_id AND is_revoked = 0');
$countStmt->execute(['user_id' => $user['id']]);
$total = (int) $countStmt->fetchColumn();
$totalPages = max(1, (int) ceil($total / $limit));

if ($page > $totalPages) {
    $page = $totalPages;
}

$offset = ($page - 1) * $limit;

$stmt = $pdo->prepare(
    'SELECT id, user_id, ip, user_agent, device, platform, browser, is_revoked, expires_at, last_seen_at, created_at, updated_at
     FROM user_sessions
     WHERE user_id = :user_id AND is_revoked = 0 
     ORDER BY id DESC
     LIMIT :limit OFFSET :offset'
);
$stmt->bindValue(':user_id', (int) $user['id'], PDO::PARAM_INT);
$stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
$sessions = $stmt->fetchAll();

$currentSessionId = (int) ($user['session_id'] ?? 0);
$now = time();

$data = array_map(function (array $session) use ($currentSessionId, $now) {
    $expiresAt = $session['expires_at'] ?? null;

    return [
        'id' => (int) $session['id'],
        'user_id' => (int) $session['user_id'],
        'ip' => $session['ip'],
        'user_agent' => $session['user_agent'],
        'device' => $session['device'],
        'platform' => $session['platform'],
        'browser' => $session['browser'],
        'is_revoked' => (int) $session['is_revoked'],
        'is_current' => ((int) $session['id'] === $currentSessionId),
        'is_expired' => $expiresAt ? (strtotime($expiresAt) < $now) : false,
        'expires_at' => $expiresAt,
        'last_seen_at' => $session['last_seen_at'],
        'created_at' => $session['created_at'],
        'updated_at' => $session['updated_at'],
    ];
}, $sessions);

paginatedJsonResponse(true, 'Sessions fetched successfully', $data, [
    'page' => $page,
    'limit' => $limit,
    'total' => $total,
    'totalPages' => $totalPages,
    'hasNext' => $page < $totalPages,
    'hasPrev' => $page > 1,
]);
