<?php
/**
 * Get Recent Activity
 * AJAX endpoint for recent audit log entries
 */

header('Content-Type: application/json');
require_once '../layouts/dbconn.php';
require_once '../includes/auth.php';

// Check authentication
if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

try {
    $limit = $_GET['limit'] ?? 10;
    $limit = min($limit, 50); // Max 50 records
    
    $sql = "SELECT event_type, event_category, event_description, performed_by, created_at
            FROM audit_logs
            ORDER BY created_at DESC
            LIMIT ?";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $limit);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $activities = [];
    while ($row = $result->fetch_assoc()) {
        // Determine badge color based on event category
        $badgeColors = [
            'SYSTEM' => 'primary',
            'FINANCIAL' => 'success',
            'WITHDRAWAL' => 'warning',
            'CONTRIBUTION' => 'info',
            'LIFE_INSURANCE' => 'danger',
            'CLAIM' => 'warning'
        ];
        
        $row['badge_color'] = $badgeColors[$row['event_category']] ?? 'secondary';
        $row['created_at'] = date('Y-m-d H:i', strtotime($row['created_at']));
        $activities[] = $row;
    }
    
    echo json_encode([
        'success' => true,
        'data' => $activities
    ]);
    
} catch (Exception $e) {
    error_log("get_recent_activity Error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Failed to load activity'
    ]);
}
