<?php
/**
 * Class ContentManagerPanel
 * Class for the content manager admin panel methods.
 * @author Rihards Siliņš
 * @version 5 22/09/2016
 * @copyright MTC media Ltd
 */
class ContentManagerPanel
{
    /**
     * alert/error/success messages in the cm panel
     * @var string[][]
     */
    public $messages = [];

    /**
     * alert/error/success message types
     * @var string[]
     */
    public static $message_types = ['success', 'error', 'alert'];
    /**
     * Function that initializes ContentManagerPanel which in turn gets initializes at the top of content manager panel
     */
    public function __construct() {
        if (defined("CMS_PAGE_VERSIONING") && CMS_PAGE_VERSIONING === true) {
            if (!defined("CMS_PAGE_PREVIEW_ADV") || CMS_PAGE_PREVIEW_ADV !== true) {
                trigger_error(
                    "CMS_PAGE_VERSIONING is enabled but CMS_PAGE_PREVIEW_ADV isn't! Enable CMS_PAGE_PREVIEW_ADV",
                    E_USER_ERROR
                );
            } elseif (!defined("CMS_PAGE_PREVIEW") || CMS_PAGE_PREVIEW !== true) {
                trigger_error(
                    "CMS_PAGE_VERSIONING is enabled but CMS_PAGE_PREVIEW isn't! Enable CMS_PAGE_PREVIEW",
                    E_USER_ERROR
                );
            }
        } elseif (defined("CMS_PAGE_PREVIEW_ADV") && CMS_PAGE_PREVIEW_ADV === true) {
            if (!defined("CMS_PAGE_PREVIEW") || CMS_PAGE_PREVIEW !== true) {
                trigger_error(
                    "CMS_PAGE_PREVIEW_ADV is enabled but CMS_PAGE_PREVIEW isn't! Enable CMS_PAGE_PREVIEW",
                    E_USER_ERROR
                );
            }
        }
    }
    /**
     * ContentManagerPanel::setUserName
     * Username to be used by the content_manager panel
     * @param string $username
     */
    public function setUserName($username)
    {
        $_SESSION['content_manager']['username'] = $username;
    }

    /**
     * ContentManagerPanel::setUserId
     * User id to go with username to be used by the content_manager panel
     * @param int $user_id
     */
    public function setUserId($user_id)
    {
        $_SESSION['content_manager']['user_id'] = $user_id;
    }

    /**
     * ContentManagerPanel::getUserEmail
     * Get user email from a user id to be used by the content_manager panel
     * @param int $user_id
     * @return string $email
     */
    public function getUserEmail($user_id) {
        $admin_user = new AdminUser();
        $user = $admin_user->get_user($user_id);
        if (!empty($user['email'])) {
            return $user['email'];
        }
        return "";
    }

    /**
     * ContentManagerPanel::checkPermissions
     * Check current logged in adminuser permissions in relation to cms panel
     * @param int $admin_id admin id
     */
    public function checkPermissions($admin_id)
    {

        // check is mtcadmin permissions
        $is_mtcadmin = false;
        if ($admin_id == MTCADMIN_USERID) {
            $is_mtcadmin = true;
        }
        $this->setIsMtcadminSession($is_mtcadmin);

        // check publish permissions
        $is_publisher = false;
        if ($is_mtcadmin == true) {
            $is_publisher = true;
        }

        if (defined("CMS_PAGE_VERSIONING_PAGE_PUBLISH_ADMIN_MENU_ID") && !empty(CMS_PAGE_VERSIONING_PAGE_PUBLISH_ADMIN_MENU_ID)) {
            $admin_user = new AdminUser();
            $permissions = $admin_user->get_permissions();

            if (in_array(CMS_PAGE_VERSIONING_PAGE_PUBLISH_ADMIN_MENU_ID, $permissions)) {
                $is_publisher = true;
            }
        }
        $this->setIsPublisherSession($is_publisher);

    }

    /**
     * ContentManagerPanel::setIsPublisherSession()
     * Toggles session variable based on current settion state.
     * @param bool $is_publisher
     */
    public function setIsPublisherSession($is_publisher)
    {
        $_SESSION['content_manager']['is_publisher'] = $is_publisher;
    }

    /**
     * ContentManagerPanel::setIsMtcadminSession()
     * Toggles session variable based on current settion state.
     * @param bool $is_mtcadmin
     */
    public function setIsMtcadminSession($is_mtcadmin)
    {
        if (!isset($_SESSION['content_manager']['is_client_view'])) {
            $_SESSION['content_manager']['is_client_view'] = true;
        }

        if (isset($_SESSION['content_manager']['is_client_view']) && $_SESSION['content_manager']['is_client_view'] === true) {
            $_SESSION['content_manager']['is_mtcadmin'] = false;
        } else {
            $_SESSION['content_manager']['is_mtcadmin'] = $is_mtcadmin;
        }
    }

    /**
     * ContentManagerPanel::setIsMtcadminClientViewSession()
     * toggles is_client_view session variable based on current settion state.
     */
    public function setIsMtcadminClientViewSession()
    {
        if ($_SESSION['content_manager']['is_client_view'] === true) {
            $_SESSION['content_manager']['is_client_view'] = false;
        } else {
            $_SESSION['content_manager']['is_client_view'] = true;
        }
    }


