<?php
require_once APPPATH . 'modules/advancedreports/services/InventoryAPIService.php';

class variables_dictionary_model extends Cf_Model
{
    public $collectionName = 'variables_dictionary';

    public function __construct()
    {
        parent::__construct();
    }

    public function getVariables()
    {
        try {
            $inventoryAPIService = new InventoryAPIService($this->getRestClient());
            return json_decode($inventoryAPIService->getVariables(), $associative = true);
        } catch (Exception $e) {
            log_message(log_level_for_exception($e), $e->getMessage() . ' ' . $e->getFile() . ' line:' . $e->getLine());
            throw $e;
        }
    }

    /**
     * @param $data
     * @throws Exception
     * @deprecated
     */
    public function updateVariables($data)
    {
        if (empty($data)) {
            return;
        }

        try {
            // save field together with type and table
            foreach ($data as $attribute_name => $field) {
                // do not update readonly variables
                // do not save variables with missing attribute
                if (
                    (!isset($field['readonly']) || (isset($field['readonly']) && $field['readonly'] !== 1)) &&
                    $field['category'] !== 'Missing attribute_name'
                ) {
                    // insert or update if exists - similar to mongo upsert
                    $query = sprintf(
                        'WITH upsert AS (
                                UPDATE %s
                                   SET type=?,
                                       category=?,
                                       readonly=0
                                 WHERE attribute_name = ?
                             RETURNING id
                                )
                        INSERT INTO %s (attribute_name, category, type, readonly)
                        SELECT ?, ?, ?, 0
                        WHERE NOT EXISTS (SELECT 1 FROM upsert)',
                        $this->collectionName,
                        $this->collectionName,
                    );

                    $this->db->query($query, [
                        $field['type'],
                        $field['category'],
                        $attribute_name,
                        $attribute_name,
                        $field['category'],
                        $field['type'],
                    ]);
                }
            }
        } catch (Exception $e) {
            $message = $e->getMessage();
            throw new Exception('Unable to update variables_dictionary: ' . $message);
        }
    }
}
