<?php

namespace WP_Rplg_Google_Reviews\Includes\Core;

class Core {

    public function __construct() {
    }

    public static function get_default_options() {
        return array(
            'view_mode'                 => 'list',
            'pagination'                => '10',
            'text_size'                 => '',
            'min_letter'                => '',
            'disable_user_link'         => false,
            'hide_based_on'             => false,
            'hide_writereview'          => false,
            'hide_reviews'              => false,
            'hide_avatar'               => false,
            'hide_backgnd'              => false,
            'show_round'                => false,
            'show_shadow'               => false,
            'short_last_name'           => false,
            'media'                     => true,
            'reply'                     => true,

            'slider_autoplay'           => true,
            'slider_hide_border'        => false,
            'slider_hide_prevnext'      => false,
            'slider_hide_dots'          => false,
            'slider_text_height'        => '',
            'slider_speed'              => 3,
            'slider_mousestop'          => true,
            'slider_breakpoints'        => '',

            'header_merge_social'       => false,
            'header_hide_social'        => false,
            'header_center'             => false,
            'header_hide_photo'         => false,
            'header_hide_name'          => false,

            'dark_theme'                => false,
            'centered'                  => false,
            'max_width'                 => '',
            'max_height'                => '',
            'style_vars'                => '',

            'open_link'                 => true,
            'nofollow_link'             => true,
            'lazy_load_img'             => true,
            'aria_label'                => false,
            'google_def_rev_link'       => false,
            'reviewer_avatar_size'      => 56,
            'reviews_limit'             => '',
            'hidden'                    => '',
            'cache'                     => 12,
        );
    }

    public function get_reviews($feed, $is_admin = false) {
        $connection = json_decode($feed->post_content);

        if ($is_admin) {
            return $this->get_data($connection, $is_admin);
        }

        $cache_time            = isset($connection->options->cache) ? $connection->options->cache : null;
        $data_cache_key        = 'grw_feed_' . GRW_VERSION . '_' . $feed->ID . '_reviews';
        $connection_cache_key  = 'grw_feed_' . GRW_VERSION . '_' . $feed->ID . '_options';

        $data                  = get_transient($data_cache_key);
        $cached_connection     = get_transient($connection_cache_key);
        $serialized_connection = serialize($connection);

        if ($data === false || $serialized_connection !== $cached_connection || !$cache_time) {
            $expiration = $cache_time;
            switch ($expiration) {
                case '1':
                    $expiration = 3600;
                    break;
                case '3':
                    $expiration = 3600 * 3;
                    break;
                case '6':
                    $expiration = 3600 * 6;
                    break;
                case '12':
                    $expiration = 3600 * 12;
                    break;
                case '24':
                    $expiration = 3600 * 24;
                    break;
                case '48':
                    $expiration = 3600 * 48;
                    break;
                case '168':
                    $expiration = 3600 * 168;
                    break;
                default:
                    $expiration = 3600 * 24;
            }
            $data = $this->get_data($connection, $is_admin);
            set_transient($data_cache_key, $data, $expiration);
            set_transient($connection_cache_key, $serialized_connection, $expiration);
        }
        return $data;
    }

    private function get_ops($connection) {
        foreach ($this->get_default_options() as $field => $value) {
            $connection->options->{$field} = isset($connection->options->{$field}) ? esc_attr($connection->options->{$field}) : $value;
        }
        return $connection->options;
    }

    public function get_data($connection, $is_admin = false) {

        if ($connection == null) {
            return null;
        }

        $options = $this->get_ops($connection);

        $biz = array();
        $reviews = array();

        if (isset($connection->connections) && is_array($connection->connections)) {
            foreach ($connection->connections as $conn) {
                switch ($conn->platform) {
                    case 'facebook':
                        // TODO
                        // break;
                    default:
                        $result = $this->get_db_reviews($conn, $options, $is_admin);
                        if (!$options->header_hide_social) {
                            array_push($biz, $result['business']);
                        }
                        if (!$options->hide_reviews) {
                            $reviews = array_merge($reviews, $result['reviews']);
                        }
                }
            }
        }

        usort($reviews, array($this, 'sort_recent'));

        // Trim reviews limit
        if ($options->reviews_limit > 0) {
            $reviews = array_slice($reviews, 0, $options->reviews_limit);
        }

        return array('businesses' => $biz, 'reviews' => $reviews, 'options' => $options);
    }

