<?php

class ActivityLog {
    public static function all($limit = 100) {
        $db = Database::getInstance();
        return $db->fetchAll(
            "SELECT al.*, u.username, u.first_name, u.last_name 
             FROM activity_logs al 
             LEFT JOIN users u ON al.user_id = u.id 
             ORDER BY al.created_at DESC 
             LIMIT ?",
            [$limit]
        );
    }

    public static function getByUser($userId, $limit = 50) {
        $db = Database::getInstance();
        return $db->fetchAll(
            "SELECT al.*, u.username, u.first_name, u.last_name 
             FROM activity_logs al 
             LEFT JOIN users u ON al.user_id = u.id 
             WHERE al.user_id = ? 
             ORDER BY al.created_at DESC 
             LIMIT ?",
            [$userId, $limit]
        );
    }

    public static function getByAction($action, $limit = 50) {
        $db = Database::getInstance();
        return $db->fetchAll(
            "SELECT al.*, u.username 
             FROM activity_logs al 
             LEFT JOIN users u ON al.user_id = u.id 
             WHERE al.action = ? 
             ORDER BY al.created_at DESC 
             LIMIT ?",
            [$action, $limit]
        );
    }

    public static function create($userId, $action, $details = '') {
        $db = Database::getInstance();
        $db->execute(
            "INSERT INTO activity_logs (user_id, action, details, ip_address) VALUES (?, ?, ?, ?)",
            [
                $userId,
                $action,
                $details,
                $_SERVER['REMOTE_ADDR'] ?? null
            ]
        );
    }

    public static function deleteAll() {
        $db = Database::getInstance();
        return $db->execute("DELETE FROM activity_logs");
    }

    public static function deleteByUser($userId) {
        $db = Database::getInstance();
        return $db->execute("DELETE FROM activity_logs WHERE user_id = ?", [$userId]);
    }

    public static function getDistinctUsers() {
        $db = Database::getInstance();
        return $db->fetchAll(
            "SELECT DISTINCT u.id, u.username, u.first_name, u.last_name
             FROM activity_logs al
             LEFT JOIN users u ON al.user_id = u.id
             WHERE u.id IS NOT NULL
             ORDER BY u.username"
        );
    }
}
