<?php

/**
 * Class VariablesDictionaryModel
 */
class VariablesDictionaryModel
{
    /**
     * @var PDO
     */
    private $dbConnection;

    /**
     * @var array
     */
    public $errors = [];

    /**
     * @var array
     */
    private $allowedKeys = [
        'category',
        'type',
        'convert_function'
    ];

    /**
     * @var array
     */
    private $allowedFunctios = [
        'cf_clearSlist'
    ];

    /**
     * @var array
     */
    private $allowedTypes = [
        'int',
        'real',
        'slist',
        'string'
    ];

    /**
     * VariablesDictionaryModel constructor.
     */
    public function __construct()
    {
        $instance = DbConnection::getInstance();
        $this->dbConnection = $instance->getConnection();
    }

    /**
     * @return array
     */
    public function getAll()
    {
        $sql = "SELECT * FROM variables_dictionary WHERE enabled = 1 ORDER BY attribute_name";
        return $this->dbConnection->query($sql)->fetchAll(PDO::FETCH_ASSOC);
    }

    /**
     * @param $id
     * @return mixed
     */
    public function getById($id)
    {
        $sql = "SELECT * FROM variables_dictionary WHERE id = ? AND enabled = 1 LIMIT 1";
        $stmt = $this->dbConnection->prepare($sql);
        $stmt->execute([$id]);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }

    /**
     * @param $name
     * @param $enabled
     * @return mixed
     */
    public function getByName($name, $enabled = false)
    {
        $enabledCond = $enabled === true ? 'AND enabled = 1' : '';
        $sql = "SELECT * FROM variables_dictionary WHERE attribute_name = ? $enabledCond LIMIT 1";
        $stmt = $this->dbConnection->prepare($sql);
        $stmt->execute([$name]);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }

    /**
     * @param $id
     * @param array $data
     */
    public function update($id, $data)
    {
        $columns = [];
        $values = [];

        foreach ($data as $key => $value) {
            // filter by allowed keys
            if (!in_array($key, $this->allowedKeys)) {
                continue;
            }
            // add keys to columns placeholders
            $columns[] = $key . ' = ?';
            $values[] = $value;
        }

        if (!empty($columns)) {
            // add id as the last parameter
            $values[] = $id;
            // use columns as placeholders and process data via execute
            $sql = "UPDATE variables_dictionary SET " . implode(', ', $columns) . " WHERE id = ?";

            $stmt = $this->dbConnection->prepare($sql);
            $stmt->execute($values);
        }
    }

    /**
     * @return array
     */
    public function getFunctionsMap()
    {
        $variables = $this->getAll();
        $map = [];
        foreach ($variables as $variable) {
            $map[$variable['attribute_name']] = trim($variable['convert_function']);
        }
        return $map;
    }

    /**
     * @param $data
     * @return bool
     */
    public function validate($data)
    {
        $success = true;
        if (isset($data->type) && !in_array($data->type, $this->allowedTypes)) {
            $this->errors[] = 'Type is wrong. Allowed values: ' . implode(',', $this->allowedTypes);
            $success = false;
        }

        if (isset($data->convert_function) && !in_array($data->convert_function, $this->allowedFunctios)) {
            $this->errors[] = 'Convert function is wrong. Allowed values: ' . implode(',', $this->allowedFunctios);
            $success = false;
        }

        return $success;

    }

    public function updateCustomVariables()
    {
        $sql = "CALL update_variables_dictionary();";
        return $this->dbConnection->query($sql)->execute();
    }


}
