<?php

class CTLPPU_Controllers_Posts extends CTLPPU_Classes_FrontController
{
    public $updated_posts;
    public $options;
    public $posts;


    function __construct()
    {
        parent::__construct();
        $this->options = (object)CTLPPU_Classes_Tools::getOptions();
    }

    function init()
    {
        //Fontawesome
        CTLPPU_Classes_ObjController::getClass('CTLPPU_Classes_DisplayController')->loadMediaBootstrap('font-awesome.min');

        //Bootstrap
        CTLPPU_Classes_ObjController::getClass('CTLPPU_Classes_DisplayController')->loadMediaBootstrap('bootstrap.min');
        CTLPPU_Classes_ObjController::getClass('CTLPPU_Classes_DisplayController')->loadMediaBootstrap('bootstrap-theme.min');

        //Global css
        CTLPPU_Classes_ObjController::getClass('CTLPPU_Classes_DisplayController')->loadMedia('ctlppu_global');

        /* Sync user if not synced */
        if (!CTLPPU_Classes_ObjController::getClass('CTLPPU_Models_User')->isSynced())
            CTLPPU_Classes_ObjController::getClass('CTLPPU_Models_User')->syncUser();


        if ($this->model->hasUpdatedPosts()) {
            CTLPPU_Classes_ObjController::getClass('CTLPPU_Classes_DisplayController')->loadMedia('ctlppu_posts');
            CTLPPU_Classes_ObjController::getClass('CTLPPU_Classes_DisplayController')->loadMedia('ctlppu_jquery.datatables.min');
            CTLPPU_Classes_ObjController::getClass('CTLPPU_Classes_DisplayController')->loadMedia('ctlppu_datatable_theme');


            $this->posts = $this->model->mergeFields($this->getPosts());
            echo $this->getView('Posts');
        } else {
            $this->_savePosts();
            CTLPPU_Classes_ObjController::getClass('CTLPPU_Classes_DisplayController')->loadMedia('ctlppu_preposts');
            echo $this->getView('PrePosts');
        }


        return $this;
    }

    private function getPosts()
    {

        $posts = json_decode(CTLPPU_Classes_Tools::ctlppu_remote_get(
            _CTLPPU_API_PATH_ . 'posts/get'
            , array(
            "website_id" => $this->options->website_id,
            "fields" => json_encode($this->options->ctlppu_display_fields),
            "items" => _CTLPPU_ITMS_
        )), true);

        if (isset($posts['posts']) && count((array)$posts['posts']) > 0) {
            return $posts['posts'];
        }
        return false;
    }

    protected function _savePosts()
    {

        CTLPPU_Classes_Tools::ctlppu_remote_post(
	        _CTLPPU_API_PATH_ . 'posts/add'
            , CTLPPU_Classes_ObjController::getClass('CTLPPU_Models_Posts')->getSavePostsArgs());
    }

    /**
     * Called when Post action is triggered
     *
     * @return void
     */
    public function action()
    {
        parent::action();
        switch (CTLPPU_Classes_Tools::getValue('action')) {
            case 'ctlppu_getapiposts':
                CTLPPU_Classes_Tools::setHeader('json');
                if (CTLPPU_Classes_ObjController::getClass('CTLPPU_Models_User')->isSynced()) {
                    $posts = $this->getPosts();
                    if ($posts) {
                        $this->_updatePostsOptions();
                        echo json_encode(array("msg" => "Posts are ready"));
                    } else {
                        echo json_encode(array("info" => "This may take a few moments..."));
                    }
                } else {
                    CTLPPU_Classes_ObjController::getClass('CTLPPU_Models_User')->syncUser();
                    echo json_encode(array());
                }
                break;
        }
        exit();
    }

    protected function _updatePostsOptions()
    {
        CTLPPU_Classes_Tools::saveOptions("last_update", strtotime(gmdate('Y-m-d H:i:s')));
        CTLPPU_Classes_Tools::saveOptions("next_check", strtotime(gmdate('Y-m-d H:i:s', strtotime(ctlppu_get_update_frequency()))));
        CTLPPU_Classes_Tools::saveOptions("fields_hash", md5(serialize($this->options->ctlppu_display_fields)));

    }
    /**
     * Get Field Type social | seo ...
     *
     * @param $field
     * @return string
     */
    public function getFieldType($field)
    {

        $availableFields = (array)$this->model->getFieldsSource();

        foreach($availableFields as $key => $fieldCategory){
            $fieldCategory = (array)$fieldCategory;
            foreach($fieldCategory['columns'] as $keyColumn => $column){
                if($keyColumn == $field){
                    return $column['subcategory'];
                }
            }
        }

    }

