<?php

class Inventory_rule_report extends BaseRuleReport
{
    public function getReportSql($sql, CF_Rule $rule)
    {
        $inventoryColumns = $rule->inventoryConditions['columns'] ?? ($rule->inventoryConditions['filters'] ?? []);
        $columns = array_unique(
            array_map(function ($item) {
                return "inventory_new.values->>'{$item['label']}' AS \"{$item['label']}\"";
            }, $inventoryColumns),
        );

        // get first column (host name) from $this->defaultColumns
        // and insert into resulted columns array as first element
        $columns = array_merge([array_shift($this->defaultColumns)], $columns, $this->defaultColumns);

        return 'SELECT ' .
            implode(',', $columns) .
            '
                FROM Hosts
                LEFT JOIN inventory_new ON inventory_new.hostkey = Hosts.hostkey
                ' .
            $this->getFilter($sql, joinInventory: false, rule: $rule);
    }
}
