<?php
require_once '../config/cors.php';
require_once '../config/database.php';
require_once '../utils/helpers.php';

// Extract authorization token
$token = getAuthToken();

// Validate token
$user = getUserFromToken($token);
if (!$user) {
    errorResponse('User not authenticated', 401);
}

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);

try {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        // Log activity
        if (!isset($input['action'])) {
            errorResponse('Action is required', 400);
        }
        
        $action = $input['action'];
        $details = isset($input['details']) ? json_encode($input['details']) : null;
        $ipAddress = $_SERVER['REMOTE_ADDR'] ?? null;
        $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? null;
        
        $logId = generateUUID();
        $stmt = $pdo->prepare("INSERT INTO dashboard_logs (id, user_id, action, details, ip_address, user_agent) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->execute([$logId, $user['id'], $action, $details, $ipAddress, $userAgent]);
        
        jsonResponse(['message' => 'Activity logged successfully'], 200);
    } else {
        // Get logs
        $stmt = $pdo->prepare("SELECT * FROM dashboard_logs WHERE user_id = ? ORDER BY created_at DESC");
        $stmt->execute([$user['id']]);
        $logs = $stmt->fetchAll();
        
        jsonResponse(['logs' => $logs], 200);
    }
} catch (Exception $e) {
    errorResponse('Error managing dashboard logs: ' . $e->getMessage(), 500);
}
?>