<?php

namespace idoit\Module\Pro\Model\CategoryFolders;

use idoit\Model\Dao\Base;
use isys_exception_dao;
use isys_exception_database;

/**
 * Config model
 *
 * @copyright synetics GmbH
 * @license   http://www.i-doit.com/license
 */
class Config extends Base
{
    private const FIELDS = [
        'isys_category_config__id'                => 'id',
        'isys_category_config__isys_obj_type__id' => 'objectTypeId',
    ];

    /**
     * @param int $objectTypeId
     *
     * @return int|null
     * @throws isys_exception_dao
     * @throws isys_exception_database
     */
    public function create(int $objectTypeId): ?int
    {
        $objectTypeId = $this->convert_sql_id($objectTypeId);

        $sql = "INSERT INTO isys_category_config SET isys_category_config__isys_obj_type__id = {$objectTypeId};";

        if ($this->update($sql) && $this->apply_update()) {
            return (int) $this
                ->retrieve("SELECT isys_category_config__id AS id FROM isys_category_config WHERE isys_category_config__isys_obj_type__id = {$objectTypeId} LIMIT 1;")
                ->get_row_value('id');
        }

        return null;
    }

    /**
     * @param int $objectTypeId
     *
     * @return array|null
     * @throws isys_exception_database
     */
    public function getByObjectType(int $objectTypeId): ?array
    {
        $fields = $this->selectImplode(self::FIELDS);

        $sql = "SELECT {$fields} FROM isys_category_config WHERE isys_category_config__isys_obj_type__id = {$objectTypeId} LIMIT 1;";

        return $this->retrieve($sql)->get_row();
    }

    /**
     * @param int $id
     *
     * @return array|null
     * @throws isys_exception_database
     */
    public function getById(int $id): ?array
    {
        $fields = $this->selectImplode(self::FIELDS);

        $sql = "SELECT {$fields} FROM isys_category_config WHERE isys_category_config__id = {$id} LIMIT 1;";

        return $this->retrieve($sql)->get_row();
    }

    /**
     * @param int $id
     *
     * @return bool
     * @throws isys_exception_dao
     */
    public function delete(int $id): bool
    {
        $sql = "DELETE FROM isys_category_config WHERE isys_category_config__id = {$id} LIMIT 1;";

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