    /**
     * @param $post
     * @param string $where
     * @return string|void
     */
    public function getPostView($post, $where = '')
    {
        $view = "";

        if (empty($post) || !isset($post) || !isset($post['title']))
            return $view;


        switch ($where) {
            case '':
                switch ($post['type']) {
                    case 'bool':
                        $view .= $post['title'] . ': ';
                        $view .= ($post['value']) ? 'Yes' : 'No';
                        break;
                    case 'string':
                        $view .= $post['title'] . ': ';
                        $view .= (strlen($post['value']) > 0) ? ' <span title="' . $post['value'] . '">' . substr($post['value'], 0, 10) . ' ... ' . '</span>' : 'No';
                        break;
                    case 'int':
                        $view .= $post['title'] . ': ';
                        $view .= $this->model->count_format($post['value']);
                        break;
                    case 'keyword':

                        $keywords = json_decode($post['value']);
                        if (!empty($keywords)) {
                            $view .= (count($keywords) > 0) ? '<span title="' . $keywords[0] . '">' . "Keyword: " . $keywords[0] . '</span>' : "";

                        } else {
                            $view .= __("Not optimized for any keyword", _CTLPPU_PLUGIN_NAME_);
                        }
                        break;
                    case 'float':
                        $view .= $post['title'] . ': ';
                        $view .= $post['value'];
                        break;
                    default:
                        if (isset($post['title']) && isset($post['value']))
                            return $post['title'] . ': ' . ($post['value']);
                        break;
                }
                break;
            case 'table':
                switch ($post['type']) {
                    case 'bool':
                        $view .= ($post['value']) ? 'Yes' : 'No';
                        break;
                    case 'string':
                        $view .= (strlen($post['value']) > 0) ? substr($post['value'], 0, 20) . '...' : 'No';
                        break;
                    case 'int':
                        $view .= $this->model->count_format($post['value']);
                        break;
                    case 'float':
                        $view .= $post['value'];
                        break;
                    default:
                        return $post['value'];
                        break;
                }
        }
        return $view;
    }

