<?php

namespace idoit\Module\Check_mk\Model;

use idoit\Model\Dao\Base;

/**
 * Static tag model
 *
 * @package     Modules
 * @subpackage  Cabling
 * @author      Leonard Fischer <lfischer@i-doit.com>
 * @copyright   synetics GmbH
 * @since       1.10.2
 * @license     http://www.i-doit.com/license
 */
class StaticTag extends Base
{
    /**
     * Read tags by ID or unique tag name.
     *
     * @param  integer|array $id
     * @param  string        $tag
     *
     * @return \isys_component_dao_result
     * @throws \isys_exception_database
     */
    public function getTags($id = null, $tag = null)
    {
        $sql = 'SELECT * FROM isys_check_mk_tags WHERE TRUE';

        if ($id !== null && !empty($id)) {
            if (is_array($id) && count($id)) {
                $sql .= ' AND isys_check_mk_tags__id ' . $this->prepare_in_condition($id);
            } else {
                $sql .= ' AND isys_check_mk_tags__id = ' . $this->convert_sql_id($id);
            }
        }

        if ($tag !== null && !empty($tag)) {
            $sql .= ' AND isys_check_mk_tags__unique_name = ' . $this->convert_sql_text($tag);
        }

        return $this->retrieve($sql . ';');
    }

    /**
     * Create or update a static tag.
     *
     * @param  integer $id
     * @param  array   $data
     *
     * @return integer
     * @throws \isys_exception_dao
     */
    public function saveTag($id = null, array $data = [])
    {
        $fields = [];

        if ($id === null || empty($id)) {
            $sql = 'INSERT INTO isys_check_mk_tags SET %s;';
        } else {
            $sql = 'UPDATE isys_check_mk_tags SET %s WHERE isys_check_mk_tags__id = ' . $this->convert_sql_id($id) . ';';
        }

        if (count($data)) {
            foreach ($data as $field => $value) {
                $fields[] = 'isys_check_mk_tags__' . $field . ' = ' . $this->convert_sql_text($value);
            }

            $this->update(str_replace('%s', implode(', ', $fields), $sql)) && $this->apply_update();
        }

        return $id ?: $this->get_last_insert_id();
    }

    /**
     * Delete one or multiple tags.
     *
     * @param  integer|array $id
     *
     * @return boolean
     * @throws \isys_exception_dao
     */
    public function deleteTags($id)
    {
        if (is_array($id) && count($id)) {
            $sql = 'DELETE FROM isys_check_mk_tags WHERE isys_check_mk_tags__id ' . $this->prepare_in_condition($id) . ';';
        } else if (is_numeric($id) && $id > 0) {
            $sql = 'DELETE FROM isys_check_mk_tags WHERE isys_check_mk_tags__id = ' . $this->convert_sql_id($id) . ';';
        } else {
            return true;
        }

        return $this->update($sql) && $this->apply_update();
    }
}