<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Blog extends MY_Controller {

    function __construct() {
        parent::__construct('blog');
        $this->load->model('BlogModel', '', TRUE);
        $this->load->helper('url');
    }

    function index() {
        $offset = isset($_GET['page']) ? intval($_GET['page']) - 1 : 0;
        $data = $this->BlogModel->getAllPosts('', 5, $offset);

        $this->load->view('header', ['active' => 'blog', 'title' => 'Blog', 'additionalStyles' => ['blog.css']]);
        $this->load->view('blog/first', ['categories' => $this->BlogModel->getCategories()]);

        if(!empty($data)) {
            $pageCount = $this->BlogModel->getPostPageCount('', 5);
            $this->load->view('blog/postList', ['pageContent' => $data]);
        } else {
            $pageCount = 1;
            $this->load->view('blog/postListError', ['search' => '']);
        }

        $this->load->view('footer', ['additionalScripts' => ['lib/jquery.twbsPagination.min.js']]);
        $this->load->view('blog/pagination', ['pageCount' => $pageCount]);
    }

    function search($query = null) {
        if(isset($_GET['q'])) {
            redirect(base_url('blog/search/' . urlencode($this->input->get('q'))));
        } elseif($query == null) {
            redirect(base_url('blog'));
        } else {
            $query = $this->security->xss_clean(urldecode($query));
            $offset = isset($_GET['page']) ? intval($_GET['page']) - 1 : 0;
            $data = $this->BlogModel->getAllPosts($query, 5, $offset);

            $this->load->view('header', ['active' => 'blog', 'title' => 'Blog', 'additionalStyles' => ['blog.css']]);
            $this->load->view('blog/first', ['categories' => $this->BlogModel->getCategories()]);

            if(!empty($data)) {
                $pageCount = $this->BlogModel->getPostPageCount($query, 5);
                $this->load->view('blog/postList', ['pageContent' => $data]);
            } else {
                $pageCount = 1;
                $this->load->view('blog/postListError', ['search' => $query]);
            }

            $this->load->view('footer');
            $this->load->view('blog/pagination', ['pageCount' => $pageCount]);
        }
    }

    function category($category = null) {
        if($category == null) {
            redirect(base_url('blog'));
        } else {
            $category = urldecode($category);
            $offset = isset($_GET['page']) ? intval($_GET['page']) - 1 : 0;
            $data = $this->BlogModel->getCategoryPosts($category, 5, $offset);

            $this->load->view('header', ['active' => 'blog', 'title' => 'Blog', 'additionalStyles' => ['blog.css']]);
            $this->load->view('blog/first', ['categories' => $this->BlogModel->getCategories()]);

            if(!empty($data)) {
                $pageCount = $this->BlogModel->getPostPageCount('', 5);
                $this->load->view('blog/postList', ['pageContent' => $data]);
            } else {
                $pageCount = 1;
                $this->load->view('blog/postListError', ['search' => $category]);
            }

            $this->load->view('footer');
            $this->load->view('blog/pagination', ['pageCount' => $pageCount]);
        }
    }

    public function tag($tag = null) {
        if($tag == null) {
            redirect(base_url('blog'));
        }
        $tag = urldecode($tag);
        $offset = isset($_GET['page']) ? intval($_GET['page']) -1 : 0;
        $data = $this->BlogModel->getTagPosts($tag, 5, $offset);

        $this->load->view('header', ['active' => 'blog', 'title' => 'Blog', 'additionalStyles' => ['blog.css']]);
        $this->load->view('blog/first', ['categories' => $this->BlogModel->getCategories()]);

        if(!empty($data)) {
            $pageCount = $this->BlogModel->getPostPageCount('', 5);
            $this->load->view('blog/postList', ['pageContent' => $data]);
        } else {
            $pageCount = 1;
            $this->load->view('blog/postListError', ['search' => $tag]);
        }

        $this->load->view('footer');
        $this->load->view('blog/pagination', ['pageCount' => $pageCount]);
    }

    function add() {
        if(isset($_SESSION['user']) && $_SESSION['user']['rank'] >= 6) {
            redirect('/admin/blog/add');
        } else {
            redirect('/blog');
        }
    }

   function post($postTitle = null) {
        if($postTitle == null) {
            redirect("/blog");
        } elseif(isset($_GET['q'])) {
            redirect('/blog?q=' . $_GET['q']);
        } else {
            $post = $this->BlogModel->getPost($postTitle);
            if(empty($post)) {
                redirect('/blog');
            } else {
                $post['randomPosts'] = $this->BlogModel->getRandomPosts($post['postID']);
                $post['comments'] = $this->BlogModel->getComments($post['postID']);
                $post['tags'] = $this->BlogModel->getTags($post['postID']);
                $post['hasLiked'] = isset($_SESSION['user']) && !empty($_SESSION['user']) ? $this->BlogModel->hasAlreadyLiked($post['postID'], $_SESSION['user']['ID']) : false;
                $sameCategoryPosts = $this->BlogModel->getCategoryPostsByID($post['postCategoryID'], 3, $post['postID']);

                $post['prevPost'] = $this->BlogModel->getPrevPost($post['postID']);
                $post['nextPost'] = $this->BlogModel->getNextPost($post['postID']);

                $this->BlogModel->incrementViews($post['postID']);

                $this->load->view('header', ['active' => 'blog', 'title' => $post['postTitle'], 'additionalStyles' => ['posts_list.css', 'blog.css']]);
                $this->load->view('blog/first', ['categoryPosts' => $sameCategoryPosts, 'categories' => $this->BlogModel->getCategories()]);
                $this->load->view('blog/post', $post);
                $this->load->view('footer', ['additionalScripts' => ['lib/prism.js', 'blog.js']]);
            }
        }
    }

    function like() {
        if(!isset($_SESSION['user']) || $_SESSION['user']['username'] == NULL) {
            echo "no-user";
        } else {
            if(!$this->BlogModel->hasAlreadyLiked($_POST['postID'], $_SESSION['user']['ID'])) {
                echo 'true:';
                echo $this->BlogModel->addLike($_POST['postID'], $_SESSION['user']['ID'])['likeCount'];
            } else {
                echo 'false:';
                echo $this->BlogModel->removeLike($_POST['postID'], $_SESSION['user']['ID'])['likeCount'];
            }
        }
    }

    function comment() {
        if(!isset($_SESSION['user']) || $_SESSION['user']['username'] == NULL) {
            $result = ['type' => 'error', 'message' => 'Nicht eingeloggt'];
        } else {
            $url = $this->input->post('url');

            $url = str_replace('/blog/post/', '', $url);

            $comment = $this->BlogModel->addCommentByUrl($url, $_SESSION['user']['ID'], $this->input->post('comment'), false, NULL);
            $result = ['type' => 'success', 'content' => [
                'username' => $_SESSION['user']['username'],
                'displayname' => $_SESSION['user']['displayname'],
                'profilePic' => $_SESSION['user']['profilePic'],
                'date' => date('d.m.Y H: i \\U\\h\\r', strtotime($comment['date_created']))
            ]];
        }

        header("Content-Type: application/json");
        echo json_encode($result);
    }

    function getComments() {
        $url = $this->input->get('url');

        $url = str_replace('/blog/post/', '', $url);

        $comments = $this->BlogModel->getCommentsByUrl($url);
        foreach($comments as $comment) {
            $comment['author'] = $this->BlogModel->getAuthorData($comment['user_id']);
            $this->load->view('blog/comment', $comment);
        }
    }

}