<?php

class ActivityLog
{
    public function log($userId, $restaurantId, $module, $action, $details, $ip = null, $userAgent = null)
    {
        $db = Database::getInstance();
        $db->insert('activity_logs', [
            'user_id'       => $userId,
            'restaurant_id' => $restaurantId,
            'module'        => $module,
            'action'        => $action,
            'details'       => $details,
            'ip_address'    => $ip ?? ($_SERVER['REMOTE_ADDR'] ?? '127.0.0.1'),
            'user_agent'    => $userAgent ?? ($_SERVER['HTTP_USER_AGENT'] ?? ''),
            'created_at'    => date('Y-m-d H:i:s'),
        ]);
    }

    public function getLogs($restaurantId = null, $limit = 50, $offset = 0)
    {
        $db = Database::getInstance();
        $sql = "SELECT al.*, u.name AS user_name
                FROM activity_logs al
                LEFT JOIN users u ON al.user_id = u.id";

        $params = [];
        if ($restaurantId !== null) {
            $sql .= " WHERE al.restaurant_id = ?";
            $params[] = $restaurantId;
        }

        $sql .= " ORDER BY al.created_at DESC LIMIT ? OFFSET ?";
        $params[] = (int) $limit;
        $params[] = (int) $offset;

        $stmt = $db->query($sql, $params);
        return $stmt->fetchAll();
    }

    public function clearOld($days = 90)
    {
        $db = Database::getInstance();
        return $db->delete(
            'activity_logs',
            'created_at < DATE_SUB(NOW(), INTERVAL ? DAY)',
            [$days]
        );
    }
}
