<?php
// FIX 1: Add this line to allow requests from the frontend
require_once '../config/cors.php';

require_once '../config/database.php';
require_once '../middleware/auth.php';
require_once '../utils/jwt.php';

// --- AUTHENTICATION DISABLED FOR TESTING ---
/*
function ensureAdmin($token) {
    $payload = validateToken($token);
    if (!$payload || $payload->role !== 'admin') {
        http_response_code(403);
        echo json_encode(['error' => 'Unauthorized access']);
        exit;
    }
    return $payload;
}

// Get the authorization header
$headers = getallheaders();
$token = isset($headers['Authorization']) ? str_replace('Bearer ', '', $headers['Authorization']) : null;

if (!$token) {
    http_response_code(401);
    echo json_encode(['error' => 'No token provided']);
    exit;
}

// Validate admin access
$admin = ensureAdmin($token);
*/
// --- END OF DISABLED CODE ---


// FIX 2: Add database connection and convert to PDO
$database = new Database();
$db = $database->getConnection();


if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    try {
        // Get recent activities from admin logs
        $stmt = $db->prepare("
            SELECT 
                al.action,
                al.details,
                al.timestamp,
                u.name as admin_name
            FROM admin_logs al
            JOIN users u ON al.admin_id = u.id
            ORDER BY al.timestamp DESC
            LIMIT 20
        ");
        
        $stmt->execute();
        $activities = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // Format activities for display
        $formattedActivities = array_map(function($activity) {
            return [
                'description' => $activity['action'],
                'admin' => $activity['admin_name'],
                'details' => json_decode($activity['details'], true),
                'timestamp' => $activity['timestamp']
            ];
        }, $activities);

        http_response_code(200);
        echo json_encode(['activities' => $formattedActivities]);

    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Failed to fetch recent activities: ' . $e->getMessage()]);
    }
} else {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
}

// $conn->close(); // Not needed for PDO
?>