<?php

class CfInventoryAliases
{
    private $table = 'inventory_aliases';

    /**
     * @var PDO
     */
    private $dbConnection;

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

    /**
     * @return array where key is alias and value is column name
     */
    public function getAliases()
    {
        $aliases = $this->dbConnection
            ->query('SELECT * FROM ' . $this->table)
            ->fetchAll(PDO::FETCH_ASSOC);

        $result = [];
        foreach ($aliases as $item) {
            $result[$item['alias']] = $item['inventory_attribute'];
        }
        return $result;
    }

    /**
     * @param $alias
     * @param $attribute
     */
    public function insertAlias($alias, $attribute)
    {
        $data = [
            'alias' => strtolower($alias),
            'inventory_attribute' => $attribute
        ];
        $sql = 'INSERT INTO '. $this->table .' ("inventory_attribute", "alias") VALUES (:inventory_attribute, :alias)';
        $stmt = $this->dbConnection->prepare($sql);
        $stmt->execute($data);
    }

    /**
     * @param $alias
     */
    public function deleteAlias($alias)
    {
        $sql = "DELETE FROM {$this->table} WHERE alias = ? ";
        $stmt = $this->dbConnection->prepare($sql);
        $stmt->execute([$alias]);
    }
}
