<?php
class Comments extends Buyers
{
    // Возвращает комментарий по id
    public function get_comment($id)
    {
        $query = $this->db->placehold("SELECT * FROM comments WHERE id=? LIMIT 1", intval($id));

        if($this->db->query($query))
            return $this->db->result();
        else
            return false;
    }

    // Возвращает комментарии, удовлетворяющие фильтру
    public function get_comments($filter = array())
    {
        // По умолчанию
        $limit = 100;
        $sql_limit = '';
        $page = 1;
        $keyword_filter = '';
        $approved_filter = '';
        $relation_id = '';
        $relation = '';

        if(isset($filter['limit']))
            $limit = max(1, intval($filter['limit']));

        if(isset($filter['page']))
            $page = max(1, intval($filter['page']));

        if(isset($filter['relation']))
            $relation = $this->db->placehold("AND relation = ?", $filter['relation']);

        if(isset($filter['relation_id']))
            $relation_id = $this->db->placehold("AND relation_id IN(?@)", (array) $filter['relation_id']);

        //показываем автору отзыв, независимо от его статуса
        if(isset($filter['approved']))
        {
            if(isset($filter['ip']))
                $ip = $this->db->placehold("OR ip=?", $filter['ip']);
            else
                $approved_filter = $this->db->placehold("AND (approved=?)", intval($filter['approved']));
        }

        if($limit)
            $sql_limit = $this->db->placehold('LIMIT ?, ?', ($page-1)*$limit, $limit);

        if(!empty($filter['keyword']))
        {
            $keywords = explode(' ', $filter['keyword']);
            foreach($keywords as $keyword)
                $keyword_filter .= $this->db->placehold(' AND (name LIKE ?~ OR text LIKE ?~)', $keyword, $keyword);
        }

        $query = $this->db->placehold("SELECT * FROM comments WHERE 1 $relation $relation_id $keyword_filter $approved_filter ORDER BY id DESC $sql_limit");
        $this->db->query($query);
        return $this->db->results();
    }

    // Количество комментариев, удовлетворяющих фильтру
    public function count_comments($filter = array())
    {
        $approved_filter = '';
        $keyword_filter = '';
        $relation_id = '';
        $relation = '';

        if(isset($filter['approved']))
            $approved_filter = $this->db->placehold('AND approved=?', intval($filter['approved']));

        if(isset($filter['relation']))
            $relation = $this->db->placehold("AND relation = ?", $filter['relation']);

        if(isset($filter['relation_id']))
            $relation_id = $this->db->placehold("AND relation_id IN(?@)", (array) $filter['relation_id']);

        if(!empty($filter['keyword']))
        {
            $keywords = explode(' ', $filter['keyword']);
            foreach($keywords as $keyword)
                $keyword_filter .= $this->db->placehold(' AND (name LIKE ?~ OR text LIKE ?~)', $keyword, $keyword);
        }

        $query = $this->db->placehold("SELECT count(distinct id) as count FROM comments WHERE 1 $relation $relation_id $keyword_filter $approved_filter");

        $this->db->query($query);
        return $this->db->result('count');

    }

    // Добавление комментария
    public function add_comment($comment)
    {
        // Определяем ip
        $comment->ip = $this->request->ip();

        // Если были одобренные комментарии от текущего ip, одобряем сразу
        $this->db->query("SELECT 1 FROM comments WHERE approved=1 AND ip=? LIMIT 1", $comment->ip);
        if($this->db->num_rows() > 0)
            $comment->approved = 1;

        $query = $this->db->placehold('INSERT INTO comments SET ?%, date = NOW()', $comment);
        if(!$this->db->query($query))
            return false;

        return $this->db->insert_id();
    }

    // Изменение комментария
    public function update_comment($id, $comment)
    {
        $query = $this->db->placehold("UPDATE comments SET ?% WHERE id IN (?@) LIMIT ?", $comment, (array)$id, count((array)$id));
        $post = $this->db->query($query);
        return $post;
    }

    // Удаление комментария
    public function delete_comment($id)
    {
        if(!empty($id))
        {
            if($comment = $this->get_comment(intval($id)))
                $this->images->delete_images(array_keys($comment->images));

            $query = $this->db->placehold("DELETE FROM comments WHERE id=? LIMIT 1", intval($id));
            $this->db->query($query);
        }
    }
}
