<?php

class CTLPPU_Models_Posts extends CTLPPU_Models_Abstract_Models
{

    protected $_options;
    protected $_fields_source;

    function __construct()
    {
        parent::__construct();

        if (!isset($this->_options))
            $this->_options = (object)CTLPPU_Classes_Tools::getOptions();

        $this->_setFieldsSource();
    }

    public function findPostMeta($where = array())
    {
        if (!isset($where)) {
            return false;
        }
        foreach (array_keys($where) as $field) {
            if (isset($this->_wpdb->field_types[$field])) {
                $form = $this->_wpdb->field_types[$field];
            } else {
                $form = '%s';
            }
            $wheres[] = "$field = $form";
        }

        if ($rs = $this->_wpdb->get_row($this->_wpdb->prepare("SELECT *
                FROM " . $this->_wpdb->postmeta .
            " WHERE " . implode(' AND ', $wheres), $where))
        ) {
            return $rs;
        }
        return false;
    }

    public function hasSettingsChanged()
    {
        if (!empty($this->_options)) {
            if (md5(serialize($this->_options->ctlppu_display_fields)) == $this->_options->fields_hash) {
                return true;
            }
            return false;
        }
    }

    public function hasUpdatedPosts()
    {
        if (!empty($this->_options)) {
            if ((isset($this->_options->last_update) && $this->_options->last_update > strtotime('-' . ctlppu_get_update_frequency()) || $this->_options->last_update != 0)

            ) {
                //Has updated posts data
                return true;
            } else {
                //need an update
                return false;
            }
        }
        return false;
    }

    public function getSavePostsArgs()
    {
        $paths = array();
        if ($posts = $this->findAll(array("post_status" => "publish", "post_type" => "post"))) {

            $site_address = get_site_url();

            foreach ($posts as $post) {
                if (get_the_permalink($post->ID) <> "") {
                    $paths[] = array(
                        "post_id" => $post->ID,
                        "path" => str_replace($site_address, '', get_the_permalink($post->ID)),
                        "post_date" => strtotime($post->post_date));
                }
            }
            return array(
                "website_id" => $this->_options->website_id,
                "posts" => json_encode($paths),

            );

        }
        return false;
    }

    public function findAll($where = array(), $limit = 60)
    {
        if (!isset($where)) {
            return false;
        }

        foreach (array_keys($where) as $field) {
            if (isset($this->_wpdb->field_types[$field])) {
                $form = $this->_wpdb->field_types[$field];
            } else {
                $form = '%s';
            }
            $wheres[] = "$field = $form";
        }
        //Set the limit of articles
        if ($limit == 0) {
            $limit = "";
        } else {
            $limit = " LIMIT $limit";
        }

        $order = "ORDER BY post_modified DESC";


        if ($rs = $this->_wpdb->get_results($this->_wpdb->prepare("SELECT *
                FROM " . $this->_wpdb->posts .
                " WHERE " . implode(' AND ', $wheres), $where) . $order . $limit)
        ) {
            return $rs;
        }
        return false;
    }

    /**
     * @param array $posts_data
     * @return array|bool
     */
    public function mergeFields($posts_data = array())
    {
        if (empty($posts_data))
            return false;


        if (!isset($this->_fields_source))
            $this->_setFieldsSource();

        $merged = array();
        foreach ($this->_options->ctlppu_display_fields as $field) {
            $field_prefix = explode("_", $field, 2)[0];
            $merged [$field] = $this->_fields_source->$field_prefix->columns[$field];
        }

        foreach ($posts_data as $index => &$post) {
            foreach ($post as $key => $field) {
                if (array_key_exists($key, $merged)) {
                    $merged[$key]['value'] = $post[$key];
                    $post[$key] = array();

                    if ($merged[$key]['enabled'])
                        array_push($post[$key], $merged[$key]);

                    $post[$key] = current($post[$key]);
                }
            }
        }


        return $posts_data;

    }

    function searchByFieldName($name, $array)
    {
        foreach ($array as $key => $val) {
            if ($key === $name) {
                return $val;
            }
        }
        return false;
    }


    public function getFieldsSource()
    {
        if (!isset($this->_fields_source))
            $this->_setFieldsSource();

        return $this->_fields_source;
    }