    public function get_db_reviews($biz, $options, $is_admin = false) {
        global $wpdb;

        $rating = 0;
        $review_count = 0;
        $reviews = [];

        // Get place
        $place = $wpdb->get_row(
            $wpdb->prepare(
                "SELECT * FROM " . $wpdb->prefix . Database::BUSINESS_TABLE .
                " WHERE place_id = %s", $biz->id
            )
        );

        if ($place) {

            // Get reviews
            $hidden_ids  = [];
            $where_plain = $is_admin ? '' : " AND hide = ''";
            $where_r     = $is_admin ? '' : " AND r.hide = ''";

            if (isset($options->hidden) && !$is_admin) {
                $hidden_ids = $this->parse_hidden_ids($options->hidden);
                if (!empty($hidden_ids)) {
                    $hidden_phs   = implode(',', array_fill(0, count($hidden_ids), '%d'));
                    $where_plain .= ' AND id NOT IN (' . $hidden_phs . ')';
                    $where_r     .= ' AND r.id NOT IN (' . $hidden_phs . ')';
                }
            }

            if (empty($biz->lang)) {

                $sql = "SELECT r.*
                        FROM {$wpdb->prefix}" . Database::REVIEW_TABLE . " r
                        INNER JOIN (
                            SELECT author_url, MAX(time) AS max_time
                            FROM {$wpdb->prefix}" . Database::REVIEW_TABLE . "
                            WHERE google_place_id = %d{$where_plain}
                            GROUP BY author_url
                        ) t
                            ON t.author_url = r.author_url
                           AND t.max_time = r.time
                        WHERE r.google_place_id = %d{$where_r}
                        ORDER BY r.time DESC, r.id DESC";

                $params = array_merge([$place->id], $hidden_ids, [$place->id], $hidden_ids);

            } else {

                $where_plain .= " AND language = %s";

                $sql = "SELECT *
                        FROM {$wpdb->prefix}" . Database::REVIEW_TABLE . "
                        WHERE google_place_id = %d{$where_plain}
                        ORDER BY time DESC";

                $params = array_merge([$place->id], $hidden_ids);
                $params[] = $biz->lang;
            }

            $reviews = $wpdb->get_results($wpdb->prepare($sql, $params));

            // Setup photo
            $place->photo = strlen($biz->photo) > 0 ? $biz->photo : (strlen($place->photo) > 0 ? $place->photo : GRW_GOOGLE_BIZ);

            // Calculate reviews count
            if (isset($place->review_count) && $place->review_count > 0) {
                $review_count = $place->review_count;
            } else {
                $review_count = $wpdb->get_var(
                    $wpdb->prepare(
                        "SELECT count(*) FROM " . $wpdb->prefix . Database::REVIEW_TABLE .
                        " WHERE google_place_id = %d", $place->id
                    )
                );
            }

            // Calculate rating
            $rating = 0;
            if ($place->rating > 0) {
                $rating = $place->rating;
            } else if (count($reviews) > 0) {
                foreach ($reviews as $review) {
                    $rating = $rating + $review->rating;
                }
                $rating = round($rating / count($reviews), 1);
            }
            $rating = number_format((float)$rating, 1, '.', '');
        }

        $business = json_decode(json_encode(
            array(
                'id'                  => $biz->id,
                'name'                => $biz->name ? $biz->name : $place->name,
                'url'                 => isset($place->url) ? $place->url : null,
                'photo'               => isset($place->photo) ? $place->photo : GRW_GOOGLE_BIZ,
                'address'             => isset($place->address) ? $place->address : null,
                'rating'              => $rating,
                'review_count'        => $review_count,
                'provider'            => 'google'
            )
        ));

        $google_reviews = array();
        foreach ($reviews as $rev) {
            if (isset($options->min_letter) && isset($rev->text) && strlen($rev->text) < $options->min_letter) {
                continue;
            }
            $text = isset($rev->text) && strlen($rev->text) > 0 ? nl2br(wp_encode_emoji($rev->text)) : null;
            $review = json_decode(json_encode(
                array(
                    'id'            => $rev->id,
                    'hide'          => $rev->hide,
                    'biz_id'        => $biz->id,
                    'biz_url'       => $place->url,
                    'rating'        => $rev->rating,
                    'text'          => $text,
                    'author_avatar' => $rev->profile_photo_url,
                    'author_url'    => $rev->author_url,
                    'author_name'   => isset($options->short_last_name) && $options->short_last_name ?
                                       $this->get_short_name($rev->author_name) : $rev->author_name,
                    'time'          => $rev->time,
                    'images'        => isset($rev->images) ? $rev->images : null,
                    'reply'         => isset($rev->reply) ? $rev->reply : null,
                    'reply_time'    => isset($rev->reply_time) ? $rev->reply_time : null,
                    'url'           => isset($rev->url) ? $rev->url : null,
                    'provider'      => isset($rev->provider) ? $rev->provider : 'google'
                )
            ));
            array_push($google_reviews, $review);
        }

        return array('business' => $business, 'reviews' => $google_reviews);
    }

