<?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);
}

global $pdo;
$user = requireAuth();

$sessionCountStmt = $pdo->prepare('SELECT COUNT(*) FROM user_sessions WHERE user_id = :user_id AND is_revoked = 0 AND expires_at >= NOW()');
$sessionCountStmt->execute(['user_id' => $user['id']]);
$activeSessions = (int)$sessionCountStmt->fetchColumn();

$lastSuccessStmt = $pdo->prepare("SELECT login_at FROM user_login_history WHERE user_id = :user_id AND status = 'success' ORDER BY id DESC LIMIT 1");
$lastSuccessStmt->execute(['user_id' => $user['id']]);
$lastLoginAt = $lastSuccessStmt->fetchColumn() ?: null;

$failedCountStmt = $pdo->prepare("SELECT COUNT(*) FROM user_login_history WHERE user_id = :user_id AND status = 'failed'");
$failedCountStmt->execute(['user_id' => $user['id']]);
$failedAttempts = (int)$failedCountStmt->fetchColumn();

jsonResponse(true, 'Security overview fetched successfully', [
    'active_sessions' => $activeSessions,
    'last_login_at' => $lastLoginAt,
    'failed_attempts' => $failedAttempts,
]);