    protected function _setFieldsSource()
    {

        $this->_fields_source = (object)
        array(
            /**
             * SEO Columns
             */
            "seo" => (object)array(
                "title" => "SEO",
                "description" => __("SEO Data", _CTLPPU_PLUGIN_NAME_),
                "enabled" => true,
                "columns" => array(
                    "seo_speed" => array(
                        "enabled" => true,
                        "subcategory" => "content",
                        "title" => __("Page speed", _CTLPPU_PLUGIN_NAME_),
                        "icon" => "tachometer",
                        "type" => "float",
                        "description" => __("represents the loading page time for this article", _CTLPPU_PLUGIN_NAME_)

                    ),
                    "seo_gzip" => array(
                        "enabled" => true,
                        "subcategory" => "seo",
                        "title" => __("Gzip", _CTLPPU_PLUGIN_NAME_),
                        "icon" => "file-archive-o",
                        "type" => "bool",
                        "description" => __("gzip is a file format and a software application used for file compression and decompression. ", _CTLPPU_PLUGIN_NAME_)
                    ),
                    "seo_keywords" => array(
                        "enabled" => true,
                        "subcategory" => "content",
                        "title" => __("Keywords", _CTLPPU_PLUGIN_NAME_),
                        "icon" => "key",
                        "type" => "keyword",
                        "description" => __("Your SEO keywords are the key words and phrases in your web content that make it possible for people to find your site via search engines.", _CTLPPU_PLUGIN_NAME_)
                    ),
                    "seo_description" => array(
                        "enabled" => true,
                        "subcategory" => "content",
                        "title" => __("Desciption", _CTLPPU_PLUGIN_NAME_),
                        "icon" => "font",
                        "type" => "string",
                        "description" => __("A meta description is an HTML and XHTML element that describes your page to search engines.", _CTLPPU_PLUGIN_NAME_)
                    ),
                    "seo_metaOpenGraph" => array(
                        "enabled" => true,
                        "subcategory" => "seo",
                        "title" => __("Meta Open Graph", _CTLPPU_PLUGIN_NAME_),
                        "icon" => "users",
                        "type" => "bool",
                        "description" => __("The Open Graph protocol enables any web page to become a rich object in a social graph.", _CTLPPU_PLUGIN_NAME_),
                    ),
                    "seo_metaTwitterCard" => array(
                        "enabled" => true,
                        "subcategory" => "seo",
                        "title" => __("Twitter Card", _CTLPPU_PLUGIN_NAME_),
                        "icon" => "twitter-square",
                        "type" => "bool",
                        "description" => __("With Twitter Cards, you can attach rich photos, videos and media experience to Tweets that drive traffic to your website", _CTLPPU_PLUGIN_NAME_),
                    ),
                    "seo_duplicateOpenGraph" => array(
                        "enabled" => true,
                        "subcategory" => "seo",
                        "title" => __("Duplicate Open Graph", _CTLPPU_PLUGIN_NAME_),
                        "icon" => "files-o",
                        "type" => "bool"
                    ),
                    "seo_duplicateTwitterCard" => array(
                        "enabled" => true,
                        "subcategory" => "seo",
                        "title" => __("Duplicate Twitter Card", _CTLPPU_PLUGIN_NAME_),
                        "icon" => "twitter",
                        "type" => "bool"
                    ),
                    "seo_duplicateTitle" => array(
                        "enabled" => true,
                        "subcategory" => "seo",
                        "title" => __("Duplicate Title", _CTLPPU_PLUGIN_NAME_),
                        "icon" => "th",
                        "type" => "bool"

                    ),
                    "seo_duplicateDescription" => array(
                        "enabled" => true,
                        "subcategory" => "seo",
                        "title" => __("Duplicate Description", _CTLPPU_PLUGIN_NAME_),
                        "icon" => "th",
                        "type" => "bool"
                    ),
                    "seo_keywordInUrl" => array(
                        "enabled" => true,
                        "subcategory" => "content",
                        "title" => __("Keyword in URL", _CTLPPU_PLUGIN_NAME_),
                        "icon" => "key",
                        "type" => "bool"
                    ),
                    "seo_keywordInTitle" => array(
                        "enabled" => true,
                        "subcategory" => "content",
                        "title" => __("Keyword in title", _CTLPPU_PLUGIN_NAME_),
                        "icon" => "key",
                        "type" => "bool"
                    ),
                    "seo_keywordInDescription" => array(
                        "enabled" => true,
                        "subcategory" => "content",
                        "title" => __("Keyword in description", _CTLPPU_PLUGIN_NAME_),
                        "icon" => "key",
                        "type" => "bool"
                    ),
                    "seo_friendly" => array(
                        "enabled" => true,
                        "subcategory" => "content",
                        "title" => __("SEO Friendly", _CTLPPU_PLUGIN_NAME_),
                        "icon" => "smile-o",
                        "type" => "bool"
                    ),
                    "seo_areShareButtons" => array(
                        "enabled" => true,
                        "subcategory" => "seo",
                        "title" => __("Share Buttons", _CTLPPU_PLUGIN_NAME_),
                        "icon" => "share-alt-square",
                        "type" => "bool",
                        "description" => __("ShareThis social media buttons and widgets for publisher websites to drive engagement and consumer sharing behavior across social networks.", _CTLPPU_PLUGIN_NAME_)
                    ),

                )
            ),

            /**
             * Blogging Columns
             */

            "blogging" => (object)array(
                "title" => "Blogging",
                "description" => __("About blogging", _CTLPPU_PLUGIN_NAME_),
                "enabled" => true,
                "columns" => array(
                    "blogging_frequency" => array(
                        "enabled" => true,
                        "subcategory" => "content",
                        "title" => __("Blogging Frequency", _CTLPPU_PLUGIN_NAME_),
                        "icon" => "pencil",
                        "type" => "int"
                    ),
                    "blogging_optimized" => array(
                        "enabled" => true,
                        "subcategory" => "content",
                        "title" => __("SEO Optimization Score", _CTLPPU_PLUGIN_NAME_),
                        "icon" => "check-circle-o",
                        "type" => "int"
                    )
                )
            ),

            /**
             * Authority Columns
             */

            "authority" => (object)array(
                "title" => "Authority",
                "description" => __("About Authority", _CTLPPU_PLUGIN_NAME_),
                "enabled" => false,
                "columns" => array(
                    "moz_authority" => array(
                        "enabled" => true,
                        "subcategory" => "analysis",
                        "title" => __("Moz Authority", _CTLPPU_PLUGIN_NAME_),
                        "icon" => "th",
                        "type" => "int"
                    ),
                )
            ),
            /**
             * Social Columns
             */
            "social" => (object)array(
                "title" => "Social",
                "description" => __("Your Social Media status", _CTLPPU_PLUGIN_NAME_),
                "enabled" => false,
                "columns" => array(
                    "social_facebookShare" => array(
                        "enabled" => true,
                        "subcategory" => false,
                        "title" => __("Facebook Share", _CTLPPU_PLUGIN_NAME_),
                        "icon" => "share",
                        "type" => "int"
                    ),
                    "social_facebookLike" => array(
                        "enabled" => true,
                        "subcategory" => false,
                        "title" => __("Facebook like", _CTLPPU_PLUGIN_NAME_),
                        "icon" => "thumbs-up",
                        "type" => "int"
                    ),
                    "social_commentCount" => array(
                        "enabled" => true,
                        "subcategory" => false,
                        "title" => __("Comment Count", _CTLPPU_PLUGIN_NAME_),
                        "icon" => "comment",
                        "type" => "int"
                    ),
                    "social_linkedinShare" => array(
                        "enabled" => true,
                        "subcategory" => false,
                        "title" => __("Linked Share", _CTLPPU_PLUGIN_NAME_),
                        "icon" => "linkedin",
                        "type" => "int"
                    ),
                    "social_plusShare" => array(
                        "enabled" => true,
                        "subcategory" => false,
                        "title" => __("Google Plus Shares", _CTLPPU_PLUGIN_NAME_),
                        "icon" => "google-plus",
                        "type" => "int"
                    ),
                    "social_stumbleShare" => array(
                        "enabled" => true,
                        "subcategory" => false,
                        "title" => __("Stumble Share", _CTLPPU_PLUGIN_NAME_),
                        "icon" => "stumbleupon-circle",
                        "type" => "int"
                    ),
                    "social_twitterTweets" => array(
                        "enabled" => true,
                        "subcategory" => false,
                        "title" => __("Number of tweets", _CTLPPU_PLUGIN_NAME_),
                        "icon" => "twitter-square",
                        "type" => "int"
                    ),
                    "social_twitterShare" => array(
                        "enabled" => true,
                        "subcategory" => false,
                        "title" => __("Twitter Shares", _CTLPPU_PLUGIN_NAME_),
                        "icon" => "retweet",
                        "type" => "int"
                    ),
                    "social_redditShare" => array(
                        "enabled" => true,
                        "subcategory" => false,
                        "title" => __("Reddit Shares", _CTLPPU_PLUGIN_NAME_),
                        "icon" => "reddit",
                        "type" => "int"
                    ),
                    "social_pinterestShare" => array(
                        "enabled" => true,
                        "subcategory" => false,
                        "title" => __("Pinterest Shares", _CTLPPU_PLUGIN_NAME_),
                        "icon" => "pinterest-p",
                        "type" => "int"
                    ),
                    "social_shares" => array(
                        "enabled" => true,
                        "subcategory" => false,
                        "title" => __("Total Shares", _CTLPPU_PLUGIN_NAME_),
                        "icon" => "share-alt-square",
                        "type" => "int"
                    ),
                )
            ),

            /**
             * Inbound Columns
             */
            "inbound" => (object)array(
                "title" => "Inbound",
                "description" => __("Your Inbound Links", _CTLPPU_PLUGIN_NAME_),
                "enabled" => false,
                "columns" => array(
                    "inbound_links" => array(
                        "enabled" => true,
                        "subcategory" => false,
                        "title" => __("Number of Inbounds", _CTLPPU_PLUGIN_NAME_),
                        "icon" => "link",
                        "type" => "int"
                    ),
                )
            ),
        );
    }

    public function count_format($n, $point = '.', $sep = ',')
    {
        if ($n < 0)
            return 0;

        if ($n < 10000)
            return number_format($n, 0, $point, $sep);

        $d = $n < 1000000 ? 1000 : 1000000;
        $f = round($n / $d, 1);

        return number_format($f, $f - intval($f) ? 1 : 0, $point, $sep) . ($d == 1000 ? 'k' : 'M');
    }

}