<?php

// Prevent direct script access
if (basename(__FILE__) == basename($_SERVER['SCRIPT_FILENAME'])) {
    die('No direct script access allowed');
}

// --- User Activity Log Related Queries ---

/**
 * Logs a user activity.
 */
function logUserActivity(int $user_id, string $action, ?array $details = null): bool {
    try {
        $details_json = $details ? json_encode($details, JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE) : null;
        if ($details_json === false) {
             // Log JSON encoding error if necessary
             $details_json = json_encode(['error' => 'Failed to encode details', 'original_details' => $details], JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
        }

        $stmt = pdo()->prepare("INSERT INTO user_activity_logs (user_id, action, details, created_at) VALUES (?, ?, ?, NOW())");
        return $stmt->execute([$user_id, $action, $details_json]);
    } catch (PDOException $e) {
        file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error logging activity for user {$user_id}: " . $e->getMessage() . "\n", FILE_APPEND);
        return false;
    }
}

/**
 * Gets recent activity logs for a user.
 */
function getUserActivityLogs(int $user_id, int $limit = 20, int $offset = 0): array {
    try {
        $stmt = pdo()->prepare("SELECT action, details, created_at FROM user_activity_logs WHERE user_id = :user_id ORDER BY id DESC LIMIT :limit OFFSET :offset");
        $stmt->bindValue(':user_id', $user_id, PDO::PARAM_INT);
        $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
        $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
        $stmt->execute();
        return $stmt->fetchAll();
    } catch (PDOException $e) {
        file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error getting activity logs for user {$user_id}: " . $e->getMessage() . "\n", FILE_APPEND);
        return [];
    }
}

?>
