<?php
require_once '../config/database.php';

header('Content-Type: application/json');

if (!isset($_SESSION['admin_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

try {
    $pdo = getDBConnection();
    
    // Successful logins in last 24 hours
    $stmt = $pdo->prepare("
        SELECT COUNT(*) as count 
        FROM activity_logs 
        WHERE action = 'login' 
        AND created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)
    ");
    $stmt->execute();
    $successful_logins = $stmt->fetch()['count'];
    
    // Failed logins in last 24 hours
    $stmt = $pdo->prepare("
        SELECT COUNT(*) as count 
        FROM activity_logs 
        WHERE action = 'login_failed' 
        AND created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)
    ");
    $stmt->execute();
    $failed_logins = $stmt->fetch()['count'];
    
    // Currently locked accounts
    $stmt = $pdo->prepare("
        SELECT COUNT(*) as count 
        FROM admins 
        WHERE locked_until IS NOT NULL 
        AND locked_until > NOW()
    ");
    $stmt->execute();
    $locked_accounts = $stmt->fetch()['count'];
    
    // Active sessions (rough estimate based on recent activity)
    $stmt = $pdo->prepare("
        SELECT COUNT(DISTINCT user_id) as count 
        FROM activity_logs 
        WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 MINUTE)
    ");
    $stmt->execute();
    $active_sessions = $stmt->fetch()['count'];
    
    echo json_encode([
        'success' => true,
        'data' => [
            'successful_logins' => $successful_logins,
            'failed_logins' => $failed_logins,
            'locked_accounts' => $locked_accounts,
            'active_sessions' => $active_sessions
        ]
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false, 
        'message' => 'Error fetching security stats: ' . $e->getMessage()
    ]);
}
?>