    public function getPostTooltip($post, $field)
    {
        if (empty($post) || !isset($field)) {
            return false;
        }

        $tooltip = "";
        switch ($field) {
            case 'seo_speed':
                $tooltip .= $post['value'] . " " . $post['description'] . ".";
                $tooltip .= ($post['value'] > 1) ? __(" This page speed is too low.", _CTLPPU_PLUGIN_NAME_) : __(" Looks good.", _CTLPPU_PLUGIN_NAME_);
                break;
            case 'seo_gzip':
                $tooltip .= $post['description'];
                $tooltip .= ($post['value']) ? __(" You have gzip on this article that is okay.", _CTLPPU_PLUGIN_NAME_) : __(" Install some cache plugin.", _CTLPPU_PLUGIN_NAME_);
                break;

            case 'seo_keywords':
                $tooltip .= $post['description'];
                $tooltip .= ($post['value'] <> '' && count(json_decode($post['value'])) > 0) ? __(" This article is optimized for: ", _CTLPPU_PLUGIN_NAME_) . implode(", ", json_decode($post['value'])) . " keywords" : "";
                break;

            case'seo_description':
                $tooltip .= $post['description'];
                $tooltip .= (strlen($post['value']) == 0) ? __(" You don't have any meta description for this article.", _CTLPPU_PLUGIN_NAME_) : __(" This article's meta description is ", _CTLPPU_PLUGIN_NAME_) . '<strong>' . htmlentities($post['value']) . '</strong>';
                break;

            case 'seo_metaOpenGraph':
                $tooltip .= $post['description'];
                $tooltip .= ($post['value']) ? __(" This article has Open Graph.", _CTLPPU_PLUGIN_NAME_) : __(" This article doesn't have Open Graph. Squirrly Plugin may help you with this. ", _CTLPPU_PLUGIN_NAME_);
                break;

            case 'seo_metaTwitterCard':
                $tooltip .= $post['description'];
                $tooltip .= ($post['value']) ? __(" This article has Twitter Card. Your article looks cool on Twitter.", _CTLPPU_PLUGIN_NAME_) : __(" This article doesn't have Twitter Card. Squirrly Plugin may help you with this. ", _CTLPPU_PLUGIN_NAME_);
                break;

            case 'seo_duplicateOpenGraph':
                $tooltip .= ($post['value']) ? __(" You have duplicate Open Graph. Try to fix it.", _CTLPPU_PLUGIN_NAME_) : __(" Everything looks okay.", _CTLPPU_PLUGIN_NAME_);
                break;

            case 'seo_duplicateTwitterCard':
                $tooltip .= ($post['value']) ? __(" You have duplicate Twitter Card. Try to fix it.", _CTLPPU_PLUGIN_NAME_) : __(" It looks good on Twitter.", _CTLPPU_PLUGIN_NAME_);
                break;

            case 'seo_duplicateTitle':
                $tooltip .= ($post['value']) ? __(" You have duplicate meta title for this article. This is not Google Friendly. ", _CTLPPU_PLUGIN_NAME_) : __(" Article's meta title looks good.", _CTLPPU_PLUGIN_NAME_);
                break;

            case 'seo_duplicateDescription':
                $tooltip .= ($post['value']) ? __(" You have duplicate meta description for this article. This is not Google Friendly. ", _CTLPPU_PLUGIN_NAME_) : __(" Article's meta description looks good.", _CTLPPU_PLUGIN_NAME_);
                break;

            case 'seo_keywordInUrl':
                $tooltip .= ($post['value']) ? __(" You have it. Good job! ", _CTLPPU_PLUGIN_NAME_) : __(" Can't find any keyword in URL. This is not good for SEO.", _CTLPPU_PLUGIN_NAME_);
                break;

            case 'seo_keywordInTitle':
                $tooltip .= ($post['value']) ? __(" You have it. Good job! ", _CTLPPU_PLUGIN_NAME_) : __(" Can't find any keyword in title. This is not good for SEO.", _CTLPPU_PLUGIN_NAME_);
                break;

            case 'seo_friendly':
                $tooltip .= ($post['value']) ? __(" This article is SEO Friendly. ", _CTLPPU_PLUGIN_NAME_) : __(" Article is not SEO Friendly. Edit to solve problem. How about Squirrly Plugin for Wordpress?", _CTLPPU_PLUGIN_NAME_);
                break;

            case 'seo_areShareButtons':
                $tooltip .= $post['description'];
                $tooltip .= ($post['value']) ? __(" Nice! You have them.", _CTLPPU_PLUGIN_NAME_) : __(" You need to add them.", _CTLPPU_PLUGIN_NAME_);
                break;

            case 'blogging_frequency':
                $tooltip .= __(" Your blogging frequency is ", _CTLPPU_PLUGIN_NAME_) . $post['value'];
                break;

            case 'blogging_optimized':
                $tooltip .= __(" Your article is optimized ", _CTLPPU_PLUGIN_NAME_) . $post['value'] . "%";
                break;

            case 'social_facebookShare':
                $tooltip .= ($post['value'] == 0) ? "No one shared your article on Facebook " : $post['value'] . " " . "Facebook Shares";
                break;

            case 'social_facebookLike':
                $tooltip .= ($post['value'] == 0) ? "No one liked your article on Facebook " : $post['value'] . " " . "Facebook likes";
                break;

            case 'social_commentCount':
                $tooltip .= ($post['value'] == 0) ? "There is not engagement on social media. " : $post['value'] . " " . __("comments for this article on social", _CTLPPU_PLUGIN_NAME_);
                break;

            case 'social_linkedinShare':
                $tooltip .= ($post['value'] == 0) ? "No one shared your article on LinkedIn " : $post['value'] . " " . "linked shares";
                break;

            case 'social_plusShare':
                $tooltip .= ($post['value'] == 0) ? "No one shared your article on Google Plus " : $post['value'] . " " . "shares on Google Plus";
                break;

            case 'social_stumbleShare':
                $tooltip .= ($post['value'] == 0) ? "No one shared your article on StumbleUpon " : $post['value'] . " " . "StumbleUpon shares";
                break;

            case 'social_twitterTweets':
                $tooltip .= __("This article got ", _CTLPPU_PLUGIN_NAME_) . $post['value'] . __(" tweets", _CTLPPU_PLUGIN_NAME_);
                break;

            case 'social_twitterShare':
                $tooltip .= ($post['value'] == 0) ? "No one shared your article on Twitter " : $post['value'] . " " . "Twitter shares";
                break;

            case 'social_redditShare':
                $tooltip .= ($post['value'] == 0) ? "No one shared your article on Reddit " : $post['value'] . " " . "Reddit shares";
                break;

            case 'social_pinterestShare':
                $tooltip .= ($post['value'] == 0) ? "No one shared your article on Pinterest " : $post['value'] . " " . "Pinterest shares";
                break;

            case 'social_shares':
                $tooltip .= ($post['value'] == 0) ? "No one shared your article. " : __("This article has ", _CTLPPU_PLUGIN_NAME_) . $post['value'] . " " . " social shares";
                break;

            case 'moz_authority';
                $tooltip .= __("Authority for this article is ", _CTLPPU_PLUGIN_NAME_) . $post['value'];
                break;

            case 'seo_keywordInDescription':
                $tooltip .= ($post['value']) ? __(" You have it. Good job! ", _CTLPPU_PLUGIN_NAME_) : __(" Can't find any keyword in description. This is not good for SEO.", _CTLPPU_PLUGIN_NAME_);
                break;
        }

        return $tooltip;
    }

}
