<?php
class Blog extends Buyers
{
    public function __construct()
    {
        // Создаем папку для ресайзов изображений, если её нет
        if(!is_dir($this->config->root_dir.$this->images->blog_images_dir))
            mkdir($this->config->root_dir.$this->images->blog_images_dir, 0755);
    }

    public function get_categories()
    {
        return $categories = array("nature" => "Природа", "health" => "Здоровье", "technology" => "Технологии", "games" => "Игры");
    }

    public function get_post($id)
    {
        $post = array();

        $condition = is_int($id) ? "id" : "url";
        $this->db->query("SELECT * FROM blog WHERE $condition = ? LIMIT 1", $id);
        if($res = $this->db->result())
            $post = $this->get_images(array($res->id => $res));

        return reset($post);
    }

    public function get_posts($filter = array())
    {
        // По умолчанию
        $limit = 100;
        $page = 1;
        $post_id_filter = '';
        $visible_filter = '';
        $keyword_filter = '';
        $tag_filter     = '';
        $category_filter = '';

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

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

        if(!empty($filter['id']))
            $post_id_filter = $this->db->placehold('AND id in(?@)', (array) $filter['id']);

        if(isset($filter['category']))
            $category_filter = $this->db->placehold('AND FIND_IN_SET(?, categories)', (string) $filter['category']);

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

        if(isset($filter['tag']))
            $tag_filter = $this->db->placehold('AND FIND_IN_SET(?, tags)', (string) $filter['tag']);

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

        $sql_limit = $this->db->placehold(' LIMIT ?, ? ', ($page-1)*$limit, $limit);
        $this->db->query("SELECT * FROM blog WHERE 1 $post_id_filter $category_filter $tag_filter $visible_filter $keyword_filter ORDER BY id DESC $sql_limit");
        if($posts = $this->db->results())
            $posts = $this->get_images($posts);

        return $posts;
    }

    public function count_posts($filter = array())
    {
        $post_id_filter = '';
        $visible_filter = '';
        $keyword_filter = '';
        $tag_filter     = '';
        $category_filter = '';

        if(!empty($filter['id']))
            $post_id_filter = $this->db->placehold('AND id IN(?@)', (array)$filter['id']);

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

        if(isset($filter['tag']))
            $tag_filter = $this->db->placehold('AND FIND_IN_SET(?, tags)', $filter['tag']);

        if(isset($filter['category']))
            $category_filter = $this->db->placehold('AND FIND_IN_SET(?, categories)', $filter['category']);

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

        $query = "SELECT COUNT(distinct id) as count FROM blog WHERE 1 $post_id_filter $category_filter $tag_filter $visible_filter $keyword_filter";

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

    public function add_post($post)
    {
        $date_query = !isset($post->date) ? ', date=NOW()' : '';
        $query = $this->db->placehold("INSERT INTO blog SET ?% $date_query", $post);
        $this->db->query($query);
        return $this->db->insert_id();
    }

    public function update_post($id, $post)
    {
        $query = $this->db->placehold("UPDATE blog SET ?% WHERE id IN(?@) LIMIT ?", $post, (array)$id, count((array)$id));
        $this->db->query($query);
        return $post;
    }

    public function delete_post($id)
    {
        if(empty($id))
            return false;

        if($post = $this->get_post(intval($id)))
        {
            $this->images->delete_images(array_keys($post->images));
            $this->db->query("DELETE FROM blog WHERE id = ? LIMIT 1", intval($id));
        }
        return true;
    }

    private function get_images($posts)
    {
        $images = array();

        if(empty($posts))
            return array();

        $tmp = $this->images->get_images(array('relation'=>'blog', 'relation_id'=>array_keys($posts)));
        foreach($tmp AS $pi)
            $images[$pi->relation_id][$pi->id] = $pi;

        foreach($posts AS $r)
        {
            if($r->images = $images[$r->id] ?? array())
                $r->image = reset($r->images);
            else
                $r->image = $this->images->no_image;
        }

        return $posts;
    }
}
