<?php

class DModelModuleCustomLinks extends Model
{
    public function getFieldsQuery($data)
    {
        [
            'text' => $text,
            'link' => $link,
            'icon' => $icon,
            'order' => $order,
            'status' => $status,
            'parent' => $parent,
            'position' => $position,
        ] = $data;

        $text = (string) $text;
        $link = (string) $link;
        $icon = (string) $icon;
        $order = (int) $order;
        $status = (int) $status;
        $parent = (int) $parent;
        $position = (int) $position;

        $fields = "
            `text`='$text',
            `link`='$link',
            `icon`='$icon',
            `order`='$order',
            `status`='$status',
            `position`='$position'
        ";

        if ($parent) {
            $fields .= ",`parent`='$parent'";
        }

        return $fields;
    }

    public function add($data)
    {
        $sql = "INSERT INTO custom_links SET {$this->getFieldsQuery($data)};";
        $this->db->query($sql);
        return $this->db->getLastId();
    }

    public function edit($id, $data)
    {
        $sql = "UPDATE custom_links SET {$this->getFieldsQuery($data)} WHERE custom_links_id = $id";
        $this->db->query($sql);
        return $id;
    }

    public function delete($id)
    {
        $sql = "DELETE FROM custom_links WHERE custom_links_id = $id";
        $this->db->query($sql);
    }

    public function getList()
    {
        $sql = "SELECT * FROM custom_links";
        $query = $this->db->query($sql);
        return $query->rows;
    }

    public function getListId()
    {
        $sql = "SELECT custom_links_id FROM custom_links";
        $query = $this->db->query($sql);

        $ids = array_map(function ($customLinks) {
            return $customLinks['custom_links_id'];
        }, $query->rows);

        return $ids;
    }

    public function getListEnabledByPosition($position)
    {
        $sql = "SELECT * FROM custom_links WHERE `status` = 1 AND `position` = $position";
        $query = $this->db->query($sql);
        return $query->rows;
    }
}