    public function get_overview($place_id = 0) {
        global $wpdb;

        // -------------- Get Google place --------------
        $place_sql = "SELECT id, place_id, name, rating, review_count, updated" .
                     " FROM " . $wpdb->prefix . Database::BUSINESS_TABLE .
                     " WHERE rating > 0 AND review_count > 0" . ($place_id > 0 ? ' AND id = %d' : '') .
                     " ORDER BY id DESC";

        $places = $place_id > 0 ?
                  // Query for specific Google place
                  $wpdb->get_results($wpdb->prepare($place_sql, sanitize_text_field(wp_unslash($place_id)))) :
                  // Query for summary (all places)
                  $wpdb->get_results($place_sql);

        $count = count($places);
        if ($count < 1) {
            return null;
        }

        $rating = 0;
        $review_count = 0;
        $google_places = array();
        $google_place_ids = array();

        foreach ($places as $place) {
            $id = $place->id;
            $name = $place->name;
            $rating += $place->rating;
            $review_count += $place->review_count;

            array_push($google_place_ids, $place->id);
            array_push($google_places, json_decode(json_encode(array('id' => $place->id, 'name' => $place->name, 'updated' => $place->updated))));
        }

        if ($count > 1) {
            $rating = round($rating / $count, 1);
            $rating = number_format((float)$rating, 1, '.', '');
            array_unshift($google_places, json_decode(json_encode(array('id' => 0, 'name' => 'Summary for all places'))));
        }

        // -------------- Get Google reviews --------------
        $google_reviews = array();

        $reviews = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT * FROM " . $wpdb->prefix . Database::REVIEW_TABLE .
                " WHERE google_place_id IN (" . implode(', ', array_fill(0, count($google_place_ids), '%d')) . ")" .
                " ORDER BY time DESC LIMIT 10",
                $google_place_ids
            )
        );

        foreach ($reviews as $rev) {
            $review = json_decode(json_encode(
                array(
                    'id'            => $rev->id,
                    'hide'          => $rev->hide,
                    'rating'        => $rev->rating,
                    'text'          => $rev->text,
                    'author_url'    => $rev->author_url,
                    'author_name'   => $rev->author_name,
                    'time'          => $rev->time,
                )
            ));
            array_push($google_reviews, $review);
        }

        // -------------- Get Google stats --------------
        $stats = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT * FROM " . $wpdb->prefix . Database::STATS_TABLE .
                " WHERE google_place_id IN (" . implode(', ', array_fill(0, count($google_place_ids), '%d')) . ")" .
                " ORDER BY id DESC LIMIT 10000",
                $google_place_ids
            )
        );

        // -------------- Get min/max stats values --------------
        $stats_minmax = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT t1.* FROM " . $wpdb->prefix . Database::STATS_TABLE . " t1" .
                " JOIN (" .
                    "SELECT min(time) AS min_value, max(time) AS max_value, google_place_id FROM " . $wpdb->prefix . Database::STATS_TABLE .
                    " WHERE google_place_id IN (" . implode(', ', array_fill(0, count($google_place_ids), '%d')) . ")" .
                    " GROUP BY google_place_id" .
                ") AS t2 ON t1.google_place_id = t2.google_place_id AND (t1.time = t2.min_value OR t1.time = t2.max_value)",
                $google_place_ids
            )
        );

        return
            array(
                'rating'       => $rating,
                'review_count' => $review_count,
                'places'       => $google_places,
                'reviews'      => $google_reviews,
                'stats'        => $stats,
                'stats_minmax' => $stats_minmax
            );
    }

    public function merge_biz($businesses, $id = '', $name = '', $url = '', $photo = '', $provider = '') {
        $count = 0;
        $rating = 0;
        $review_count = array();
        $review_count_manual = array();
        $business_platform = array();
        $biz_merge = null;
        foreach ($businesses as $business) {
            if ($business->rating < 1) {
                continue;
            }

            $count++;
            $rating += $business->rating;

            if (isset($business->review_count_manual) && $business->review_count_manual > 0) {
                $review_count_manual[$business->id] = $business->review_count_manual;
            } else {
                $review_count[$business->id] = $business->review_count;
            }

            array_push($business_platform, $business->provider);

            if ($biz_merge == null) {
                $biz_merge = json_decode(json_encode(
                    array(
                        'id'           => strlen($id)       > 0 ? $id       : $business->id,
                        'name'         => strlen($name)     > 0 ? $name     : $business->name,
                        'url'          => strlen($url)      > 0 ? $url      : $business->url,
                        'photo'        => strlen($photo)    > 0 ? $photo    : $business->photo,
                        'provider'     => strlen($provider) > 0 ? $provider : $business->provider,
                        'review_count' => 0,
                    )
                ));
            }
            $rating_tmp = round($rating / $count, 1);
            $rating_tmp = number_format((float)$rating_tmp, 1, '.', '');
            $biz_merge->rating = $rating_tmp;
        }
        $review_count = array_merge($review_count, $review_count_manual);
        foreach ($review_count as $id => $count) {
            $biz_merge->review_count += $count;
        }
        $biz_merge->platform = array_unique($business_platform);
        return $biz_merge;
    }

    private function get_short_name($author_name){
        $names = explode(" ", $author_name);
        if (count($names) > 1) {
            $last_index = count($names) - 1;
            $last_name = $names[$last_index];
            if ($this->_strlen($last_name) > 1) {
                $last_char = $this->_substr($last_name, 0, 1);
                $last_name = $this->_strtoupper($last_char) . ".";
                $names[$last_index] = $last_name;
                return implode(" ", $names);
            }
        }
        return $author_name;
    }

    private function sort_recent($a, $b) {
        return $b->time - $a->time;
    }

    private function parse_hidden_ids($input) {
        $ids = array();
        if (empty($input)) {
            return $ids;
        }
        if (is_string($input)) {
            $parts = preg_split('/\s*,\s*/', $input, -1, PREG_SPLIT_NO_EMPTY);
        } elseif (is_array($input)) {
            $parts = $input;
        } else {
            return $ids;
        }
        foreach ($parts as $p) {
            $val = intval($p);
            if ($val > 0) {
                $ids[] = $val;
            }
        }
        $ids = array_values(array_unique($ids));
        return $ids;
    }

    private function _strlen($str) {
        return function_exists('mb_strlen') ? mb_strlen($str, 'UTF-8') : strlen($str);
    }

    private function _substr($str, $start, $length = NULL) {
        return function_exists('mb_substr') ? mb_substr($str, $start, $length, 'UTF-8') : substr($str, $start, $length);
    }

    private function _strtoupper($str) {
        return function_exists('mb_strtoupper') ? mb_strtoupper($str, 'UTF-8') : strtoupper($str);
    }

}