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

class Blog extends MY_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->model('BlogModel', '', TRUE);
        $this->load->model('FileModel', '', TRUE);
    }

    public function index()
    {
        $this->neededPermission('blog.view');
        $posts = $this->BlogModel->getPostList(false);
        $this->load->view('admin/sidebar', ['title' => 'Alle Blog-Posts']);
        $this->load->view('admin/blog_posts', ['posts' => $posts]);
        $this->load->view('admin/footer');
    }

    public function tags() {
        $this->neededPermission('blog.view');

        $tags = $this->BlogModel->getAllTags();
        $tags = $this->BlogModel->mergeTagInfo($tags);

        $this->load->view('admin/sidebar', ['title' => 'Alle Blog-Tags']);
        $this->load->view('admin/blog_tags', ['tags' => $tags]);
        $this->load->view('admin/footer', ['additionalScripts' => 'all-blog-tags.js']);
    }

    public function sendEdit()
    {
        header('Content-Type: application/json');
        if (!isset($_SESSION['user']) || empty($_SESSION['user']) || $_SESSION['user']['rank'] < 6) {
            echo json_encode(['success' => false, 'message' => 'Du musst eingeloggt sein, um Blog-Posts zu verfassen']);
            exit;
        }

        $postID = $this->input->post('postID');
        $postID = is_numeric($postID) && is_int(intval($postID)) ? intval($postID) : -2;

        if ($postID == -2) {
            echo json_encode(['success' => false, 'message' => 'Ungültige Post-ID angegeben. Bitte versuche es später erneut']);
            exit;
        }

        $contentID = $this->input->post('contentID');
        $contentID = is_numeric($contentID) && is_int(intval($contentID)) ? intval($contentID) : -2;

        $translationID = $this->input->post('translationID');
        $translationID = is_numeric($translationID) && is_int(intval($translationID)) ? intval($translationID) : -2;

        $postImage = $this->input->post('postImage');
        $postTitle = $this->input->post('postTitle');
        $postDescription = $this->input->post('postDescription');
        $postContent = $this->input->post('postContent');

        $postPublishDate = $this->input->post('postPublishDate');
        $postPublishDate = date("Y-m-d H:i:s", strtotime($postPublishDate));

        $postUrl = $this->input->post('postUrl');
        $postCategory = $this->input->post('postCategory');
        $postTags = $this->input->post('postTags');

        $postLang = $this->input->post('postLanguage');
        $postLang = $postLang !== NULL ? $postLang : 'de';

        if(strlen($postUrl) == 0) {
            echo json_encode(['success' => false, 'message' => 'Es wurde keine Post-URL angegeben.']);
            exit;
        }
        if(strlen($postUrl) < 4) {
            echo json_encode(['success' => false, 'message' => 'Die angegebene Post-URL ist zu kurz. Sie muss mindestens 4 Zeichen umfassen, um eine eindeutige Zuordnung zu ermöglichen.']);
            exit;
        }

        if ($postID == -1 || $translationID == -1) { // Create new blog post
            if ($postID == -1) {
                $postID = $this->BlogModel->createNewPostDraft($_SESSION['user']['ID']);

                if($this->BlogModel->postUrlExisting($postUrl)) {
                    echo json_encode(['success' => false, 'message' => 'Die angegebene Post-URL bereits vorhanden.']);
                    exit;
                }
            }
            $translationID = $this->BlogModel->createNewTranslation($postID, $postLang);
        }

        if ($contentID < 0) {
            $contentID = $this->BlogModel->createNewContentDraft($postID);
        }

        $this->BlogModel->updatePostDraft($postID, $postUrl, $postCategory, $postPublishDate, $postImage);
        $this->BlogModel->updateContentDraft($contentID, $postContent, $postLang);
        $this->BlogModel->updateTranslation($translationID, $postTitle, $postDescription);

        if(!empty($postTags)) {
            $this->BlogModel->deleteAllPostTags($postID);
            foreach ($postTags as $postTag) {
                $tagID = $this->BlogModel->createTagIfNotExists($postTag);
                $this->BlogModel->addPostTagByID($postID, $tagID);
            }
        }

        echo json_encode(['success' => true, 'message' => 'Der Entwurf wurde erfolgreich gespeichert.', 'postID' => $postID, 'contentID' => $contentID, 'translationID' => $translationID]);
    }

    public function publishPost()
    {
        header('Content-Type: application/json');
        if (!isset($_SESSION['user']) || empty($_SESSION['user']) || $_SESSION['user']['rank'] < 6) {
            echo json_encode(['success' => false, 'message' => 'Du musst eingeloggt sein, um Blog-Posts zu verfassen']);
            exit;
        }

        $postID = $this->input->post('postID');
        $postID = is_numeric($postID) && is_int(intval($postID)) ? intval($postID) : -2;

        if ($postID < 0) {
            echo json_encode(['success' => false, 'message' => 'Ungültige Post-ID angegeben. Bitte versuche es später erneut']);
            exit;
        }

        $contentIDs = $this->input->post('contentIDs');
        $contentPublished = FALSE;
        foreach ($contentIDs as $lang => $contentID) {
            $contentID = is_numeric($contentID) && is_int(intval($contentID)) ? intval($contentID) : -2;

            if($contentID < 0) {
                continue;
            }

            $this->BlogModel->publishContentDraft($_SESSION['user']['ID'], $contentID, $postID, $lang);
            $contentPublished = TRUE;
        }

        if (!$contentPublished) {
            echo json_encode(['success' => false, 'message' => 'Ungültige Content-ID angegeben. Bitte versuche es später erneut']);
            exit;
        }

        $this->BlogModel->publishPostDraft($postID);

        echo json_encode(['success' => true, 'message' => 'Der Post wurde erfolgreich veröffentlicht.']);
    }

    public function getTranslations()
    {
        header('Content-Type: application/json');
        if (!isset($_SESSION['user']) || empty($_SESSION['user']) || $_SESSION['user']['rank'] < 6) {
            echo json_encode(['status' => 'error', 'message' => 'Du musst eingeloggt sein, um Blog-Posts zu verfassen']);
            exit;
        }

        $postID = $this->input->post('postID');
        $postID = is_numeric($postID) && is_int(intval($postID)) ? intval($postID) : -2;

        if ($postID < 0) {
            echo json_encode(['status' => 'error', 'message' => 'Ungültige Post-ID angegeben. Bitte versuche es später erneut']);
            exit;
        }

        $translations = $this->BlogModel->getPostTranslations($postID);
        echo json_encode(['status' => 'success', 'translations' => $translations]);
    }

    public function getPost() {
        header('Content-Type: application/json');
        if (!isset($_SESSION['user']) || empty($_SESSION['user']) || $_SESSION['user']['rank'] < 6) {
            echo json_encode(['status' => 'error', 'message' => 'Du musst eingeloggt sein, um Blog-Posts zu verfassen.']);
            exit;
        }

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

        if(!is_numeric($postID)) {
            echo json_encode(['status' => 'error', 'message' => 'Es wurde eine ungültige Post-ID angegeben.']);
            exit;
        }

        $postData = $this->BlogModel->getPostDataByID($postID);

        if(empty($postData)) {
            echo json_encode(['status' => 'error', 'message' => 'Es wurde kein Post mit der angegebenen Post-ID gefunden.']);
            exit;
        }

        echo json_encode(['status' => 'success', 'postData' => $postData[0]]);
    }

    public function getContent() {
        header('Content-Type: application/json');
        if (!isset($_SESSION['user']) || empty($_SESSION['user']) || $_SESSION['user']['rank'] < 6) {
            echo json_encode(['status' => 'error', 'message' => 'Du musst eingeloggt sein, um Blog-Posts zu verfassen.']);
            exit;
        }

        $postID = intval($this->input->post('postID'));
        $contentID = intval($this->input->post('contentID'));
        $language = $this->input->post('lang');

        if(!is_numeric($postID)) {
            echo json_encode(['status' => 'error', 'message' => 'Es wurde eine ungültige Post-ID angegeben.']);
            exit;
        }

        if(!is_numeric($contentID)) {
            echo json_encode(['status' => 'error', 'message' => 'Es wurde kein Content mit der angegebenen Content-ID gefunden.']);
            exit;
        }

        $contentData = $this->BlogModel->getContentDataByID($postID, $contentID, $language);

        if(empty($contentData)) {
            echo json_encode(['status' => 'error', 'message' => 'Es wurde kein Content mit der angegebenen Content-ID gefunden.']);
            exit;
        }

        echo json_encode(['status' => 'success', 'contentData' => $contentData[0]]);
    }

    public function getTranslationData() {
        header('Content-Type: application/json');
        if (!isset($_SESSION['user']) || empty($_SESSION['user']) || $_SESSION['user']['rank'] < 6) {
            echo json_encode(['status' => 'error', 'message' => 'Du musst eingeloggt sein, um Blog-Posts zu verfassen.']);
            exit;
        }

        $postID = intval($this->input->post('postID'));
        $translationID = intval($this->input->post('translationID'));
        $language = $this->input->post('lang');

        if(!is_numeric($postID)) {
            echo json_encode(['status' => 'error', 'message' => 'Es wurde eine ungültige Post-ID angegeben.']);
            exit;
        }

        if(!is_numeric($translationID)) {
            echo json_encode(['status' => 'error', 'message' => 'Es wurde kein Übersetzung mit der angegebenen ID gefunden.']);
            exit;
        }

        $translationData = $this->BlogModel->getTranslationDataByID($postID, $translationID, $language);

        if(empty($translationData)) {
            echo json_encode(['status' => 'error', 'message' => 'Es wurde kein Übersetzung mit der angegebenen ID gefunden.']);
            exit;
        }

        echo json_encode(['status' => 'success', 'translationData' => $translationData[0]]);
    }

    public function getPostTags() {
        header('Content-Type: application/json');
        if (!isset($_SESSION['user']) || empty($_SESSION['user']) || $_SESSION['user']['rank'] < 6) {
            echo json_encode(['success' => false, 'message' => 'Du musst eingeloggt sein, um Blog-Posts zu verfassen.']);
            exit;
        }

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

        if(!is_numeric($postID)) {
            echo json_encode(['success' => false, 'message' => 'Es wurde eine ungültige Post-ID angegeben.']);
            exit;
        }

        $postTags = $this->BlogModel->getTags($postID);

        echo json_encode(['success' => true, 'tags' => $postTags]);
    }

    public function edit($postID = -1, $lang = "de")
    {
        if (!isset($_SESSION['user']) || empty($_SESSION['user']) || $_SESSION['user']['rank'] < 6) redirect(base_url('login'));

        $translations = ['de' => -1];
        $contents = ['de' => -1];

        if(!$postID != -1) {
            if($this->BlogModel->postIDExisting($postID)) {
                $postTranslations = $this->BlogModel->getPostTranslationIDs($postID);
                foreach ($postTranslations as $postTranslation) {
                    $translations[$postTranslation['language']] = $postTranslation['postTranslationID'];
                }

                $postContents = $this->BlogModel->getPostContentIDs($postID);
                foreach ($postContents as $postContent) {
                    $contents[$postContent['language']] = $postContent['contentID'];
                }
            }
        }

        $categories = $this->BlogModel->getCategories();
        $this->load->view('admin/sidebar', ['title' => 'Blog-Post erstellen', 'additionalStyles' => ['lib/bootstrap-tagsinput.css', 'lib/bootstrap-tagsinput-typeahead.css']]);
        $this->load->view('admin/blog_edit', ['categories' => $categories, 'postID' => $postID, 'contents' => $contents, 'translations' => $translations, 'postLanguage' => $lang]);
        $this->load->view('admin/footer', ['additionalScripts' => ['lib/typeahead.bundle.min.js', 'lib/bootstrap-tagsinput.min.js', 'lib/highlight.pack.js', 'lib/quill.min.js', 'blog-edit.js']]);

    }

    public function history($postID = NULL)
    {
        if (!isset($_SESSION['user']) || empty($_SESSION['user']) || $_SESSION['user']['rank'] < 6) redirect(base_url('login'));
        if ($postID === NULL) redirect(base_url('admin/blog'));

        $content['de'] = $this->BlogModel->getAllContentVersions($postID, 'de');
        $content['en'] = $this->BlogModel->getAllContentVersions($postID, 'en');
        $content['fr'] = $this->BlogModel->getAllContentVersions($postID, 'fr');

        $this->load->view('admin/sidebar', ['title' => 'Geschichte']);
        $this->load->view('admin/blog_history', ['content' => $content]);
        $this->load->view('admin/footer');
    }

    public function new_category()
    {
        if (!isset($_SESSION['user']) || empty($_SESSION['user']) || $_SESSION['user']['rank'] !== 'admin') redirect(base_url('login'));
        $name = filter_input(INPUT_POST, "name");
        $display_name = filter_input(INPUT_POST, "display_name");
        if ($name !== NULL && $display_name !== NULL) {
            $category = $this->BlogModel->getCategoryIDAfterInsert($name, $display_name);
            echo $category;
        }
    }

    public function delete()
    {
        if (!isset($_SESSION['user']) || empty($_SESSION['user']) || $_SESSION['user']['rank'] < 6) redirect(base_url('login'));
        $id = filter_input(INPUT_POST, "id");
        echo $this->BlogModel->deletePost($id);
    }

    public function deleteFinally()
    {
        if (!isset($_SESSION['user']) || empty($_SESSION['user']) || $_SESSION['user']['rank'] < 6) redirect(base_url('login'));
        $id = filter_input(INPUT_POST, "id");
        $this->BlogModel->deletePostFinally($id);
    }

    public function restore()
    {
        if (!isset($_SESSION['user']) || empty($_SESSION['user']) || $_SESSION['user']['rank'] < 6) redirect(base_url('login'));
        $id = filter_input(INPUT_POST, "id");
        echo $this->BlogModel->restorePost($id);
    }

    public function trashbin()
    {
        if (!isset($_SESSION['user']) || empty($_SESSION['user']) || $_SESSION['user']['rank'] < 6) redirect(base_url('login'));
        $posts = $this->BlogModel->getPostList(true);
        $this->load->view('admin/sidebar', ['title' => 'Alle Blog-Posts']);
        $this->load->view('admin/blog_posts', ['posts' => $posts, 'trashbin' => true]);
        $this->load->view('admin/footer');
    }

    public function tagsList()
    {
        if (!isset($_SESSION['user']) || empty($_SESSION['user']) || $_SESSION['user']['rank'] < 6) {
            echo '{"type":"error", "message":"<b>Fehler beim Upload!</b> Aufgrund von zu geringen Zugriffsrechten konnte das Bild leider nicht hochgeladen werden <i>Sollte es sich dabei um ein Irrtum handeln, kontaktiere bitte einen Admin über das Kontakformular.</i>"}';
            header("Content-Type: application/json");
            exit;
        }
        $result = array_map(function($value) {
            return $value['display_name'];
        }, $this->BlogModel->getAllTags());
        echo json_encode($result);
//        echo json_encode($this->BlogModel->getAllTags());
        header("Content-Type: application/json");
    }

    public function updatePreview() {
        header('Content-Type: application/json');
        if(!$this->hasPermission('blog.create')) {
            echo json_encode(['success' => false, 'message' => 'Du hast nicht genügend Rechte, um die Vorschau anzusehen.']);
            exit;
        }

        if(!isset($_POST['postTitle']) || !isset($_POST['postDesc']) || !isset($_POST['postContent'])) {
            exit;
        }

        if(!isset($_POST['previewID'])) {
            $previewID = substr(md5(uniqid() . date(time())), 0, 16);
        } else {
            $previewID = $_POST['previewID'];
        }

        $_SESSION['preview_' . $previewID] = [
            'title' => $_POST['postTitle'],
            'desc' => $_POST['postDesc'],
            'content' => $_POST['postContent'],
        ];

        echo json_encode(['success' => true, 'previewID' => $previewID, 'session' => $_SESSION['preview_' . $previewID]]);
    }


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

        if(!$this->hasPermission('blog.create')) {
            echo json_encode([]);
            exit;
        }

        $templates = [
            new Template('Verweis auf anderen Post', 'Verlinkungs-Karte für weiteren Blog-Post', 'post_reference'),
        ];

        foreach ($templates as $template) {
            $template->content = $this->load->view('admin/blog/templates/' . $template->content, '', true);
        }

        echo json_encode($templates);
    }

    public function preview() {
        $this->neededPermission('blog.create');

        $previewID = $_GET['id'];

        if(!isset($_SESSION['preview_' . $previewID])) {
            redirect('admin/blog');
        }

        $this->load->view('header', ['active' => 'blog', 'title' => 'Vorschau', 'additionalStyles' => ['posts_list.css', 'blog.css']]);
        $this->load->view('blog/first', ['categoryPosts' => [], 'categories' => $this->BlogModel->getCategories()]);
        $this->load->view('admin/blog_post_preview', $_SESSION['preview_' . $previewID]);
        $this->load->view('footer', ['additionalScripts' => ['lib/prism.js', 'blog.js']]);
    }
}

class Template {
    public $title;
    public $desc;
    public $content;

    /**
     * Template constructor.
     * @param $title
     * @param $desc
     * @param $content
     */
    public function __construct($title, $desc, $content)
    {
        $this->title = $title;
        $this->desc = $desc;
        $this->content = $content;
    }
}