<?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, 'page' => $offset]);
        }

        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']) && $this->hasPermission('blog.create')) {
                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['ID']);
                    $post['comments'] = $this->BlogModel->getComments($post['ID']);
                    $post['tags'] = $this->BlogModel->getTags($post['ID']);
                    $post['hasLiked'] = isset($_SESSION['user']) && !empty($_SESSION['user']) ? $this->BlogModel->hasAlreadyLiked($post['ID'], $_SESSION['user']['ID']) : false;
                    $sameCategoryPosts = $this->BlogModel->getCategoryPostsByID($post['categories'], 3, $post['ID']);

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

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

                    $this->load->view('header', ['active' => 'blog', 'title' => $post['title'], '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', 'comment-item.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 = [
                    'success' => false,
                    'message' => '<b>Nicht eingeloggt!</b> Du musst in deinem Account angemeldet sein, um Kommentare auf Blog-Posts zu verfassen. Die Registrierung ist völlig kostenlos!',
                ];
            } else {
                $url = $this->input->post('url');

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

                $comment = $this->BlogModel->addCommentByUrl($url, $_SESSION['user']['ID'], $this->input->post('comment'), NULL);

                if ($comment == NULL) {
                    $result = [
                        'success' => false,
                        'message' => '<b>Post nicht gefunden.</b> Bitte lade die Seite erneut oder kontaktiere das Support-Team!',
                    ];
                } else {
                    $result = [
                        'success' => true,
                        'content' => [
                            'username' => $_SESSION['user']['username'],
                            'displayname' => $_SESSION['user']['displayname'],
                            'profilePicture' => $_SESSION['user']['profilePic'],
                        ]
                    ];
                }
            }

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

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

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

            $authorCache = [];

            $comments = $this->BlogModel->getCommentsByUrl($url);
            foreach ($comments as $comment) {
                $userID = $comment['userID'];
                if (isset($authorCache[$userID])) {
                    $author = $authorCache[$userID];
                } else {
                    $author = $this->BlogModel->getAuthorData($userID);
                    $authorCache[$userID] = $author;
                }
                $this->load->view('network/blog/comment_item', ['data' => $author, 'c' => $comment]);
            }
        }

        public function getReportModal()
        {
            header('Content-Type: application/json');

            $body = $this->load->view('blog/report_modal', [], true);
            echo json_encode([
                'success' => true,
                'title' => 'Kommentar melden',
                'body' => $body
            ]);
        }

        public function reportComment()
        {
            header('Content-Type: application/json');

            $commentID = intval($this->input->post('ID'));

            if ($commentID == 0) {
                echo json_encode(['success' => false, 'message' => 'Der angegebene Kommentar existiert nicht.']);
                exit;
            }

            $reason = $this->input->post('reason');
            $reasonText = trim($this->input->post('explanation'));

            if ($reason == '') {
                echo json_encode(['success' => false, 'message' => 'Bitte wähle einen Grund für deine Meldung aus.']);
                exit;
            }

            $allowedReasons = ['hatespeech', 'racism', 'terrorism', 'abuse', 'violence', 'copyright', 'spam', 'technical-issue'];

            if (!array_search($reason, $allowedReasons)) {
                echo json_encode(['success' => false, 'message' => 'Bitte wähle einen standardmäßig vorhandenen und validen Grund für die Meldung aus.']);
                exit;
            }

            if (!$this->BlogModel->isCommentIDValid($commentID)) {
                echo json_encode(['success' => true, 'message' => 'Der ausgewählte Kommentar ist nicht (mehr) vorhanden. Sollte es sich hierbei um ein Irrtum handeln, verfasse bitte über den Button unten rechts ein Feedback.']);
                exit;
            }

            $this->BlogModel->reportComment($commentID, $reason, $reasonText);

            echo json_encode(['success' => true, 'message' => 'Vielen Dank für das Melden dieses Kommentars. Wir werden schnellstmöglich angemessene Aktionen unternehmen.']);
        }

        public function getDeleteModal()
        {
            header('Content-Type: application/json');
            if (!isset($_SESSION['user'])) {
                echo json_encode(['success' => false, 'message' => 'Du musst eingeloggt sein, um die Posts deines Accounts zu löschen']);
                exit;
            }

            $commentID = intval($this->input->post('ID'));

            if ($commentID == 0) {
                echo json_encode(['success' => false, 'message' => 'Der angegebene Kommentar existiert nicht.']);
                exit;
            }

            $comment = $this->BlogModel->getComment($commentID);

            if ($comment == NULL) {
                echo json_encode(['success' => false, 'message' => 'Der angegebene Kommentar existiert nicht.']);
                exit;
            }

            $author = $this->BlogModel->getAuthorData($comment['userID']);

            if ($author == NULL || $author['ID'] !== $_SESSION['user']['ID']) {
                echo json_encode(['success' => false, 'message' => 'Du kannst keine Kommentare löschen, die dir nicht gehören.']);
                exit;
            }

            $body = $this->load->view('blog/delete_modal', ['author' => $author, 'comment' => $comment], true);

            echo json_encode(['success' => true, 'title' => 'Kommentar löschen', 'body' => $body]);
        }

        public function deleteComment()
        {
            header('Content-Type: application/json');
            if (!isset($_SESSION['user'])) {
                echo json_encode(['success' => false, 'message' => 'Du musst eingeloggt sein, um die Posts deines Accounts zu löschen']);
                exit;
            }

            $commentID = intval($this->input->post('ID'));

            if ($commentID == 0) {
                echo json_encode(['success' => false, 'message' => 'Der angegebene Kommentar existiert nicht.']);
                exit;
            }

            $comment = $this->BlogModel->getComment($commentID);

            if ($comment == null) {
                echo json_encode(['success' => false, 'message' => 'Der angegebene Kommentar existiert nicht.']);
                exit;
            }

            $author = $this->BlogModel->getAuthorData($comment['userID']);

            if ($author == NULL || $author['ID'] !== $_SESSION['user']['ID']) {
                echo json_encode(['success' => false, 'message' => 'Du kannst keine Kommentare löschen, die dir nicht gehören.']);
                exit;
            }

            $this->BlogModel->deleteComment($_SESSION['user']['ID'], $commentID);

            echo json_encode(['success' => true, 'message' => 'Der Kommentar wurde erfolgreich gelöscht.']);
        }

    }