<?php

class InventoryConditionSetter extends BaseComplianceSetter
{
    public function setCondition(array &$condition, array $data = [])
    {
        $condition['inventoryConditions'] = ['columns' => [], 'filters' => [], 'SQLSTRING' => ''];

        foreach ($condition['rules'] as $rule) {
            $attribute = array_filter($data, function ($item) use ($rule) {
                return $item['attribute_name'] == $rule['attribute'];
            });

            // allow compliance report importing if an inventory attribute is not reported
            if (empty($attribute)) {
                $column = [
                    'id' => "attribute_name=attribute_name={$rule['attribute']}",
                    'attribute_name' => "attribute_name=attribute_name={$rule['attribute']}",
                    'label' => $rule['attribute'],
                    'source_table' => 'inventory',
                ];
            } else {
                $attribute = reset($attribute);
                $this->validate($rule, $attribute['type']);
                $column = [
                    'id' => "attribute_name=attribute_name={$rule['attribute']}",
                    'attribute_name' => "attribute_name=attribute_name={$rule['attribute']}",
                    'category' => $attribute['category'],
                    'readonly' => $attribute['readonly'],
                    'type' => $attribute['type'],
                    'convert_function' => $attribute['convert_function'],
                    'enabled' => 1,
                    'label' => $rule['attribute'],
                    'source_table' => 'inventory',
                ];
            }

            $condition['inventoryConditions']['columns'][] = $column;
            $condition['inventoryConditions']['filters'][] = array_merge($column, [
                'value' => $rule['value'],
                'condition' => $rule['operator'],
            ]);
        }
    }

    private function validate($rule, $type)
    {
        $required = ['attribute', 'operator'];
        $missing = array_diff($required, array_keys($rule));
        if (sizeof($missing) > 0) {
            throw new Exception('Inventory condition missing rule\'s: ' . implode(', ', $missing) . ' fields');
        }

        if (!in_array($rule['operator'], array_values(InventoryAlert::OPERATORS))) {
            throw new Exception(
                "Wrong inventory operator: {$rule['operator']} \n Allowed operators: " .
                    implode(', ', array_values(InventoryAlert::OPERATORS)),
            );
        }

        $ucType = strtoupper($type);
        $typeOperators = constant("InventoryAlert::{$ucType}_OPERATORS");
        if (!in_array($rule['operator'], $typeOperators)) {
            throw new Exception(
                "Wrong {$type} inventory attribute {$rule['attribure']} operator: {$rule['operator']} \n Allowed operators: " .
                    implode(', ', $typeOperators),
            );
        }
    }
}
