<?php declare(strict_types=1);

class Log {
    private Database $db;

    public function __construct() {
        $this->db = new Database();
    }

    // Get the latest 200 system logs, joined with the user's name
    public function getLogs(): array {
        $this->db->query('
            SELECT system_logs.*, users.name as user_name 
            FROM system_logs 
            LEFT JOIN users ON system_logs.user_id = users.id 
            ORDER BY system_logs.created_at DESC 
            LIMIT 200
        ');
        return $this->db->resultSet();
    }

    // Get only the 5 most recent logs for the dashboard widget
    public function getRecentLogs(): array {
        $this->db->query('
            SELECT system_logs.*, users.name as user_name 
            FROM system_logs 
            LEFT JOIN users ON system_logs.user_id = users.id 
            ORDER BY system_logs.created_at DESC 
            LIMIT 5
        ');
        return $this->db->resultSet();
    }

    // Get logs specifically for Cron Job executions
    public function getCronLogs(int $limit = 50): array {
        $this->db->query("
            SELECT * FROM system_logs 
            WHERE action = 'CRON_RUN' 
            ORDER BY created_at DESC 
            LIMIT :limit
        ");
        $this->db->bind(':limit', $limit);
        return $this->db->resultSet();
    }

    // Clear all system logs
    public function clearLogs(): bool {
        $this->db->query('TRUNCATE TABLE system_logs');
        return $this->db->execute();
    }
}