    /**
     * ContentManagerPanel::getPagedataPageSelectOptions
     * Get pagedata page select options from the page tree
     * @param int $page_id
     * @param int $limit
     * @param int $check_published bool
     * @return string[] $select_options
     */
    public static function getPagedataPageSelectOptions($page_id, $limit, $check_published) {
        $select_options = array();
        $tree_options = array(
            'check_innav' => false,
            'check_published' => $check_published,
        );
        $page_tree = CMSNav::tree($page_id, $limit, $tree_options);
        $select_options = self::flattenThePageTree($page_tree, $tree_options);
        return $select_options;
    }

    /**
     * ContentManagerPanel::flattenThePageTree
     * Flatten the page tree into a one dimension array to be used as select options
     * @param mixed[][] $page_tree
     * @param mixed[] $tree_options
     * @param int $n
     * @param string[] $select_options
     * @return string[] $select_options
     */
    public static function flattenThePageTree($page_tree, $tree_options, $n = 0, $select_options = array()) {
        foreach ($page_tree as $page_branch) {
            $indent = "";
            for ($i = 0; $i < $n; $i++) {
                $indent .= "-";
            }
            $select_options[$page_branch['id']] = $indent.$page_branch['title'];
            if (!empty($page_branch['sub'])) {
                $select_options = self::flattenThePageTree($page_branch['sub'], $tree_options, $n + 1, $select_options);
            }
        }
        return $select_options;
    }

    /**
     * ContentManagerPanel::getPagedataSelectOptions
     * Parse page_list_item_data options to get select options
     * @param string $pagedata_options
     * @return string[] $select_options
     */
    public static function getPagedataSelectOptions($pagedata_options) {
        if (preg_match("/Page\(([0-9]+)(,true)?(,true)?\)/", $pagedata_options, $matches)) {
            $limit = 1;
            if (isset($matches[2])) {
                $limit = PHP_INT_MAX;
            }

            $check_published = false;
            if (isset($matches[3])) {
                $check_published = true;
            }
            return self::getPagedataPageSelectOptions($matches[1], $limit, $check_published);
        } elseif (preg_match("/^json_url:(.+)$/", $pagedata_options, $matches)) {
            if ( !preg_match("/^http/", $matches[1]) ) {
                $url = config('app.url').$matches[1];
            } else {
                $url = $matches[1];
            }
            $file_get_contents_context_options = array(
                "http" => array(
                    "method" => "GET",
                    "header"=>"Accept-language: en\r\n" .
                    "Cookie: ".session_name()."=".session_id()."\r\n"
                ),
                'ssl' => [
                    'verify_peer'=> false,
                    'verify_peer_name'=> false,
                ],
            );


                $file_get_contents_context = stream_context_create($file_get_contents_context_options);
                session_write_close();// this is the key


                $json_url_contents = file_get_contents($url, false, $file_get_contents_context);

            if (!empty($json_url_contents)) {
                if (($result = json_decode($json_url_contents)) !== NULL) {
                    return $result;
                }
            }
        } elseif (($result = json_decode($pagedata_options)) !== NULL) {
            return $result;
        }
        return array();
    }

    /**
     * ContentManagerPanel::formatUpdatedDatetime
     * Format updated_datetime
     * @param DateTime object $updated_datetime
     * @return string $formated_updated_datetime
     */
    public static function formatUpdatedDatetime(DateTime $updated_datetime) {
        $result = "";
        $result .= " ".util::human_time_diff($updated_datetime->format("U"));
        $result .= " (".$updated_datetime->format("H:i jS F Y").")";
        return $result;
    }

    /**
     * Merge in session messages with panel messages. Then unset the session ones.
     */
    public function mergeSessionMessages()
    {
        foreach (self::$message_types as $message_type) {
            if (empty($_SESSION['content_manager'][$message_type])) {
                continue;
            }
            if (!isset($this->messages[$message_type])) {
                $this->messages[$message_type] = [];
            }
            $this->messages[$message_type] = array_merge(
                $this->messages[$message_type],
                $_SESSION['content_manager'][$message_type]
            );
            unset($_SESSION['content_manager'][$message_type]);
        }
    }

    /**
     * Add message to panel messages
     * @param string $message
     * @param string $message_type
     */
    public static function addMessage($message, $message_type = "error")
    {
        if (!isset($_SESSION['content_manager'])) {
            $_SESSION['content_manager'] = [];
        }
        $type = "error";
        if (in_array($message_type, self::$message_types)) {
            $type = $message_type;
        }
        if (!isset($_SESSION['content_manager'][$type])) {
            $_SESSION['content_manager'][$type] = [];
        }
        $_SESSION['content_manager'][$type][] = $message;
    }

    /**
     * Load page for manipulation in the content manager panel
     * @param int $page_id
     * @return Page Object $page
     */
    public static function loadPage($page_id, $load_language = true) {
        $page = new Page();
        $page->get($page_id);
        if ($load_language && defined('CMS_MULTI_LANG') && CMS_MULTI_LANG === true && $page->type != 'temp') {
            if (empty($_SESSION['content_manager']['language'])) {
                $_SESSION['content_manager']['language'] = '';
            }
            $page->setLanguage($_SESSION['content_manager']['language']);
            $page->get($page_id);
        }
        return $page;
    }

    /**
     * Report error to and die if encountered an unrecoverable error during some of the cms ajax scripts
     * @param string $error_message
     * @param string $http_status
     * @param string $error_message_type optional, default 'error' also can be 'alert' (or 'success'?)
     */
    public static function messageAndDie($error_message, $http_status, $error_message_type = "error") {
        header($http_status);
        ContentManagerPanel::addMessage($error_message, $error_message_type);
        die($error_message);
    }
}
