<?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_login_history WHERE user_id = :user_id');
$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, login_at, logout_at, ip, device, browser, platform, user_agent, status, failure_reason, created_at
     FROM user_login_history
     WHERE user_id = :user_id
     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();
$rows = $stmt->fetchAll();

$data = array_map(function (array $row) {
    $row['id'] = (int) $row['id'];
    $row['user_id'] = (int) $row['user_id'];
    return $row;
}, $rows);

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