<?php

namespace idoit\Module\QCW\Model;

use idoit\Model\Dao\Base;
use idoit\Module\QCW\Provider\CRUDCount;
use isys_application;

/**
 * i-doit QCW object type group Model.
 *
 * @package     Modules
 * @subpackage  QCW
 * @author      Leonard Fischer <lfischer@i-doit.com>
 * @copyright   synetics GmbH
 * @license     http://www.i-doit.com/license
 */
class ObjectTypeGroup extends Base
{
    use CRUDCount;

    /**
     * @param  mixed $idConst May be the ID or constant.
     *
     * @return \isys_component_dao_result
     * @throws \isys_exception_database
     */
    public function load($idConst = null)
    {
        $condition = '';

        if ($idConst !== null) {
            if (is_numeric($idConst)) {
                $condition = 'WHERE isys_obj_type_group__id = ' . $this->convert_sql_id($idConst);
            } else {
                $condition = 'WHERE isys_obj_type_group__const = ' . $this->convert_sql_text($idConst);
            }
        }

        return $this->retrieve('SELECT *
            FROM isys_obj_type_group
            ' . $condition . '
            ORDER BY isys_obj_type_group__sort');
    }

    /**
     * Save method for a single object type group.
     *
     * @param  mixed $idConst May be the ID or constant.
     * @param  array $data
     *
     * @return bool
     */
    public function save($idConst = null, array $data)
    {
        $sqlData = [];

        if ($idConst === null) {
            $this->incrementCreate();

            // Use the standard way to create a new object type!
            return \isys_cmdb_dao::instance($this->m_db)
                ->insert_new_objtype_group($data['title'], $data['const'], 65535, ($data['visible'] ? C__RECORD_STATUS__NORMAL : C__RECORD_STATUS__BIRTH));
        }

        // ID-4369  This is necessary to prevent the user from (accidentally) overwriting language constants.
        if (isset($data['titleOrig'])) {
            if ($data['title'] != $data['titleOrig'] && $data['title'] != isys_application::instance()->container->get('language')
                    ->get($data['titleOrig'])) {
                $sqlData[] = 'isys_obj_type_group__title = ' . $this->convert_sql_text($data['title']);
            }
        } else {
            $sqlData[] = 'isys_obj_type_group__title = ' . $this->convert_sql_text($data['title']);
        }

        if (isset($data['visible'])) {
            $sqlData[] = 'isys_obj_type_group__status = ' .
                $this->convert_sql_int((isset($data['visible']) ? ($data['visible'] ? C__RECORD_STATUS__NORMAL : C__RECORD_STATUS__BIRTH) : C__RECORD_STATUS__NORMAL));
        }

        if (!count($sqlData)) {
            return true;
        }

        $sql = 'UPDATE isys_obj_type_group SET ' . implode(', ', $sqlData);

        if (is_numeric($idConst)) {
            $sql .= ' WHERE isys_obj_type_group__id = ' . $this->convert_sql_id($idConst);
        } else {
            $sql .= ' WHERE isys_obj_type_group__const = ' . $this->convert_sql_text($idConst);
        }

        $this->incrementUpdate();

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

    /**
     * @param   array $data
     *
     * @return  array
     */
    public function saveMultiple(array $data)
    {
        $data = array_filter($data);

        foreach ($data as &$objTypeGroup) {
            try {
                $objTypeGroup = $this->save((($objTypeGroup['id'] > 0) ? $objTypeGroup['id'] : null), $objTypeGroup);
            } catch (\Exception $e) {
                $objTypeGroup = $e->getMessage();
            }
        }

        return $data;
    }

    /**
     * @param   mixed $idConst May be the ID or constant.
     *
     * @return  boolean
     * @throws  \isys_exception_dao
     */
    public function delete($idConst)
    {
        if (empty($idConst)) {
            return true;
        }

        //move all objecttypes to orphaned group!
        $sql = 'UPDATE isys_obj_type
            SET isys_obj_type__isys_obj_type_group__id = ' . defined_or_default('C__OBJTYPE_GROUP__ORPHANED') . '
            WHERE isys_obj_type__isys_obj_type_group__id = (
                SELECT isys_obj_type_group__id FROM isys_obj_type_group ';
        if (is_numeric($idConst)) {
            $sql .= 'WHERE isys_obj_type_group__id = ' . $this->convert_sql_id($idConst) . ');';
        } else {
            $sql .= 'WHERE isys_obj_type_group__const = ' . $this->convert_sql_text($idConst) . ');';
        }
        $this->update($sql);

        //delete group
        $sql = 'DELETE FROM isys_obj_type_group ';

        if (is_numeric($idConst)) {
            $sql .= 'WHERE isys_obj_type_group__id = ' . $this->convert_sql_id($idConst) . ';';
        } else {
            $sql .= 'WHERE isys_obj_type_group__const = ' . $this->convert_sql_text($idConst) . ';';
        }

        $this->incrementDelete();

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

    /**
     * @param   array $data
     *
     * @return  array
     */
    public function deleteMultiple(array $data)
    {
        $data = array_filter($data);

        foreach ($data as &$objTypeGroup) {
            try {
                if ($objTypeGroup['id'] > 0) {
                    $objTypeGroup = $this->delete($objTypeGroup['id']);
                }
            } catch (\Exception $e) {
                $objTypeGroup = $e->getMessage();
            }
        }

        return $data;
    }
}
